Question

I have implemented a Java EE security realm that redirects users to login.jsp if they try and access a protected resource.

  • Say a user wants to go to a protected url - http://mywebapp/shopping_cart which is mapped to ShoppingCartServlet
  • As they are not logged in Glassfish directs them to login.jsp
  • They then enter their username and password and click Login and the information gets POSTed to http://mywebapp/j_security_check
  • If they have entered the correct details they are then redirected to the servlet that handles the url http://mywebapp/shopping_cart

Now I want to pull the user's details from the database but how can I when there are no parameters in the redirect request?

Their username was sent to http://mywebapp/j_security_check but there are no parameters in the redirect request that j_security_check makes to http://mywebapp/shopping_cart. So what method is used to access the user's details once they log in?

Était-ce utile?

La solution

Create a filter which checks if the user is logged in while no associated User object from the database is present in the session. Then, just load that data and put in session.

Basically,

@WebFilter("/*")
public class UserFilter implements Filter {

    @EJB
    private UserService service;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String remoteUser = request.getRemoteUser();

        if (remoteUser != null) {
            HttpSession session = request.getSession();

            if (session.getAttribute("user") == null) {
                User user = service.find(remoteUser);
                session.setAttribute("user", user);
            }
        }

        chain.doFilter(req, res);
    }

    // ...
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top