title: Using Servlets and JSP together resulting in unexpected looping
body: <p>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:</p>
  
  <pre><code>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);
  }
  </code></pre>
  
  <p>This works fine for the simple example, but when I step it up (even a little):</p>
  
  <pre><code>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) &amp;&amp; (pathInfo.length() &gt; 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);
  }
  </code></pre>
  
  <p>As far as I can tell what's happening is that if I go to (for example) <a href="http://localhost/main/example" rel="nofollow noreferrer">http://localhost/main/example</a> 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.</p>
  
  <p>How can I have it run different JSP files with some logic similar to above?</p>
  
  <p>Just for good measure the mapping in the web.xml is:</p>
  
  <pre><code>&lt;servlet&gt;
      &lt;servlet-name&gt;Main&lt;/servlet-name&gt;
      &lt;servlet-class&gt;com.example.MainServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;Main&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/main/*&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  </code></pre>