0

I am learning Java Servlets. Trying to implement the doPost() method, however I get an error that "HTTP Status 405 - HTTP method POST is not supported by this URL".

Code

<html>
<body>
<center>
<form name="Form1" action="http://localhost:8080/examples/servlet/ColorGetServlet" method="post">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>

<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

Servlet

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

public class ColorGetServlet extends HttpServlet{

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

    String color = request.getParameter("color");
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();

    pw.println("<B>The Selected Color is: ");
    pw.println(color);
    pw.close();
    } 
}

Will appreciate if anyone can tell me what am I doing wrong.

4

2 回答 2

0

这是一种变通方法,而不是调用 servlet 的正确过程。将以下行添加到 jsp 页面的顶部。

<%@page import="your-package-name.examples.servlet.ColorGetServlet"%>

例如,

<%@page import="com.yourcompany.examples.servlet.ColorGetServlet"%>

这不是一个好方法,因为您直接绕过了 web.xml,而是将 servlet 导入到您的 jsp 页面中。并在您的页面更改<input type=submit value="Submit">

<input type="submit" value="Submit">

尝试上述方法,如果失败,请发表评论。

于 2014-09-19T05:06:00.367 回答
0

您好,问题出在action,请改成

<html>
<body>

<form name="Form1" action="<%=request.getContextPath() %>/ColorGetServlet" method="post">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>

<br><br>
<input type=submit value="Submit">
</form>

</body>
</html>

web.xml 应该如下所示:

 <servlet>
    <description></description>
    <display-name>ColorGetServlet</display-name>
    <servlet-name>ColorGetServlet</servlet-name>
    <servlet-class>ColorGetServlet.ColorGetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ColorGetServlet</servlet-name>
    <url-pattern>/ColorGetServlet</url-pattern>
  </servlet-mapping>

我希望我有帮助

于 2018-09-02T10:21:19.897 回答