使用HttpServletRequest类来获取表单的请求,因为它有getMethod()方法
对应Hello.java代码:
package demo01; import javax.servlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class Hello implements Servlet { public Hello() { } @Override public void init(ServletConfig servletConfig) throws ServletException { } @Override public ServletConfig getServletConfig() { return null; } /** * service方法专门用来处理请求和响应 * @param servletRequest * @param servletResponse * @throws ServletException * @throws IOException */ @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("3 hello world"); // 类型转换,因为HttpServletRequest有getMethod() HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest; // 获取请求 String method = httpServletRequest.getMethod(); if (method.equals("GET")){ doGet(); }else if(method.equals("POST")){ doPost(); } } public void doGet(){ System.out.println("get请求"); } public void doPost(){ System.out.println("post请求"); } @Override public String getServletInfo() { return null; } @Override public void destroy() { } }
对应a.html代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="http://localhost:8080/draft_war_exploded/hello" method="post"> <input type="submit"> </form> </body> </html>
表单中method为get,控制台就返回“get请求”;如果为post,控制台就返回“post请求”。