<web-app> ... <filter> <filter-name>accessControl</filter-name> <filter-class> com.ora.jsp.servlets.AccessControlFilter </filter-class> <init-param> <param-name>loginPage</param-name> <param-value>/ch18/login.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>accessControl</filter-name> <url-pattern>/ch18/protected/*</url-pattern> </filter-mapping> ... </web-app>
package com.ora.jsp.servlets; import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; public class AccessControlFilter implements Filter { private FilterConfig config = null; private String loginPage; public void init(FilterConfig config) throws ServletException { this.config = config; loginPage = config.getInitParameter("loginPage"); if (loginPage == null) { throw new ServletException("loginPage init param missing"); } } public void destroy( ) { config = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpResp = (HttpServletResponse) response; if (!isAuthenticated(httpReq)) { String forwardURI = getForwardURI(httpReq); // Forward to the login page and stop further processing ServletContext context = config.getServletContext( ); RequestDispatcher rd = context.getRequestDispatcher(forwardURI); if (rd == null) { httpResp.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Login page doesn't exist"); } rd.forward(request, response); return; } /* * Process the rest of the filter chain, if any, and ultimately * the requested servlet or JSP page. */ chain.doFilter(request, response); } /<strong> * Returns true if the session contains the authentication token. */ private boolean isAuthenticated(HttpServletRequest request) { boolean isAuthenticated = false; HttpSession session = request.getSession( ); if (session.getAttribute("validUser") != null) { isAuthenticated = true; } return isAuthenticated; } /</strong> * Returns the context-relative path to the login page, with the * parameters used by the login page. */ private String getForwardURI(HttpServletRequest request) { StringBuffer uri = new StringBuffer(loginPage); uri.append("?errorMsg=Please+log+in+first&origURL="). append(URLEncoder.encode(getContextRelativeURI(request))); return uri.toString( ); } /** * Returns a context-relative path for the request, including * the query string, if any. */ private String getContextRelativeURI(HttpServletRequest request) { int ctxPathLength = request.getContextPath().length( ); String requestURI = request.getRequestURI( ); StringBuffer uri = new StringBuffer(requestURI.substring(ctxPathLength)); String query = request.getQueryString( ); if (query != null) { uri.append("?").append(query); } return uri.toString( ); } }
|