views:

295

answers:

1

I'm trying to use Servlets as a controller layer and JSPs as a view layer. Many of the examples/tutorials I've read suggest doing somehting like this:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 // add something for the JSP to work on
 request.setAttribute("key", "value");

 // show JSP
 request.getRequestDispatcher("main.jsp")forward(request, response);
}

This works fine for the simple example, but when I step it up (even a little):

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 // add something for the JSP to work on
 request.setAttribute("key", "value");

 String pathInfo = request.getPathInfo();
 if ((pathInfo != null) && (pathInfo.length() > 1)) {
  // get everything after the '/'
  pathInfo = pathInfo.subSequence(1, pathInfo.length()).toString();

  if (pathInfo.equals("example")) {
   request.getRequestDispatcher("alternate.jsp").forward(request, response);
  }
 }

 // show JSP
 request.getRequestDispatcher("main.jsp").forward(request, response);
}

As far as I can tell what's happening is that if I go to (for example) http://localhost/main/example it's hitting the servlet, getting to where it dispatches to alternate.jsp, then it runs the servlet again but this time instead of the pathInfo equaling "example" it equals "alternate.jsp" so it falls through to the main.jsp dispatch.

How can I have it run different JSP files with some logic similar to above?

Just for good measure the mapping in the web.xml is:

<servlet>
 <servlet-name>Main</servlet-name>
 <servlet-class>com.example.MainServlet</servlet-class>
</servlet>
<servlet-mapping>
 <servlet-name>Main</servlet-name>
 <url-pattern>/main/*</url-pattern>
</servlet-mapping>
+2  A: 

Oddly, I was just looking at this from another angle. See here, section 7.3.2 Servlet Matching Procedure for information on the order of matches.

Short summary: Path based mappings trump extension based mappings, so you're hijacking the JSP mapping.

Tetsujin no Oni
Does anyone have any suggestions for alternate approaches?
fiXedd