我在一个简单的servlet链接示例中看到一个奇怪的问题,我正在尝试:
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);
}
}
以及调用表单:
<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 =苏格拉底有效。 怎么回事?
答案 0 :(得分:1)
假设/justServlets
是您的网络应用的上下文路径,转发的代码应该使用/secondservlet
而不是/justServlets/secondservlet
,因为正如the javadoc所说:
路径名必须以/开头,并且相对于当前上下文根被解释为。
(强调我的)
实际上,您转发到/justServlets/justServlets/secondservlet
,这可能不存在。
答案 1 :(得分:0)
当您转发的servlet缺少与最初处理的方法相同的处理程序(在本例中为POST)时,通常会发生这种情况。确保servlet2确实处理了doPost,并确实转发到servlet2。