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

◇◆丶佛笑我妖孽 提交于 2019-11-30 05:21:31
Luiggi Mendoza

This can be handled in a Filter and there are great explanation and example in StackOverflow Servlet-Filter wiki.

Adapting the code there for your problem (note the addition and usage of the needsAuthentication method):

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig config)
        throws ServletException {
        // If you have any <init-param> in web.xml, then you could get them
        // here by config.getInitParameter("name") and assign it as field.
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        String requestPath = httpServletRequest.getRequestURI();

        if (needsAuthentication(requestPath) ||
            session == null ||
            session.getAttribute("user") == null) { // change "user" for the session attribute you have defined

            response.sendRedirect(request.getContextPath() + "/login"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }

    @Override
    public void destroy() {
        // If you have assigned any expensive resources as field of
        // this Filter class, then you could clean/close them here.
    }

    //basic validation of pages that do not require authentication
    private boolean needsAuthentication(String url) {
        String[] validNonAuthenticationUrls =
            { "Login.jsp", "Register.jsp" };
        for(String validUrl : validNonAuthenticationUrls) {
            if (url.endsWith(validUrl)) {
                return false;
            }
        }
        return true;
    }
}

I would recommend to move all the pages that require authentication inside a folder like app and then change the web filter to

@WebFilter("/app/*")

In this way, you can remove the needsAuthentication method from the filter.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!