开发者

Using Filters to Restrict JSP Access?

开发者 https://www.devze.com 2023-03-22 02:02 出处:网络
Im using a javascript call from a JSP to login using an AJAX call and the prototype framework for the server side request, I set up a filter to intercept all requests so that I can either redirect to

Im using a javascript call from a JSP to login using an AJAX call and the prototype framework for the server side request, I set up a filter to intercept all requests so that I can either redirect to the login page or proceed.

The problem Im having is that if you type the path into the URL in the browser to go to a different page, theres no way of filtering this 开发者_运维技巧before the page loads because its not an AJAX request and in some cases there isnt an HTTPWebRequest until a button is pressed on the page..

What would be the best way to handle this?

Thanks!


I understand that you are not utilizing the Java EE provided container managed authentication. It would namely take this automatically into account when properly configured.

With a homegrown authentication system, the normal practice is to put the logged-in user as an attribute in the session scope so that the remnant of your code can intercept on that, so also the servlet filters.

Assuming that your login method look like this:

User user = userService.find(username, password);

if (user != null) {
    request.getSession().setAttribute("user", user);
}

// ...

Then you could just do as follows in a filter:

@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);

    if (session == null || session.getAttribute("user") == null) {
        response.sendRedirect("login.jsp"); // No logged-in user found, so redirect to login page.
    } else {
        chain.doFilter(req, res); // Logged-in user found, so just continue request.
    }
}

Map this filter on an URL pattern which covers the secured pages, e.g. /app/* or something.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号