1 Servlet基本执行过程

Web容器(如Tomcat)判断当前请求是否第一次请求Servlet程序 。

如果是第一次,则Web容器执行以下任务:

加载Servlet类。
实例化Servlet类。
调用init方法并传入ServletConfig对象

如果不第一次执行,则:

调用service方法,并传入request和response对象

Web容器在需要删除Servlet时(例如,在停止服务器或重新部署项目时)将调用destroy方法。

2 Web容器如何处理Servlet请求

Web容器负责处理请求。让我们看看它如何处理请求。

将用户请求与web.xml文件中的Servlet进行映射。
创建请求和响应对象
创建新的线程,并在该线程上调用Servlet的service方法
在public的service方法内部调用protected的service方法
protected的service方法根据请求的类型调用doGet方法。
doGet方法生成响应并将其传递给客户端。
发送响应后,Web容器将删除请求和响应对象。该线程是继续留在线程池中还是被删除取决于服务器实现。

3 public的service方法部分源码

public的service方法将ServletRequest对象转换为HttpServletRequest类型,而ServletResponse对象转换为HttpServletResponse类型。然后,调用传递这些对象的服务方法。让我们看一下内部代码:

public void service(ServletRequest req, ServletResponse res) 
  throws ServletException, IOException 
{ 
  HttpServletRequest request; 
  HttpServletResponse response; 
  try 
  { 
    request = (HttpServletRequest)req; 
    response = (HttpServletResponse)res; 
  } 
  catch(ClassCastException e) 
  { 
    throw new ServletException("non-HTTP request or response"); 
  } 
  service(request, response); 
} 

4 protected的service方法部分源码

protected的service方法判断请求的类型,如果请求类型为GET,则调用doGet方法,如果请求类型为POST,则调用doPost方法,依此类推。让我们看一下内部代码:

protected void service(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException 
{ 
  String method = req.getMethod(); 
  if(method.equals("GET")) 
  { 
    long lastModified = getLastModified(req); 
    if(lastModified == -1L) 
    { 
      doGet(req, resp); 
    }  
.... 
//rest of the code 
  } 
}

以上就是Java Servlet 运行原理分析的详细内容,更多关于Java Servlet 运行原理的资料请关注免费资源网其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。