struts2struts2-interceptors

Struts2 custom login interceptor


Can someone explain me how to write a custom login interceptor that checks username, password and also checks if the users validity date is greater than the current date. Im new to java programming & struts 2...i would really appreciate step by step info. I get the username, etc info by manual jdbc connection...i have a jndi setup for that. This also needs to have session management.

So a step by step with the following code samples would be nice,

1) The dao using jndi to get username,etc from DB

2) The login action with session aware

3) interceptor

4) login.jsp

5) struts.xml definition for the interceptor

6) task.jsp and task2.jsp ( internal pages that can only be seen if user is logged in)

Thank you!


Solution

  • You are on the right track.

    There are many articles on that topic (google it). Choose one and try to understand it. The interceptor part should look something like this:

    public String intercept (ActionInvocation invocation) throws Exception {
        // Get the action context from the invocation so we can access the
        // HttpServletRequest and HttpSession objects.
        final ActionContext context = invocation.getInvocationContext ();
        HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
        HttpSession session =  request.getSession (true);
    
        // Is there a "user" object stored in the user's HttpSession?
        Object user = session.getAttribute (USER_HANDLE);
        if (user == null) {
            // The user has not logged in yet.
    
            // Is the user attempting to log in right now?
            String loginAttempt = request.getParameter (LOGIN_ATTEMPT);
            if (! StringUtils.isBlank (loginAttempt) ) { // The user is attempting to log in.
    
                // Process the user's login attempt.
                if (processLoginAttempt (request, session) ) {
                    // The login succeeded send them the login-success page.
                    return "login-success";
                } else {
                    // The login failed. Set an error if we can on the action.
                    Object action = invocation.getAction ();
                    if (action instanceof ValidationAware) {
                        ((ValidationAware) action).addActionError ("Username or password incorrect.");
                    }
                }
            }
    
            // Either the login attempt failed or the user hasn't tried to login yet, 
            // and we need to send the login form.
            return "login";
        } else {
            return invocation.invoke ();
        }
    }
    

    Above code sample is part of this article where you will also find other steps.

    Another way I would recommend is integration of spring security with Struts 2. That way you get secured and proven configurable security stack.