大二寒假作业之JavaWeb

今日学习了使用反射的方法调用Servlet类的函数来简化dopost函数中的代码量,优化逻辑的方法。

在servlet类中写上我们要调用的函数

public void findPassAndId(HttpServletRequest req, HttpServletResponse resp)
    {
        studentdate=studentdao.qrStudentByPassAndId("123456789","20194073");
        System.out.println(studentdate.getStudentname());
    }
    public void findListClass(HttpServletRequest req, HttpServletResponse resp)
    {
        liststudentdate=studentdao.qrStudentListByClass("信1905-1");
        for(StudentDate studate:liststudentdate)
        {
            System.out.println(studate.getStudentid());
        }
    }

在dopost函数中我们通过获取jsp页面传入servlet层的函数名然后利用Method对象获取函数并调用,这样就使得逻辑清晰,减少了dopost中的代码量。

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        String action=req.getParameter("action");
        try {
            Method method=this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

 我们可以将doPost写在BaseServlet中这样其他的Servlet只要继承BaseServlet就可以,只需要写对应的函数。

原文地址:https://www.cnblogs.com/fengchuiguobanxia/p/14322668.html