package gr.xfrag.faces.mapping; import java.io.IOException; import java.net.URL; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; /** * This Filter will map requests of URIs ending with "/{anyword}" * where {anyword} is the file name of a JSP page without the * extension, to the corresponding JSF URL. It must be declared * in web.xml configuration file with an initialization parameter * named "faces extension" having the extension used to map the * FacesServlet. */ public class MappingFilter extends HttpServlet implements Filter { private FilterConfig filterConfig; private String facesExtension; /** * Process the request/response pair. Check if the requested URI * ends with the desired pattern and if does so, forward the * request to the FacesServlet. */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; // Get the requested URI String uri = httpReq.getRequestURI(); try{ // Check if the URI matches mapping creteria. boolean matches = uri.matches(".*/[\\w]+"); if(matches){ ServletContext context = filterConfig.getServletContext(); // Strip context path from the requested URI String path = context.getContextPath(); if (uri.startsWith(path)){ uri = uri.substring(path.length()); } // Check if there is actually a file to handle the forward. URL url = context.getResource(uri+".jsp"); if(url != null){ // Generate the forward URI String forwardURI = uri + facesExtension; // Get the request dispatcher RequestDispatcher rd = context.getRequestDispatcher(forwardURI); if(rd != null){ // Forward the request to FacesServlet rd.forward(request, response); return; } } } // We are not interested for this request, pass it to the FilterChain. chain.doFilter(request, response); } catch (ServletException sx) { filterConfig.getServletContext().log(sx.getMessage()); } catch (IOException iox) { filterConfig.getServletContext().log(iox.getMessage()); } } /** * Handle the passed-in FilterConfig */ public void init(FilterConfig config) throws ServletException { filterConfig = config; facesExtension = config.getInitParameter("faces extension"); } /** * Clean up resources */ public void destroy() { filterConfig = null; } }