Java chooses the corresponding method in servlet through reflection mechanism

Keywords: Java JSP encoding JavaEE xml

This method is used to select the corresponding method in the servlet by the corresponding name in Javaee development.

Note: The main code is as follows

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * This is the problem of setting up browser encoding
         */
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html,charset=UTF-8");
        
        String servletPath = req.getServletPath();
        String methodName = servletPath.substring(1);
        methodName = methodName.substring(0, methodName.length()-4);
        System.out.println(methodName);
        
        try {
            /**
             * Selection of servlet corresponding method based on reflection mechanism
             */
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
                    HttpServletResponse.class);
            /**
             * Call the corresponding method with reflection
             */
            method.invoke(this, req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Here's where the reflection mechanism went wrong when you logged in!");
            req.getRequestDispatcher("error.jsp").forward(req, resp);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

Example

Note: Submitting action="<%=request.getContextPath()%>/saveTeacher.ado" in the form form form on the subsequent jsp page can directly invoke the saveTeacher method in the servlet through the reflection mechanism.

public class AdministratorsServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * This is the problem of setting up browser encoding
         */
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html,charset=UTF-8");
        
        String servletPath = req.getServletPath();
        String methodName = servletPath.substring(1);
        methodName = methodName.substring(0, methodName.length()-4);
        System.out.println(methodName);
        
        try {
            /**
             * Selection of servlet corresponding method based on reflection mechanism
             */
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
                    HttpServletResponse.class);
            /**
             * Call the corresponding method with reflection
             */
            method.invoke(this, req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Here's where the reflection mechanism went wrong when you logged in!");
            req.getRequestDispatcher("error.jsp").forward(req, resp);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    
    /**
     * Basic Operation for Teachers    
     */
    
    /**
     * Add a teacher
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void saveTeacher(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Teachers teacher = new Teachers();
            teacher.setTeacherId(Integer.parseInt(req.getParameter("teacherId")));
            teacher.setTeacherName(req.getParameter("teacherName"));
            teacher.setSex(req.getParameter("sex"));
            teacher.setPhoneNo(req.getParameter("phoneNo"));
            teacher.setAddress(req.getParameter("address"));
            teacher.setBirthday(new Date(new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("birthday")).getTime()));
            teacher.setSalary(new BigDecimal(req.getParameter("salary")));
            ITeachersService teacherService = new TeachersServiceImpl();
            int rows = teacherService.save(teacher);
            if(rows>0) {
                System.out.println("Success in preserving a teacher's basic information!");
                req.getRequestDispatcher("saveSuccess.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Failed to add basic information about a teacher object!");
            resp.sendRedirect("error.jsp");
        }

    }
}

First, configure the relevant information in the web.xml file as follows

Note: * in <url-pattern>*.ado</url-pattern> represents the selected corresponding method
<servlet>
      <servlet-name>AdministratorsServlet</servlet-name>
      <servlet-class>cn.gbb.student_achievement_system.controller.AdministratorsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>AdministratorsServlet</servlet-name>
      <url-pattern>*.ado</url-pattern>
  </servlet-mapping>

2. When submitting from form in jsp page, we need to pay attention to the content of action it submits.

Note: <form action="<%=request.getContextPath()%>/saveTeacher.ado" method="get">
 1 <body style="height: 100%;width: 100%; background-image:url(lib/skr.jpg); background-size: cover;">
 2         <div style="height: 100px;width: 100%; text-align: center;">
 3             <h1>Student Achievement Management System</h1>
 4         </div>
 5         <div align="center">
 6                 <form action="<%=request.getContextPath() %>/saveTeacher.ado" method="get">
 7                     <%
 8                         Teachers_Login teacherLogin = (Teachers_Login) request.getAttribute("teacherLogin");
 9                     %>
10                         <input type="hidden" name="teacherId" value="<%=teacherLogin.getTeacherId()%>">
11                         <input type="hidden" name="teacherName" value="<%=teacherLogin.getTeacherName()%>">
12                     <table>
13                         <tr>
14                             <th colspan="2" align="center">Please fill in the teacher's basic information.</th>
15                         </tr>
16                         <tr>
17                             <td>Staff number:</td>
18                             <td><%=teacherLogin.getTeacherId()%></td>
19                         </tr>
20                         <tr>
21                             <td>Full name:</td>
22                             <td><%=teacherLogin.getTeacherName()%></td>
23                         </tr>
24                         <tr>
25                             <td>Gender:</td>
26                             <td><input type="text" name="sex"></td>
27                         </tr>
28                         <tr>
29                             <td>Telephone number?</td>
30                             <td><input type="text" name="phoneNo"></td>
31                         </tr>
32                         <tr>
33                             <td>Family address:</td>
34                             <td><input type="text" name="address"></td>
35                         </tr>
36                         <tr>
37                             <td>Date of birth:</td>
38                             <td><input type="text" name="birthday"></td>
39                         </tr>
40                         <tr>
41                             <td>Wages:</td>
42                             <td><input type="text" name="salary"></td>
43                         </tr>
44                         <tr>
45                             <td colspan="2" style="text-align: center;"><input type="submit" value="Determine"><input type="reset" value="Reset"></td>
46                         </tr>
47                     </table>
48                 </form>
49                 <p style="text-align: center;"><a href="administratorsMain.jsp">Back to home page</a></p>
50         </div>
51 </body>

Summary: In this way, you can select the corresponding method in the servlet when submitting the jsp page. I hope it will be helpful to you. Thank you!!!!

Posted by benracer on Wed, 20 Mar 2019 09:27:28 -0700