How can I handle/restrict user-access to servlets & jsp's?

后端 未结 2 693
心在旅途
心在旅途 2020-12-29 11:56

I\'m currently writing a little dynamic web-application in Java. The application is supposed to be an event-platform where you can create a user-account, log in, and then yo

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 12:16

    There're several ways to do it such as servlet filter as above. I saw in some projects they use a simpler mechanism to do it by creating a common action (servlet). So instead of extends HttpServlet, all servlet will be extended the common action. And you can implement a lot of common stuffs such as authentication, validations, permissions...

    Here's common action example:

    public class CommonServlet extends HttpServlet {
    ................
    ................
    protected boolean validate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
    
        String email = (String) request.getSession().getAttribute("email");
        Object salaryGroup = request.getSession().getAttribute("SALARY_GROUP");
    
        if (email == null || email.equals("")) {
            request.setAttribute("err", "You have not logged in");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return false;
        }
    
    ................
    ................
    }
    
    public void setRoleAndValidate(HttpServletRequest request, HttpServletResponse response, String role)
            throws ServletException, IOException {
        if (!validate(request, response)) {
            return;
        }
    
        setRoleCode(role);
    }
    ................
    ................
    

    }

    Your action servlet will be as below:

    @WebServlet("/employeeManager")
    public class EmployeeManager extends CommonServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
                     ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            setRoleAndValidate(request, response, Permission.EMPLOYEE_LIST.toString());
    
            String action = request.getParameter("action");
            .....
    

    Here's the simple implementation

提交回复
热议问题