一、为什么要使用一个Servlet来处理多个请求?
当浏览器发送了一次请求到服务器时,servlet容器会根据请求的url-pattern找到对应的Servlet类,执行对应的doPost或doGet方法,再将响应信息返回给浏览器,这种情况下,一个具体的Servlet类只能处理对应的web.xml中配置的url-pattern请求,一个Servlet类,一对配置信息。如果业务扩展,需要三个Servlet来处理请求,就需要再加上两个具体的Servlet类,两对配置信息,如果继续向上扩展,是不是会认为如此写法的效率非常低下?并且会浪费更多的资源?
为了避免重复的操作(多次编写配置文件,多次新建具体的Servlet类)影响效率,就衍生出一套简单的操作来提高效率,一次配置,多次使用;一个Servlet具体类,处理多个请求。
二、如何使用一个Servlet来处理多个请求?
首先聊聊解决思路,有两种方法。一是根据请求的地址,截取其中的具体方法名,然后使用if-else判断匹配,再执行具体的方法。二是根据截取出来的方法名,使用反射机制,来执行具体的方法。
第一种方案很笨拙,需要不断的使用if-else来判断。第二种方法相对来讲,灵活的处理了原先需要使用if-else的判断逻辑,由类根据方法名自主去执行。
1、新建一个Maven项目,建好一个Servlet类
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取请求的URI地址信息 String url = request.getRequestURI();
// 截取其中的方法名 String methodName = url.substring(url.lastIndexOf("/")+1, url.lastIndexOf("."));
Method method = null;
try {
// 使用反射机制获取在本类中声明了的方法 method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
// 执行方法 method.invoke(this, request, response);
} catch (Exception e) {
throw new RuntimeException("调用方法出错!");
}
}
private void queryEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("执行查询员工的方法...");
response.setContentType("text/html;charset=utf8");
PrintWriter pw = response.getWriter();
pw.println("<h1>查询员工的方法</h1>");
pw.flush();
pw.close();
}
private void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("执行新增员工的方法...");
response.setContentType("text/html;charset=utf8");
PrintWriter pw = response.getWriter();
pw.println("<h1>新增员工的方法</h1>");
pw.flush();
pw.close();
}
private void deleteEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("执行删除员工的方法...");
response.setContentType("text/html;charset=utf8");
PrintWriter pw = response.getWriter();
pw.println("<h1>删除员工的方法</h1>");
pw.flush();
pw.close();
}
private void queryEmpList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("执行查询所有员工的方法...");
response.setContentType("text/html;charset=utf8");
PrintWriter pw = response.getWriter();
pw.println("<h1>查询所有员工的方法</h1>");
pw.flush();
pw.close();
}
}
2、配置web.xml文件信息
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>servlet.CustomerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
转载自: https://blog.youkuaiyun.com/codeMas/article/details/80696777