要求在我只使用POST方法的

时间:2018-06-07 18:16:22

标签: java servlets requestdispatcher

这是我的HTML代码

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>New Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <form method="post" action="display">

我使用上面的POST方法进行servlet操作

            Enter Name: <input type="text" name="name">
            Enter City <input type="text" name="city">
            <input type="submit" name="submit">
        </form>        
    </body>
</html>

Servlet1.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class servlet1 extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException 

使用&#34; doPost &#34;对于html表单中定义的POST方法

    {
        response.setContentType("text/html");

        Cookie c1 = new Cookie("name",request.getParameter("name"));
        Cookie c2 = new Cookie("city",request.getParameter("city"));

        response.addCookie(c1);
        response.addCookie(c2);

通过此表单重定向到第二个servlet

        response.sendRedirect("servlet2");

    }
}

servlet2.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class servlet2 extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse 
    response) throws ServletException, IOException 

我收到错误说&#34; 此网址不支持HTTP GET方法&#34;但是我的代码中没有提到GET。

    {
        response.setContentType("text/html");

        Cookie c[] = request.getCookies();
        PrintWriter pw = response.getWriter();

        for(Cookie cookie : c)
        {
            if(cookie.getName().equals("name") || 
cookie.getName().equals("city"))
            {
                pw.println(cookie.getValue()+"<br>");
            }
        }
        pw.println("Print using cookie");
    }
}
如果我使用&#34; doGET &#34;那么servlet工作得非常好。 servlet2.java中的方法。但是我使用 POST 方法,然后为什么需要&#34; doGET&#34; ??

上面的代码出现以下错误。     HTTP状态405 - 此URL不支持HTTP方法GET

type: Status report

message: HTTP method GET is not supported by this URL

description: The specified HTTP method is not allowed for the requested 
resource.

Apache Tomcat/7.0.56

0 个答案:

没有答案