FileDocCategorySizeDatePackage
AuthorizationFilter.javaAPI DocExample2387Sun Sep 05 16:52:36 BST 2004com.oreilly.strutsckbk.ch11.ams

AuthorizationFilter

public class AuthorizationFilter extends Object implements Filter

Fields Summary
private String[]
roleNames
private String
onFailure
Constructors Summary
Methods Summary
public voiddestroy()

    
public voiddoFilter(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain)

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        ActionErrors errors = new ActionErrors();
        if (user != null) {
            boolean hasRole = false;
            for (int i = 0; i < roleNames.length; i++) {
                if (user.hasRole(roleNames[i])) {
                    hasRole = true;
                    break;
                }
            }
            if (!hasRole) {
                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(
                        "error.authorization.required"));
            }
        }
        if (errors.isEmpty()) {
            chain.doFilter(request, response);
        } else {
            req.setAttribute(Globals.ERROR_KEY, errors);
            req.getRequestDispatcher(onFailure).forward(req, res);
        }
    
public voidinit(javax.servlet.FilterConfig filterConfig)

        String roles = filterConfig.getInitParameter("roles");
        if (roles == null || "".equals(roles)) {
            roleNames = new String[0];
        } else {
            roles.trim();
            roleNames = roles.split("\\s*,\\s*");
        }
        onFailure = filterConfig.getInitParameter("onFailure");
        if (onFailure == null || "".equals(onFailure)) {
            onFailure = "/index.jsp";
        }