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 ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.