1

我在尝试的一个简单的 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");
    }

  }

}

小服务程序 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);
  }

}

和调用形式:

<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>

'POST' 给出 405(不允许的方法)错误。但是,调用第一个 servlet 为 ..../justServlets/gateway?name=Socrates 有效。怎么了?

4

2 回答 2

1

假设这/justServlets是您的 webapp 的上下文路径,转发的代码应该使用/secondservlet而不是/justServlets/secondservlet,因为正如javadoc所说:

路径名必须以 / 开头,并被解释为相对于当前上下文根

(强调我的)

实际上,您正在转发到/justServlets/justServlets/secondservlet,它可能不存在。

于 2012-09-29T06:51:21.310 回答
0

这通常发生在您要转发的 servlet 缺少与最初处理的方法相同的方法(在本例中为 POST)的处理程序时。确保 servlet2 确实处理 doPost 并且您确实正在转发到 servlet2。

于 2012-09-29T06:44:51.967 回答