The following code filter will render /templates/main.jsp regardless of what URL comes in. The only exception are URLs which end in a extension, like *.jpg or *.css. They are delegated to the default request chain. This way you don’t interfere with style sheets and all that.
This is the behavior you need when you design a blog-like site with so called “pretty URLs” / permalinks. Before you render the main.jsp template you have to extract an entry name from the URL and fetch it from the database, or fetch several pages depending on how the request URL looks like. They are then displayed in main.jsp.
It’s Model View Controller (MVC) in its purest form. Your filter is the controller, the main.jsp the view, and you will have some model (e.g., the list of posts) that your view will render.
public class MainController implements Filter {
private FilterConfig filterConfig;
/** Creates a new instance of MainControllerFilter */
public MainController() {
}
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
if (hasExtension(request.getRequestURI())) {
// if we have a request for style.css, pic.jpg etc.
// this will be the regular mechanism, so a regular 404 could occur
filterChain.doFilter(servletRequest, servletResponse);
} else {
// retrieve pages from database etc.
servletRequest.getRequestDispatcher("/templates/main.jsp").forward(servletRequest, servletResponse);
}
}
private boolean hasExtension(String path) {
if (path.matches(".+.w{2,4}$")) {
return true;
}
return false;
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
}
Your web.xml will look something like this:
<filter>
<filter-name>MainController
<filter-class>com.uberdose.mvc.servlet.MainController
</filter>
<filter-mapping>
<filter-name>MainController
<url-pattern>/*
</filter-mapping>
Tags: model view controller, mvc, servlet