当浏览器发送了一次请求到服务器时,servlet容器会根据请求的url-pattern找到对应的Servlet类,执行对应的doPost或doGet方法,再将响应信息返回给浏览器,这种情况下,一个Servlet类,一对配置信息。多个业务, 就需要多个Servert类, 效率太低下, 实际上我们是可以通过一个Servlet类实现多个业务请求的
这里通过类的反射机制及invoke方法来实现一Servlet类多请求的操作实例
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Method; @WebServlet(name = "ServletDoMore", value = "/domore/*") public class ServletDoMore extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取请求的URI地址信息 String url = request.getRequestURI(); // 截取其中的方法名 String methodName = url.substring(url.lastIndexOf("/")+1); System.out.println(methodName); // 使用反射机制获取在本类中声明了的方法 Method method = null; try { method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); method.invoke(this, request, response); } catch (Exception e) { System.out.println("方法不存在"); } } private void add(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{ System.out.println("添加表单"); } private void addsave(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{ System.out.println("信息保存"); } private void update(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{ System.out.println("修改表单"); } private void updatesave(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{ System.out.println("修改保存"); } private void index(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{ System.out.println("信息列表"); } }
请求不同的地址如下就会访问对应的方法
http://localhost/domore/add http://localhost/domore/addsave http://localhost/domore/update http://localhost/domore/updatesave http://localhost/domore/index