servlet中get和post请求的分发处理
package LWB;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class HelloServlet implements Servlet {
public HelloServlet() {
System.out.println("1.构造方法");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("2.init方法");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
//service方法是专门用来处理请求和响应的
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("3. HelloServlet被访问了");
//类型转换,因为HttpServletRequest类型有getMethod()方法
HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
//获取请求的方法
String method=httpServletRequest.getMethod();
// System.out.println(method);
if("GET".equals(method)){
doGet();
}
else if("POST".equals(method)){
doPost();
}
}
public void doGet(){
System.out.println("get请求");
System.out.println("get请求");
}
public void doPost(){
System.out.println("post请求");
System.out.println("post请求");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("4.destroy方法");
}
}