多个请求对应一个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");		
	}
阅读更多
个人分类: Servlet
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭