- When Tomcat receives a client request, it will hand over the request
CoyoteAdapter
for processing. CoyoteAdapter
Connector
Find the corresponding sum based on the request method (GET, POST, etc.) and URLProcessor
.Processor
It is a Servlet container that is responsible for creating and maintaining Servlet objects, processing HTTP requests, and returning the generated responses to the client.Processor
The Servlet instance will be created and initialized when calledStandardWrapperValve
, and its corresponding life cycle method will be called to process the request and generate a response.
The following is StandardWrapperValve
a code snippet that handles Servlet requests:
public final class StandardWrapperValve extends ValveBase {
public void invoke(Request request, Response response) throws IOException, ServletException {
......
// 在这里获取到对应的Servlet对象
Servlet servlet = wrapper.allocate();
try {
// 初始化Servlet并调用相应的生命周期方法
request.setServletPath(wrapper.getServletPath());
request.setAttribute(Globals.SERVLET_MAPPING_ATTR, wrapper.getServletMapping().getMatchValue());
support.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT, servlet);
servlet.init(config);
support.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet);
pipeline.invoke(request, response);
support.fireInstanceEvent(InstanceEvent.BEFORE_DESTROY_EVENT, servlet);
} finally {
// 销毁Servlet实例
if (servlet != null) {
wrapper.deallocate(servlet);
}
request.recycle();
response.recycle();
}
}
}
In this code snippet we can see:
StandardWrapperValve
It is anValve
implementation class used to process Servlet requests in Tomcat's request processing process.- In
invoke
the method,StandardWrapperValve
first find the correspondingServlet
object based on the URL path information (servlet path) contained in the request. - Then, the HTTP request is processed and the response is generated
StandardWrapperValve
by callingServlet
the life cycle methods (init()
,service()
etc.). - Finally, in
finally
the block, the Servlet container will callservlet
thedestroy()
method to destroy the Servlet instance.
It should be noted that this is just a brief example of Tomcat's Servlet request processing logic. The actual code implementation may be more complex than this and involve multiple modules and classes working together.