Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL mapping in Tomcat to FrontController servlet

I'm trying to follow the pattern at Design Patterns web based applications. It all works fine part from when it comes to maping "root" URLs.

I'd like to put all requests through the "Front Controller" so I've put

<servlet-mapping>
    <servlet-name>ControllerServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

in the web.xml. Stepping through with Netbeans shows the request coming in, and the Action working OK, but then the line

request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);

ALSO gets caught by the controller, it goes to the Action again and it all fails.

I can make it work by not going from the URL root e.g.

  <servlet-mapping>
        <servlet-name>ControllerServlet</servlet-name>
        <url-pattern>/pages/*</url-pattern>
    </servlet-mapping>

But that isn't what I want. Is there any way to make it work with "root" URLs?

like image 803
Mark Avatar asked Jan 17 '12 23:01

Mark


1 Answers

The /* URL pattern covers everything, also the forwarded JSP files and static resources like CSS/JS/images. You don't want to have that on a front controller servlet.

Keep your controller servlet on a more specific URL pattern like /pages/*. You can achieve the functional requirement of getting rid of "/pages" in the URL by grouping the static resources in a common folder like /resources and creating a Filter which is mapped on /* and does the following job in the doFilter() method:

HttpServletRequest req = (HttpServletRequest) request;
String path = req.getRequestURI().substring(req.getContextPath().length());

if (path.startsWith("/resources/")) {
    // Just let container's default servlet do its job.
    chain.doFilter(request, response);
} else {
    // Delegate to your front controller.
    request.getRequestDispatcher("/pages" + path).forward(request, response);
}

A forwarded JSP resource will by default not match this filter, so it will properly be picked up by the container's own JspServlet.

like image 136
BalusC Avatar answered Jan 01 '23 20:01

BalusC