11.8. Limiting Access for Specific URLs by Role

Problem

You need to verify the user is authorized to access selected URLs based on the user's security role and profile.

Solution

Use a servlet filter such as the one shown in Example 11-14.

Example 11-14. Authorization filter

package com.oreilly.strutsckbk.ch11.ams; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.Globals; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMessage; public class AuthorizationFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { String roles = filterConfig.getInitParameter("roles"); if (roles == null || "".equals(roles)) { roleNames = new String[0]; } else { roles.trim( ); // use the new split method of JDK 1.4 roleNames = roles.split("\\s*,\\s*"); } onFailure = filterConfig.getInitParameter("onFailure"); if (onFailure == null || "".equals(onFailure)) { onFailure = "/index.jsp"; } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = ...

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.