Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。
Servlet创建的三种方式
1 Servlet实现接口
//一次创建,到处服务
2 继承GenericServlet 接口//少用
3 继承HttpServlet
具体为
Servlet,ServletConfig-->GenericServlet(定义init(),并抽象化service方法
-->HttpServlet(进一步继承)-->需要的Servlet接口
在 HttpServlet 中,自定义了一个新的 service() 方法,其中通过 getMethod() 方法判断请求的类型,从而调用 doGet() 或者 doPost() 处理 get,post 请求,使用者只需要继承 HttpServlet,然后重写 doPost() 或者 doGet() 方法处理请求即可。
abstract class GenericServlet implements Servlet,ServletConfig{
private trServletConfig servletConfig;
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig=servletConfig;
this.init();
}
public void init(){
}
public abstract void service(ServletRequest request,ServletResponse response)
throws ServletException,java.io.IOException{
}
public void destroy(){ }
}
abstract class HttpServlet extends GenericServlet{
protected void service(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse){
}
public void service(ServletRequest servletRequest,ServletResponse servletResponse){
HttpServletRequest request;
HttpServletResponse response;
try{
request=(HttpServletRequest)servletRequest;
response=(HttpServletResponse)servletResponse;
}catch(ClassCastException){
throw new ServletException("non-http request or response");
}
this.service(request,response);
}
}
public class ServletDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("haha");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("ee");
doGet(req,resp);
}
}