关于多个请求调用同一个Servlet

 1 package com.ouyang.dao;
 2 
 3 import java.io.IOException;
 4 import java.lang.reflect.InvocationTargetException;
 5 import java.lang.reflect.Method;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 import org.apache.catalina.filters.AddDefaultCharsetFilter;
14 
15 @WebServlet("*.do")
16 public class CustomerServlet extends HttpServlet {
17     private static final long serialVersionUID = 1L;
18 
19     protected void doGet(HttpServletRequest request,
20             HttpServletResponse response) throws ServletException, IOException {
21         doPost(request, response);
22     }
23 
24     protected void doPost(HttpServletRequest request,
25             HttpServletResponse response) throws ServletException, IOException {
26 
27         String servletPath = request.getServletPath();
28 
29         String methodName = servletPath.substring(1, servletPath.length() - 3);
30 
31         try {
32             Method method = getClass().getDeclaredMethod(methodName,
33                     HttpServletRequest.class, HttpServletResponse.class);
34             method.invoke(this, request, response);
35         } catch (Exception e) {
36             e.printStackTrace();
37         }
38 
39     }
40 
41     private void add(HttpServletRequest request, HttpServletResponse response) {
42         System.out.println("add");
43 
44     }
45 
46     private void query(HttpServletRequest request, HttpServletResponse response) {
47         System.out.println("query");
48 
49     }
50 
51     private void delete(HttpServletRequest request, HttpServletResponse response) {
52         System.out.println("delete");
53 
54     }
55 }
View Code
 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <a href="add.do">Add</a>
11     <br>
12     <br>
13 
14     <a href="query.do">Query</a>
15     <br>
16     <br>
17 
18     <a href="delete.do">Delete</a>
19     <br>
20     <br>
21 
22 </body>
23 </html>
View Code

难点有二:
  1.url-pattern 采用" .do   "来映射

  2.采用反射机制调用对应的方法

优点:

  1.便于维护

转载于:https://www.cnblogs.com/Ouyangan/p/4189119.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值