2010-09-02 152 views
2

根据给出的示例here,我编写了一个servlet来处理POST和GET请求。我有以下:作为GET处理POST请求的Servlet

具有以下形式的HTML:

form method="POST" action="servlet/RequestType" 

和输入:

input type="submit" value="POST" 

以下doGetdoPost方法:

public void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { 
    rsp.setContentType("text/html"); 
    PrintWriter out = rsp.getWriter(); 

    String requestType = req.getMethod(); 

    out.println("<html>"); 
    out.println("<head><title> Request Type: " + requestType 
     + " </title></head>"); 
    out.println("<body>"); 
    out.println("<p>This page is the result of a " + requestType 
    + " request.</p>"); 
    out.println("</body></html>"); 
} 

public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { 
    doGet(req, rsp); 
} 

输出应成为:

此页面是POST请求的结果。

但我发现了:

这个网页是一个GET请求的结果。

有没有人知道为什么会发生这种情况?

+0

我看不到您的HTML。您确定属性method =“POST”是否在HTML

元素中设置? 尝试删除doPost方法。您应该收到一条消息,指出该操作不受支持。 – gawi 2010-09-02 02:47:56

+1

是的,我刚刚编辑我的帖子,以显示我的表单是如何的,它之前没有显示,因为我认为html标签。无论如何,这是我的形式: AntonioJunior 2010-09-02 02:51:54

+0

我有一个类似的问题。解决方案:http://stackoverflow.com/questions/8695795/html-form-method-post-calls-java-servlet-doget-method – mynameismarcin 2012-01-02 10:12:09

回答

0

您需要按下表单的提交按钮才能发送POST请求。

这就是说,2001年的这个教程给了我很多痒。我会建议去阅读一个更新的/体面的。

+0

是的,BalusC,我按了。这就是我得到这个结果的原因。我会尝试寻找另一个教程。有什么建议么?谢谢! – AntonioJunior 2010-09-04 02:42:52

2

我知道,这是不解决,但尝试在调用doGet()之前检查doPost()中的请求方法。 使用System.out.println() - 你会看到会写什么。如果什么都不会写,那就意味着你的请求总是GET。