Servlet chaining - simple example

IUnknown picture IUnknown · Sep 29, 2012 · Viewed 9.7k times · Source

I see a strange issue in a simple servlet chaining example that I am trying:

Servlet 1:

public class gatewayservlet extends HttpServlet {

  public void doPost(HttpServletRequest request , 
    HttpServletResponse response)
    throws ServletException , IOException {
        doGet(request,response);
  }

  public void doGet(HttpServletRequest request , 
    HttpServletResponse response)
    throws ServletException , IOException {

    response.setContentType("text/plain");

    PrintWriter out = response.getWriter();

    name = request.getParameter("name");

    RequestDispatcher rd = getServletConfig().getServletContext().getRequestDispatcher("/justServlets/secondservlet");

    if(name!=null) {
      request.setAttribute("UserName",name);
      rd.forward(request , response);
      // Forward the value to another Secondservlet
    } else {
      response.sendError(response.SC_BAD_REQUEST, 
        "UserName Required");
    }

  }

}

Servlet 2:

public class secondservlet extends HttpServlet {

  public void doGet(HttpServletRequest request , 
    HttpServletResponse response)
    throws ServletException , IOException {

    response.setContentType("text/plain");

    PrintWriter out = response.getWriter();

    String UserName = (String)request.getAttribute("UserName");

    out.println("The UserName is "+ UserName);

  }


  public void doPost(HttpServletRequest request , 
    HttpServletResponse response)
    throws ServletException , IOException {
        doGet(request,response);
  }

}

And the invoking form:

<html>
<body>
<FORM ACTION="/justServlets/gateway" METHOD=POST>
<P>Please Fill the Registration Form</p><br>
Enter Your Name<input type="text" name="name"><br>
<input type="submit" value="send">
</FORM>
</body>
</html>

The 'POST' gives a 405(Method not allowed) error. However ,invoking the first servlet as ..../justServlets/gateway?name=Socrates works. Whats the matter?

Answer

JB Nizet picture JB Nizet · Sep 29, 2012

Assuming that /justServlets is the context path of your webapp, the code which forwards should use /secondservlet and not /justServlets/secondservlet, because, as the javadoc says:

The pathname must begin with a / and is interpreted as relative to the current context root.

(emphasis mine)

As it is, you're forwarding to /justServlets/justServlets/secondservlet, which probably doesn't exist.