Matthew
Matthew

Reputation: 8426

Servlet URL and physical directories

So, now that I have moved my JSP files to /WEB-INF/content from /content after coding my ProcessServlet to use forward() to get to them, how should I set up my web.xml URL pattern to get to the Servlet?

Note: My JSPs were under /content along with CSS, image and JS files. So /content/css, /content/image, /content/js are all still there.

I found that if I use the pattern "/content/*" in web.xml for my Servlet then requests for css, images and js all go through the Servlet as well. How should I avoid this?

Can someone suggest a better way to set up my URLs and directories?

Upvotes: 1

Views: 763

Answers (3)

BalusC
BalusC

Reputation: 1109072

2 options:

  1. Move /content/css, /content/image, /content/js to /resources/css, etc. To fix URLs in existing JSPs, just use find&replace the smart way. Should be a minute work.

  2. Change servlet's URL pattern /content/* to something else, e.g. /pages/*.

    • If you want to keep your existing URLs, add a filter on /content/* which does basically the following:

      String uri = ((HttpServletRequest) request).getRequestURI();
      if (uri.startsWith("/content/css/") || uri.startsWith("/content/image/") || uri.startsWith("/content/js/")) {
          chain.doFilter(request, response); // Goes to default servlet.
      } else {
          request.getRequestDispatcher("/pages" + uri).forward(request, response);
      }
      

    This is only a drastic change. You'd probably need to fix all links in JSPs, for sure if they are not designed the way that there's a master template wherein you've specified <base> in a single location. Also, you might want to add 301 redirects for old bookmarks and search indexes.

Upvotes: 2

gigadot
gigadot

Reputation: 8969

This is how I setup mine:

+-WEB-INF/
|   +-jsp/*.jsp
+-styles/*.css
+-images/*.jpn,*.png,etc.

I use servlet mapping to map dynamic contents, e.g. *jsp, and leave the default servlet to deal with the static contents. Of course, this is not the only way to solve problem.

web.xml looks like this:

<servlet-mapping>
    <servlet-name>Your Servlet</servlet-name>
    <url-pattern>/content/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

The default servlet is provided by most servelt container and you do not need to write one. The keyword is "default" for tomcat and jetty.

Upvotes: 1

Yoni
Yoni

Reputation: 10321

You don't have to use a servlet for such forwarding. If the number of jsp pages is not large, you can declare mapping for them directly in the web.xml, just as you'd do for servlets (See example here)

Upvotes: 1

Related Questions