• 一个Servlet中可以有多个处理请求的方法


    BaseServlet

      一个请求写一个Servlet太过复杂和麻烦,我们希望在一个Servlet中可以有多个处理请求的方法。

      客户端发送请求时,必须给出一个参数,用来说明要调用的方法

      方法的结构和service()方法的结构一样

    初始版

      当我们访问Servlet时,发生了那些操作?

      首先是通过<url-pattern>找到<servlet-name>,通过<serlvet-name>最终找到<servlet-class>,也就是类名,在通过反射得到Serlvet对象。

      再由tomcat调用init()、service()、destroy()方法,这一过程是Servlet的生命周期。在HttpServlet里有个service()的重载方法。ServletRequest、ServletResponse经过service(ServletRequest req,ServletResponse resp)方法转换成Http格式的。再在service(HttpServletRequest req,HttpServletResponse resp)中调用doGet()或者doPost()方法。

      路径:http://localhost:8080/baseservlet/base?method=addUser

    public class BaseServlet extends HttpServlet{
    
    	@Override
    	protected void service(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		String method = req.getParameter("method");//获取要调用的方法,其中的value="method"是自己约定的
    		if("addUser".equals(method)){
    			addUser(req,resp);
    		}
    		if("deleteUser".equals(method)){
    			deleteUser();
    		}
    	}
    
    	private void deleteUser() {
    		System.out.println("deleteUser()");
    	}
    
    	private void addUser(HttpServletRequest req, HttpServletResponse resp) {
    		System.out.println("add()");
    		
    	}
    	
    }
    

     改进版

      很显然,上面的代码不是我们想要的。

    public class BaseServlet extends HttpServlet{
    
    	@Override
    	protected void service(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		String name = req.getParameter("method");//获取方法名
    		if(name == null || name.isEmpty()){
    			throw new RuntimeException("没有传递method参数,请给出你想调用的方法");
    		}
    		Class c = this.getClass();//获得当前类的Class对象
    		Method method = null;
    		try {
    			//获得Method对象
    			method =  c.getMethod(name, HttpServletRequest.class,HttpServletResponse.class);
    		} catch (Exception e) {
    			throw new RuntimeException("没有找到"+name+"方法,请检查该方法是否存在");
    		}
    		
    		try {
    			method.invoke(this, req,resp);//反射调用方法
    		} catch (Exception e) {
    			System.out.println("你调用的方法"+name+",内部发生了异常");
    			throw new RuntimeException(e);
    		}
    		
    	}
    }
    

    在项目中,用一个Servlet继承该BaseServlet就可以实现多个请求处理。  

    部分资料来源网络

  • 相关阅读:
    解决360浏览器兼容模式的页面显示问题
    .NET知识点汇总
    C# 6.0新加特性
    C# 5.0新加特性
    C# 4.0新加特性
    C# 3.0新加特性
    C# 2.0新加特性
    C#中null、""、string.empty区别
    C#使用SQLite
    页面 关于处理如何点击按钮实现定位到某一位置操作
  • 原文地址:https://www.cnblogs.com/ckui/p/6002029.html
Copyright © 2020-2023  润新知