多个请求对应一个Servlet的方法

*多个请求对应一个Servlet的方法:
1.一种方便添加新方法的方式:
1).JSP代码:

<a href="addCustomer.do">Add</a><br><br>
<a href="query.do">Query</a><br><br>

2).Servlet映射地址:

@WebServlet("*.do")

3).doGet和doPost方法:
 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			doPost(request, response);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		//1.获取ServletPath:/update.do或addCustomer.do 
		String servletPath=req.getServletPath();
		//2.去除/ 和.do ,得到类似于update 或addCustomer 这样的字符串
		String methodName=servletPath.substring(1);
		methodName=methodName.substring(0, methodName.length()-3);
		
		/*
		 * 方便添加新方法,直接获取请求的映射地址对应的方法执行。
		
		 */
		try {   
			//3.利用反射获取methodName 对应的方法
			Method method=getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
		
			//4.利用反射调用对应的方法。
			method.invoke(this,req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			
			//5.遇到错误可以直接返回错误提示页面
			resp.sendRedirect("error.jsp");
		} 
	}

2.另一种方法:(麻烦) 容易泄露信息

 1).JSP:

 

 
 <a href="customerServlet?method=add">Add</a>

2).Servlet映射地址:

 

@WebServlet("/customerServlet")

3).
doPost:

 

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String method=request.getParameter("method");
		switch (method) {
		case "add":
			add(request,response);
			break;
		case "query":
			query(request,response);
			break;
		case "delete":
			delete(request,response);
			break;
		case "update":
			update(request,response);
			break;
		default:
			break;
		}	
	}

对应的方法:

 

private void update(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
		System.out.println("update");	
	}
	private void delete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
		System.out.println("delete");
	}
	private void query(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
		System.out.println("query");		
	}
	private void addCustomer(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
		System.out.println("add");		
	}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值