HttpServlet:
1).是一个Servlet,继承自GenericServlet.针对于HTTP协议所制定.
2).在service()方法中直接把ServletRequest和ServletResponse转为HttpServletRequest和HttpServletResponse 并调用 了重载的service(HttpServletRequest,HttpServletResponse)
在service(HttpServletRequest,HttpServletResponse)中获取了请求方式:request.getMethod().根据请求方式又创建了doXxx()方法(xxx为具体的请求方式,比如doGet,doPost
public class MyHttpServlet extends MyGenericServlet {
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
if (res instanceof HttpServletResponse) {
HttpServletResponse response = (HttpServletResponse) res;
service(request, response);
}
}
}
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.获取请求方式
String method = request.getMethod();
// 2.根据请求方式在调用对应的处理方法
if ("GET".equalsIgnoreCase(method)) {
doGet(request, response);
} else if ("POST".equalsIgnoreCase(method)) {
doPost(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
3)实际开发中,直接继承HttpServlet,并根据请求方式复写doXxx()方法接口。
4)好处:直接有针对性的覆盖doXxx()方法;直接使用HttpServletRequest和HttpServletResponse,不再需要强转。