细节
如果前端发了个get请求,你后端这个Hello类没重写doGet,那就会执行父类HttpServlet的doGet方法,报一个405的错误
一般只写一个,不会两个都写
类里的代码
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class Hello extends HttpServlet {
// @Override
// protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setContentType("text/html");
// PrintWriter out = resp.getWriter();
// out.print("<h1>hello world</h1>");
// }
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<h1>doGet</h1>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<h1>doPost</h1>");
}
}
配置文件里的代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>app1</servlet-name>
<servlet-class>Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>app1</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
网页上的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1>get请求</h1>
<a href="/app2/hello">hello(get请求)</a><br>
<h1>post请求</h1>
<form action="/app2/hello" method="post">hello(post请求)
<input type="submit" value="按钮">
</form>
</body>
</html>