get方法没问题,post方法报405错误
HTTP Status [405] – [Method Not Allowed]
Type Status Report
Message HTTP method POST is not supported by this URL
Description The method received in the request-line is known by the origin server but not supported by the target resource.
Apache Tomcat/9.0.0.M21
代码:index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- <link rel="stylesheet" type="text/css" href=""> --> <title>Insert title here</title> </head> <body> <h1>第一个servlet小例子</h1> <hr> <a href="servlet/HelloServlet">Get方法请求HelloServlet</a> <form action="servlet/HelloServlet" method="post"> <input type="submit" value="用post方式提交HelloServlet" /> </form> </body> </html>
HelloServlet.java:
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("处理Get请求……"); PrintWriter out = response.getWriter(); response.setContentType("text/html;charset=utf-8"); out.println("<b>Hello Servlet</b>"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("处理Post请求……"); PrintWriter out = response.getWriter(); response.setContentType("text/html;charset=utf-8"); out.println("<b>Hello Servlet</b>"); } }
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- 欢迎页面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/servlet/HelloServlet</url-pattern> </servlet-mapping> </web-app>