O'Reilly logo

Jakarta Struts Cookbook by Bill Siggelkow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.2. Checking for User Login on Any Struts Reques t

Problem

You want to be able to check if a user is logged in for any request made to an action in your struts-config.xml file, but you don't want to have to subclass a custom base Action class.

Solution

Create a custom request processor, overriding the processPreprocess( ) or the processActionPerform( ) method. The custom request processor shown in Example 11-3 retrieves the user object from the HTTP session. If this object is null, an HTTP error response of 403 (Forbidden) is returned.

Example 11-3. Overriding the processPreprocess( ) method

package org.apache.struts.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.webapp.example.Constants;
import org.apache.struts.webapp.example.User;

public class CustomRequestProcessor1 extends RequestProcessor {

    protected boolean processPreprocess(HttpServletRequest request,
            HttpServletResponse response) {
        HttpSession session = request.getSession( );
        User user = (User) session.getAttribute(Constants.USER_KEY);
        if (user == null) {
            try {
                response.sendError(403, "User not logged in");
            } catch (IOException e) {
                log.error("Unable to send response");
            }
            return false;
        }
        
        return true;
    }
}

If you need to use the Struts objects passed to an Action's execute() method, such as the ActionForm and ActionMapping, override the processActionPerform( ) method as shown in Example ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required