In the servlet program, since there is only one service method, there are two types of requests: post and get, so the request distribution processing is required
Create an html file in the web folder under the project
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/06_servlet1_war_exploded/hello" method="post">
<input type="submit">
</form>
<br/>
<form action="http://localhost:8080/06_servlet1_war_exploded/hello" method="get">
<input type="submit">
</form>
</body>
</html>
In the service method in the servlet program, through the subtype of the ServletRequest object, call the getMethod method to obtain the request type
/**
* service方法是专门用来处理请求和响应的(只要访问HelloServlet程序,他就会执行这个方法)
*/
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("3.service方法————HelloServlet被访问了");
/* ServletRequest对象中有一种getMethod方法
ServletRequest对象不能直接调用getMethod方法,他的子类型(子接口)可以使用
*/
HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
String method = httpServletRequest.getMethod();
// System.out.println(method);
if ("GET".equals(method)) {
System.out.println("get请求");
} else if ("POST".equals(method)) {
System.out.println("post请求");
}
}
Note: Sometimes there are a lot of get requests and post requests, which makes the code bloated. Sometimes, two methods of doGet and doPost are written, and the required functions are realized through method calls.