关于servlet抽取,以及getMethod方法的参数

下面是一个有主页面跳转到注册页面的过程

一,这个是前端页面的跳转链接(有人要说为什么不直接给路径,我也蒙住了,为什么)

<li><a href="${pageContext.request.contextPath}/user?method=registUI">注册</a></li>

二,这是一个抽取出的通用的servlet(页面请求经过的第一个servlet,所有页面请求必须经过的一个servlet, baseservlet)

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {

            //1.获取方法名称
            String mName = request.getParameter("method");
          
            //2.获取方法对象
            Method method = this.getClass().getMethod(mName,HttpServletRequest.class,HttpServletResponse.class);
           
            //3.让方法执行,接受返回值
            String path = (String) method.invoke(this, request,response);
           
            //4.判断返回值是否为空,若不为空,统一处理请求转发
            if(null != path) {
                request.getRequestDispatcher(path).forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

三,这是一个具体执行某类操作的servlet(我这里是执行用户注册的servlet,页面请求经过的第二个servlet,userservlet)

public String registUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return "/jsp/register.jsp";
    }


如上整个过程就完了,现在我们来看看其中的重点:

1,getMethod方法:

第一个参数是“方法名称”

第二个参数是“方法参数的类对象”//这个就是为什么他是.class的原因,为什么参数是类对象?因为这个是Java规定的,没有原因!!!

2,红色标注的是说白了都是只那个跳转的registerUI()方法



以上属于个人拙见,凡有错误恳请大神指点!


猜你喜欢

转载自blog.csdn.net/w6655515/article/details/78504336