1

问题:当我希望调用 doPost 时,只调用 doGet 。

我有一个嵌入式 Jetty 服务器,我按如下方式启动:

server = new Server(8080);
ServletContextHandler myContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
myContext.setContextPath("/Test.do");
myContext.addServlet(new ServletHolder(new MyServlet()), "/*");

ResourceHandler rh = new ResourceHandler();
rh.setResrouceBase("C:\\public");

HandlerList hl = new HandlerList();
hl.setHandlers(new Handler[]{rh, myContext});

server.setHandler(hl);

//server.start() follows

启动服务器后,我打开以下页面(位于“public”文件夹中,并通过http://localhost:8080/test.html打开):

<html>
<head><title>Test Page</title></head>
<body>
<p>Test for Post.</p>
<form method="POST" action="Test.do"/>
<input name="field" type="text" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

当我按下提交按钮时,我希望调用我的 servlet 的 doPost 方法,但是 doGet 似乎被调用了。MyServlet 类(扩展 HttpServlet)包含:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
  System.out.println("   doGet called with URI: " + request.getRequestURI());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
  System.out.println("   doPost called with URI: " + request.getRequestURI());
}

我从来没有得到 doPost 打印,只是来自 doGet 的打印(在提交按钮按下时)。

显然,Jetty(以及一般的网络技术)对我来说是全新的。我一直在梳理 Jetty 示例,但似乎无法让 POST 真正被 doPost 方法拾取。

感谢任何帮助。提前致谢。

4

1 回答 1

4

问题是您的上下文路径。B/c 路径设置为

myContext.setContextPath("/Test.do");

Jetty 正在返回一个 HTTP 302 Found,其位置告诉浏览器“从这里获取页面”:

HTTP/1.1 302 Found
Location: http://localhost:8080/test.do/
Server: Jetty(7.0.0.M2)
Content-Length: 0
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Date: Wed, 04 Apr 2012 19:32:01 GMT

然后使用 GET 检索实际页面。将 contextPath 更改为/以查看您的预期结果:

myContext.setContextPath("/");
于 2012-04-04T19:42:12.460 回答