SpringBoot内嵌的Tomcat启动过程以及请求

1.springboot内嵌的tomcat的pom坐标

 启动后可以看到tomcat版本为9.0.46

 2.springboot 内嵌tomcat启动流程

点击进入SpringApplication.run()方法里面

看这次tomcat启动相关的核心代码refreshContext(context);刷新上下文方法

public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch();stopWatch.start();ConfigurableApplicationContext context = null;configureHeadlessProperty();SpringApplicationRunListeners listeners = getRunListeners(args);listeners.starting();try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);configureIgnoreBeanInfo(environment);Banner printedBanner = printBanner(environment);context = createApplicationContext();prepareContext(context, environment, listeners, applicationArguments, printedBanner);// 此次的核心代码是刷新上下文方法refreshContext(context);afterRefresh(context, applicationArguments);stopWatch.stop();if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);}listeners.started(context);callRunners(context, applicationArguments);}catch (Throwable ex) {handleRunFailure(context, ex, listeners);throw new IllegalStateException(ex);}try {listeners.running(context);}catch (Throwable ex) {handleRunFailure(context, ex, null);throw new IllegalStateException(ex);}return context;
}

进入 私有方法refreshContext

private void refreshContext(ConfigurableApplicationContext context) {if (this.registerShutdownHook) {try {context.registerShutdownHook();}catch (AccessControlException ex) {// Not allowed in some environments.}}// 核心方法,继续进入refresh((ApplicationContext) context);
}
@Deprecated
protected void refresh(ApplicationContext applicationContext) {Assert.isInstanceOf(ConfigurableApplicationContext.class, applicationContext);// 核心代码,继续进入方法refresh((ConfigurableApplicationContext) applicationContext);
}

进入refresh方法

protected void refresh(ConfigurableApplicationContext applicationContext) {// 核心方法,查看调用的方法refresh()applicationContext.refresh();
}

查看refresh方法,有三个实现类,进入默认的实现类ServletWebServerApplicationContext,定位到实现方法

@Override
public final void refresh() throws BeansException, IllegalStateException {try {// 进入父类refreshsuper.refresh();}catch (RuntimeException ex) {WebServer webServer = this.webServer;if (webServer != null) {webServer.stop();}throw ex;}
}

 看onRefresh()方法

@Override
public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// Prepare this context for refreshing.prepareRefresh();// Tell the subclass to refresh the internal bean factory.ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// Prepare the bean factory for use in this context.prepareBeanFactory(beanFactory);try {// Allows post-processing of the bean factory in context subclasses.postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);// Initialize message source for this context.initMessageSource();// Initialize event multicaster for this context.initApplicationEventMulticaster();// 我们进入这个方法// Initialize other special beans in specific context subclasses.onRefresh();// Check for listener beans and register them.registerListeners();// Instantiate all remaining (non-lazy-init) singletons.finishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event.finishRefresh();}catch (BeansException ex) {if (logger.isWarnEnabled()) {logger.warn("Exception encountered during context initialization - " +"cancelling refresh attempt: " + ex);}// Destroy already created singletons to avoid dangling resources.destroyBeans();// Reset 'active' flag.cancelRefresh(ex);// Propagate exception to caller.throw ex;}finally {// Reset common introspection caches in Spring's core, since we// might not ever need metadata for singleton beans anymore...resetCommonCaches();}}
}

 找到子类的实现方法:

@Override
protected void onRefresh() {super.onRefresh();try {// 核心代码,创建web服务器createWebServer();}catch (Throwable ex) {throw new ApplicationContextException("Unable to start web server", ex);}
}

进入createWebServer方法,ServletContext、WebServer在tomcat启动的时候一定为空,还没有初始化完成,会进入if代码块执行

private void createWebServer() {WebServer webServer = this.webServer;// tomcat启动servletContext才进行创建ServletContext servletContext = getServletContext();if (webServer == null && servletContext == null) {ServletWebServerFactory factory = getWebServerFactory();// 核心代码,通过工厂获取一个WebServer实例this.webServer = factory.getWebServer(getSelfInitializer());getBeanFactory().registerSingleton("webServerGracefulShutdown",new WebServerGracefulShutdownLifecycle(this.webServer));getBeanFactory().registerSingleton("webServerStartStop",new WebServerStartStopLifecycle(this, this.webServer));}else if (servletContext != null) {try {getSelfInitializer().onStartup(servletContext);}catch (ServletException ex) {throw new ApplicationContextException("Cannot initialize servlet context", ex);}}initPropertySources();
}

 getWebServer方法需要参数,该参数是一个方法getSelfInitializer(),找到

private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() {// 方法引用,ServletContextInitializer是一个函数是接口,通过方法引用返回一个实现        // ServletContextInitializer的一个实现子类,作用同匿名内部类。return this::selfInitialize;
}

函数式接口:

@FunctionalInterface
public interface ServletContextInitializer {/*** Configure the given {@link ServletContext} with any servlets, filters, listeners* context-params and attributes necessary for initialization.* @param servletContext the {@code ServletContext} to initialize* @throws ServletException if any call against the given {@code ServletContext}* throws a {@code ServletException}*/void onStartup(ServletContext servletContext) throws ServletException;}

this::selfInitialize就是实例::方法名调用方式,this代表当前对象,selfInitialize是this(ServletWebServerApplicationContext)对象的一个私有方法

private void selfInitialize(ServletContext servletContext) throws ServletException {prepareWebApplicationContext(servletContext);registerApplicationScope(servletContext);WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext);for (ServletContextInitializer beans : getServletContextInitializerBeans()) {beans.onStartup(servletContext);}
}

继续进入getWebServer,发现是一个接口,有三个实现类Jetty、Tomcat、UnderTow,我们是Tomcat服务器,进入TomcatServletWebServerFactory中的实现方法

@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {if (this.disableMBeanRegistry) {Registry.disableRegistry();}Tomcat tomcat = new Tomcat();File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");// 用于设置临时文件的目录,这些目录用于存放JSP生成的源代码及Class文件xtomcat.setBaseDir(baseDir.getAbsolutePath());Connector connector = new Connector(this.protocol);connector.setThrowOnFailure(true);tomcat.getService().addConnector(connector);customizeConnector(connector);// 用于设置链接器,包括协议、I/0、端口、压缩、加密等等tomcat.setConnector(connector);// 是否自动部署tomcat.getHost().setAutoDeploy(false);configureEngine(tomcat.getEngine());for (Connector additionalConnector : this.additionalTomcatConnectors) {tomcat.getService().addConnector(additionalConnector);}prepareContext(tomcat.getHost(), initializers);// 核心代码return getTomcatWebServer(tomcat);
}
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {return new TomcatWebServer(tomcat, getPort() >= 0, getShutdown());
}

进入TomcatWebServer构造方法

public TomcatWebServer(Tomcat tomcat, boolean autoStart, Shutdown shutdown) {Assert.notNull(tomcat, "Tomcat Server must not be null");this.tomcat = tomcat;this.autoStart = autoStart;this.gracefulShutdown = (shutdown == Shutdown.GRACEFUL) ? new GracefulShutdown(tomcat) : null;// 核心代码initialize();
}

 进入initialize()方法

private void initialize() throws WebServerException {logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));synchronized (this.monitor) {try {addInstanceIdToEngineName();Context context = findContext();context.addLifecycleListener((event) -> {if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {// Remove service connectors so that protocol binding doesn't// happen when the service is started.removeServiceConnectors();}});// 核心代码// Start the server to trigger initialization listenersthis.tomcat.start();// We can re-throw failure exception directly in the main threadrethrowDeferredStartupExceptions();try {ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());}catch (NamingException ex) {// Naming is not enabled. Continue}// Unlike Jetty, all Tomcat threads are daemon threads. We create a// blocking non-daemon to stop immediate shutdownstartDaemonAwaitThread();}catch (Exception ex) {stopSilently();destroySilently();throw new WebServerException("Unable to start embedded Tomcat", ex);}}
}
public void start() throws LifecycleException {getServer();// 核心代码server.start();
}

进入start()方法,找到LifecycleBase实现类方法

 LifecycleBase类中init();startInternal();两个核心方法

 @Override
public final synchronized void start() throws LifecycleException {if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) ||LifecycleState.STARTED.equals(state)) {if (log.isDebugEnabled()) {Exception e = new LifecycleException();log.debug(sm.getString("lifecycleBase.alreadyStarted", toString()), e);} else if (log.isInfoEnabled()) {log.info(sm.getString("lifecycleBase.alreadyStarted", toString()));}return;}if (state.equals(LifecycleState.NEW)) {// 核心代码1init();} else if (state.equals(LifecycleState.FAILED)) {stop();} else if (!state.equals(LifecycleState.INITIALIZED) &&!state.equals(LifecycleState.STOPPED)) {invalidTransition(Lifecycle.BEFORE_START_EVENT);}try {setStateInternal(LifecycleState.STARTING_PREP, null, false);// 核心代码2startInternal();if (state.equals(LifecycleState.FAILED)) {// This is a 'controlled' failure. The component put itself into the// FAILED state so call stop() to complete the clean-up.stop();} else if (!state.equals(LifecycleState.STARTING)) {// Shouldn't be necessary but acts as a check that sub-classes are// doing what they are supposed to.invalidTransition(Lifecycle.AFTER_START_EVENT);} else {setStateInternal(LifecycleState.STARTED, null, false);}} catch (Throwable t) {// This is an 'uncontrolled' failure so put the component into the// FAILED state and throw an exception.handleSubClassException(t, "lifecycleBase.startFail", toString());}
}

 init()方法

 @Override
public final synchronized void init() throws LifecycleException {if (!state.equals(LifecycleState.NEW)) {invalidTransition(Lifecycle.BEFORE_INIT_EVENT);}try {setStateInternal(LifecycleState.INITIALIZING, null, false);// 核心代码initInternal();setStateInternal(LifecycleState.INITIALIZED, null, false);} catch (Throwable t) {handleSubClassException(t, "lifecycleBase.initFail", toString());}
}

initInternal有很多实现类,看组件Connector中的实现方法

 组件Connector类型方法

@Override
protected void initInternal() throws LifecycleException {super.initInternal();if (protocolHandler == null) {throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerInstantiationFailed"));}// Initialize adapteradapter = new CoyoteAdapter(this);protocolHandler.setAdapter(adapter);if (service != null) {protocolHandler.setUtilityExecutor(service.getServer().getUtilityExecutor());}// Make sure parseBodyMethodsSet has a defaultif (null == parseBodyMethodsSet) {setParseBodyMethods(getParseBodyMethods());}if (protocolHandler.isAprRequired() && !AprStatus.isInstanceCreated()) {throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerNoAprListener",getProtocolHandlerClassName()));}if (protocolHandler.isAprRequired() && !AprStatus.isAprAvailable()) {throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerNoAprLibrary",getProtocolHandlerClassName()));}if (AprStatus.isAprAvailable() && AprStatus.getUseOpenSSL() &&protocolHandler instanceof AbstractHttp11JsseProtocol) {AbstractHttp11JsseProtocol<?> jsseProtocolHandler =(AbstractHttp11JsseProtocol<?>) protocolHandler;if (jsseProtocolHandler.isSSLEnabled() &&jsseProtocolHandler.getSslImplementationName() == null) {// OpenSSL is compatible with the JSSE configuration, so use it if APR is availablejsseProtocolHandler.setSslImplementationName(OpenSSLImplementation.class.getName());}}try {// 核心方法protocolHandler.init();} catch (Exception e) {throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerInitializationFailed"), e);}
}

进入实现类AbstractProtocol中init()方法

@Override
public void init() throws Exception {if (getLog().isInfoEnabled()) {getLog().info(sm.getString("abstractProtocolHandler.init", getName()));logPortOffset();}if (oname == null) {// Component not pre-registered so register itoname = createObjectName();if (oname != null) {Registry.getRegistry(null, null).registerComponent(this, oname, null);}}if (this.domain != null) {ObjectName rgOname = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName());this.rgOname = rgOname;Registry.getRegistry(null, null).registerComponent(getHandler().getGlobal(), rgOname, null);}String endpointName = getName();endpoint.setName(endpointName.substring(1, endpointName.length()-1));endpoint.setDomain(domain);// 核心代码endpoint.init();
}

进入endpoint.init()方法

public final void init() throws Exception {if (bindOnInit) {// 核心代码bindWithCleanup();bindState = BindState.BOUND_ON_INIT;}if (this.domain != null) {// Register endpoint (as ThreadPool - historical name)oname = new ObjectName(domain + ":type=ThreadPool,name=\"" + getName() + "\"");Registry.getRegistry(null, null).registerComponent(this, oname, null);ObjectName socketPropertiesOname = new ObjectName(domain +":type=SocketProperties,name=\"" + getName() + "\"");socketProperties.setObjectName(socketPropertiesOname);Registry.getRegistry(null, null).registerComponent(socketProperties, socketPropertiesOname, null);for (SSLHostConfig sslHostConfig : findSslHostConfigs()) {registerJmx(sslHostConfig);}}
}

进入bindWithCleanup方法里面 

private void bindWithCleanup() throws Exception {try {// 核心代码bind();} catch (Throwable t) {// Ensure open sockets etc. are cleaned up if something goes// wrong during bindExceptionUtils.handleThrowable(t);unbind();throw t;}
}
@Override
public void bind() throws Exception {// 核心代码initServerSocket();setStopLatch(new CountDownLatch(1));// Initialize SSL if neededinitialiseSsl();selectorPool.open(getName());
}

初始化Socket 

protected void initServerSocket() throws Exception {if (getUseInheritedChannel()) {// Retrieve the channel provided by the OSChannel ic = System.inheritedChannel();if (ic instanceof ServerSocketChannel) {serverSock = (ServerSocketChannel) ic;}if (serverSock == null) {throw new IllegalArgumentException(sm.getString("endpoint.init.bind.inherited"));}} else if (getUnixDomainSocketPath() != null) {SocketAddress sa = JreCompat.getInstance().getUnixDomainSocketAddress(getUnixDomainSocketPath());serverSock = JreCompat.getInstance().openUnixDomainServerSocketChannel();serverSock.bind(sa, getAcceptCount());if (getUnixDomainSocketPathPermissions() != null) {Path path = Paths.get(getUnixDomainSocketPath());Set<PosixFilePermission> permissions =PosixFilePermissions.fromString(getUnixDomainSocketPathPermissions());if (path.getFileSystem().supportedFileAttributeViews().contains("posix")) {FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(permissions);Files.setAttribute(path, attrs.name(), attrs.value());} else {java.io.File file = path.toFile();if (permissions.contains(PosixFilePermission.OTHERS_READ) && !file.setReadable(true, false)) {log.warn(sm.getString("endpoint.nio.perms.readFail", file.getPath()));}if (permissions.contains(PosixFilePermission.OTHERS_WRITE) && !file.setWritable(true, false)) {log.warn(sm.getString("endpoint.nio.perms.writeFail", file.getPath()));}}}} else {serverSock = ServerSocketChannel.open();socketProperties.setProperties(serverSock.socket());InetSocketAddress addr = new InetSocketAddress(getAddress(), getPortWithOffset());serverSock.bind(addr, getAcceptCount());}serverSock.configureBlocking(true); //mimic APR behavior
}

startInternal();

看下这个方法,找到Connector里面的startInternal()方法实现

@Override
protected void startInternal() throws LifecycleException {// Validate settings before startingString id = (protocolHandler != null) ? protocolHandler.getId() : null;if (id == null && getPortWithOffset() < 0) {throw new LifecycleException(sm.getString("coyoteConnector.invalidPort", Integer.valueOf(getPortWithOffset())));}setState(LifecycleState.STARTING);try {// 核心代码protocolHandler.start();} catch (Exception e) {throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerStartFailed"), e);}
}

进入protocolHandler.start();方法里面。进入AbstractProtocol里面的实现方法

@Override
public void start() throws Exception {if (getLog().isInfoEnabled()) {getLog().info(sm.getString("abstractProtocolHandler.start", getName()));logPortOffset();}// 核心代码endpoint.start();monitorFuture = getUtilityExecutor().scheduleWithFixedDelay(() -> {if (!isPaused()) {startAsyncTimeout();}}, 0, 60, TimeUnit.SECONDS);
}

找到endpoint.start()方法

public final void start() throws Exception {if (bindState == BindState.UNBOUND) {bindWithCleanup();bindState = BindState.BOUND_ON_START;}// 核心代码startInternal();
}

进入这个实现类里,找到实现方法

 

@Overridepublic void startInternal() throws Exception {if (!running) {running = true;paused = false;if (socketProperties.getProcessorCache() != 0) {processorCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,socketProperties.getProcessorCache());}if (socketProperties.getEventCache() != 0) {eventCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,socketProperties.getEventCache());}if (socketProperties.getBufferPool() != 0) {nioChannels = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,socketProperties.getBufferPool());}// Create worker collectionif (getExecutor() == null) {createExecutor();}initializeConnectionLatch();// 核心代码 *******// Start poller threadpoller = new Poller();Thread pollerThread = new Thread(poller, getName() + "-ClientPoller");// 设置进程的优先级pollerThread.setPriority(threadPriority);// 守护线程:当非守护线程销毁的时候,守护线程跟着销毁。当运行的唯一线程是守护线程时,        // Java虚拟机将退出pollerThread.setDaemon(true);// 开启线程pollerThread.start();startAcceptorThread();}}

Poller类是什么?

Poller里面的run方法

@Override
public void run() {// Loop until destroy() is called// 核心代码1 轮询while (true) {boolean hasEvents = false;try {if (!close) {hasEvents = events();if (wakeupCounter.getAndSet(-1) > 0) {// If we are here, means we have other stuff to do// Do a non blocking selectkeyCount = selector.selectNow();} else {keyCount = selector.select(selectorTimeout);}wakeupCounter.set(0);}if (close) {events();timeout(0, false);try {selector.close();} catch (IOException ioe) {log.error(sm.getString("endpoint.nio.selectorCloseFail"), ioe);}break;}// Either we timed out or we woke up, process events firstif (keyCount == 0) {hasEvents = (hasEvents | events());}} catch (Throwable x) {ExceptionUtils.handleThrowable(x);log.error(sm.getString("endpoint.nio.selectorLoopError"), x);continue;}Iterator<SelectionKey> iterator =keyCount > 0 ? selector.selectedKeys().iterator() : null;// Walk through the collection of ready keys and dispatch// any active event.while (iterator != null && iterator.hasNext()) {SelectionKey sk = iterator.next();iterator.remove();NioSocketWrapper socketWrapper = (NioSocketWrapper) sk.attachment();// Attachment may be null if another thread has called// cancelledKey()if (socketWrapper != null) {// 核心代码2processKey(sk, socketWrapper);}}// Process timeoutstimeout(keyCount,hasEvents);}getStopLatch().countDown();
}

启动一个Poller线程轮询监听NIO接收的请求,直到执行核心代码2processKey(sk, socketWrapper);Poller类会轮询监听Socket连接,到这里tomcat算启动成功啦。

springboot嵌入tomcat处理请求的过程

主要看下Poller类中的processKey方法,我们发起一个请求怎么处理的呢?

processKey方法

protected void processKey(SelectionKey sk, NioSocketWrapper socketWrapper) {try {if (close) {cancelledKey(sk, socketWrapper);} else if (sk.isValid() && socketWrapper != null) {if (sk.isReadable() || sk.isWritable()) {if (socketWrapper.getSendfileData() != null) {processSendfile(sk, socketWrapper, false);} else {unreg(sk, socketWrapper, sk.readyOps());boolean closeSocket = false;// Read goes before writeif (sk.isReadable()) {if (socketWrapper.readOperation != null) {// 核心代码if (!socketWrapper.readOperation.process()) {closeSocket = true;}// 核心代码} else if (!processSocket(socketWrapper, SocketEvent.OPEN_READ, true)) {closeSocket = true;}}if (!closeSocket && sk.isWritable()) {if (socketWrapper.writeOperation != null) {if (!socketWrapper.writeOperation.process()) {closeSocket = true;}} else if (!processSocket(socketWrapper, SocketEvent.OPEN_WRITE, true)) {closeSocket = true;}}if (closeSocket) {cancelledKey(sk, socketWrapper);}}}} else {// Invalid keycancelledKey(sk, socketWrapper);}} catch (CancelledKeyException ckx) {cancelledKey(sk, socketWrapper);} catch (Throwable t) {ExceptionUtils.handleThrowable(t);log.error(sm.getString("endpoint.nio.keyProcessingError"), t);}
}

进入processSocket方法

public boolean processSocket(SocketWrapperBase<S> socketWrapper,SocketEvent event, boolean dispatch) {try {if (socketWrapper == null) {return false;}// 核心代码 线程SocketProcessorBase<S> sc = null;if (processorCache != null) {sc = processorCache.pop();}if (sc == null) {sc = createSocketProcessor(socketWrapper, event);} else {sc.reset(socketWrapper, event);}// 核心代码 获取线程池,通过线程池执行Executor executor = getExecutor();if (dispatch && executor != null) {executor.execute(sc);} else {sc.run();}} catch (RejectedExecutionException ree) {getLog().warn(sm.getString("endpoint.executor.fail", socketWrapper) , ree);return false;} catch (Throwable t) {ExceptionUtils.handleThrowable(t);// This means we got an OOM or similar creating a thread, or that// the pool and its queue are fullgetLog().error(sm.getString("endpoint.process.fail"), t);return false;}return true;
}

看看SocketProcessBase是什么?  实现了Runnable接口 

看下SocketProcessBase的run()方法

 @Overridepublic final void run() {synchronized (socketWrapper) {// It is possible that processing may be triggered for read and// write at the same time. The sync above makes sure that processing// does not occur in parallel. The test below ensures that if the// first event to be processed results in the socket being closed,// the subsequent events are not processed.if (socketWrapper.isClosed()) {return;}// 核心代码doRun();}}

看下doRun()方法

找到过滤器链ApplicationFilterChain,找到doFilter()方法

@Override
public void doFilter(ServletRequest request, ServletResponse response)throws IOException, ServletException {if( Globals.IS_SECURITY_ENABLED ) {final ServletRequest req = request;final ServletResponse res = response;try {java.security.AccessController.doPrivileged((java.security.PrivilegedExceptionAction<Void>) () -> {// 核心代码internalDoFilter(req,res);return null;});} catch( PrivilegedActionException pe) {Exception e = pe.getException();if (e instanceof ServletException)throw (ServletException) e;else if (e instanceof IOException)throw (IOException) e;else if (e instanceof RuntimeException)throw (RuntimeException) e;elsethrow new ServletException(e.getMessage(), e);}} else {internalDoFilter(request,response);}
}

定位到internalDoFilter()方法

private void internalDoFilter(ServletRequest request,ServletResponse response)throws IOException, ServletException {// Call the next filter if there is oneif (pos < n) {ApplicationFilterConfig filterConfig = filters[pos++];try {Filter filter = filterConfig.getFilter();if (request.isAsyncSupported() && "false".equalsIgnoreCase(filterConfig.getFilterDef().getAsyncSupported())) {request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);}if( Globals.IS_SECURITY_ENABLED ) {final ServletRequest req = request;final ServletResponse res = response;Principal principal =((HttpServletRequest) req).getUserPrincipal();Object[] args = new Object[]{req, res, this};SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal);} else {filter.doFilter(request, response, this);}} catch (IOException | ServletException | RuntimeException e) {throw e;} catch (Throwable e) {e = ExceptionUtils.unwrapInvocationTargetException(e);ExceptionUtils.handleThrowable(e);throw new ServletException(sm.getString("filterChain.filter"), e);}return;}// We fell off the end of the chain -- call the servlet instancetry {if (ApplicationDispatcher.WRAP_SAME_OBJECT) {lastServicedRequest.set(request);lastServicedResponse.set(response);}if (request.isAsyncSupported() && !servletSupportsAsync) {request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,Boolean.FALSE);}// Use potentially wrapped request from this pointif ((request instanceof HttpServletRequest) &&(response instanceof HttpServletResponse) &&Globals.IS_SECURITY_ENABLED ) {final ServletRequest req = request;final ServletResponse res = response;Principal principal =((HttpServletRequest) req).getUserPrincipal();Object[] args = new Object[]{req, res};SecurityUtil.doAsPrivilege("service",servlet,classTypeUsedInService,args,principal);} else {// 核心代码servlet.service(request, response);}} catch (IOException | ServletException | RuntimeException e) {throw e;} catch (Throwable e) {e = ExceptionUtils.unwrapInvocationTargetException(e);ExceptionUtils.handleThrowable(e);throw new ServletException(sm.getString("filterChain.servlet"), e);} finally {if (ApplicationDispatcher.WRAP_SAME_OBJECT) {lastServicedRequest.set(null);lastServicedResponse.set(null);}}
}

定位到service()方法的实现类HttpServlet中的service()方法中

@Overridepublic 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(lStrings.getString("http.non_http"));}// 核心代码service(request, response);}

继续进入到service()方法中

protected final void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {long startTime = System.currentTimeMillis();Throwable failureCause = null;LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();LocaleContext localeContext = buildLocaleContext(request);RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());initContextHolders(request, localeContext, requestAttributes);try {// 核心代码doService(request, response);}catch (ServletException | IOException ex) {failureCause = ex;throw ex;}catch (Throwable ex) {failureCause = ex;throw new NestedServletException("Request processing failed", ex);}finally {resetContextHolders(request, previousLocaleContext, previousAttributes);if (requestAttributes != null) {requestAttributes.requestCompleted();}logResult(request, response, failureCause, asyncManager);publishRequestHandledEvent(request, response, startTime, failureCause);}
}

 进入doService()方法

 https://blog.csdn.net/z69183787/article/details/129240218
https://blog.csdn.net/sunshinezx8023/article/details/128630710

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/325868.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

spark的任务提交方式及流程

本地模式 local 测试用,不多赘述 分布式模式 standalone standalone集群是spark 自带的一个资源调度集群&#xff0c;分为两个角色&#xff0c;master/worker&#xff0c;master负责接收任务请求、资源调度&#xff08;监听端口7077&#xff09;&#xff0c;worker负责运行exec…

win10报错“zlib.dll文件丢失,软件无法启动”,修复方法,亲测有效

zlib.dll文件是一个由Zlib创建的动态链接库文件&#xff0c;它是用于Windows操作系统的数据压缩和解压缩的软件。Zlib是一个广泛使用的软件库&#xff0c;广泛应用在许多不同类型的软件中&#xff0c;包括游戏、浏览器和操作系统。 zlib.dll的主要作用是提供数据压缩和解压缩的…

50N65-ASEMI高压N沟道MOS管50N65

编辑&#xff1a;ll 50N65-ASEMI高压N沟道MOS管50N65 型号&#xff1a;50N65 品牌&#xff1a;ASEMI 封装&#xff1a;TO-247 连续漏极电流(Id)&#xff1a;50A 漏源电压(Vdss)&#xff1a;650V 功率(Pd)&#xff1a;388W 芯片个数&#xff1a;2 引脚数量&#xff1a;…

Jupyter Lab | 在指定文件夹的 jupyter 中使用 conda 虚拟环境

Hi&#xff0c;大家好&#xff0c;我是源于花海。本文主要了解如何在指定文件夹的 jupyter 中使用 conda 虚拟环境&#xff0c;即在 conda 里面创建虚拟环境、将虚拟环境添加至 jupyter lab/notebook、安装软件包。 目录 一、创建虚拟环境 二、激活并进入虚拟环境 三、安装 …

差分约束算法

差分约束 差分约束系统包含 m m m个涉及 n n n个变量的差额限制条件&#xff0c;这些差额限制条件每个都是形式为 x i − x j ≤ b ∈ [ 1 , m ] x_i-x_j\leq b_{\in[1,m]} xi​−xj​≤b∈[1,m]​的简单线性不等式。 通常我们要求解出一组可行解。 最短路差分约束 如果我们…

Pygame和Cocos2d

Pygame和Cocos2d都是 Python 中常用的游戏引擎&#xff0c;但它们的设计目标、特点和使用场景略有不同。 Pygame与Cocos2d&#xff0c;目前是使用人数最多的两个Python游戏库。根据某知名产品点评网站的数据显示&#xff0c;排名前五的Python 2D游戏库如下图所示。其中&#x…

16.顺子日期(14)

题目 public class Main {public static boolean isLegal(String date) {int l 0;int n date.length();while(l<(n-3)) {int t1 (int)Integer.valueOf(date.substring(l,l1));int t2 (int)Integer.valueOf(date.substring(l1,l2));int t3 (int)Integer.valueOf(date.s…

Spring——Spring AOP1(代理模式Proxy)

代理&#xff08;Proxy&#xff09;模式 1.创建工程 2.代理&#xff08;Proxy&#xff09;模式介绍 作用&#xff1a;通过代理可以控制访问某个对象的方法&#xff0c;在调用这个方法前做前置处理&#xff0c;调用这个方法后做后置处理。&#xff08;即&#xff1a; AOP的微观…

多线程基础知识点

1. 进程 一个正在执行中的程序就是一个进程&#xff0c;系统会为这个进程发配独立的【内存资源】。进程是程序的一次执行过程&#xff0c;它有自己独立的生命周期&#xff0c;它会在启动程序时产生&#xff0c;运行程序时存在&#xff0c;关闭程序时消亡。 例如&#xff1a;正…

57.6K star!一个免费开源的 API 开发生态系统

&#xff01;&#xff01;&#xff01;文末有链接&#xff01;&#xff01;&#xff01; 小伙伴们&#xff0c;你们有没有遇到这样的问题呢&#xff1f;当你作为前端开发者和后端开发者一起协同工作时&#xff0c;联调接口成了必须要做的工作。 而为了验证接口的稳定性和安全…

【Linux操作系统】探秘Linux奥秘:shell 编程的解密与实战

&#x1f308;个人主页&#xff1a;Sarapines Programmer&#x1f525; 系列专栏&#xff1a;《操作系统实验室》&#x1f516;诗赋清音&#xff1a;柳垂轻絮拂人衣&#xff0c;心随风舞梦飞。 山川湖海皆可涉&#xff0c;勇者征途逐星辉。 目录 &#x1fa90;1 初识Linux OS &…

技术概述:ARMv8体系结构

John Goodacre, Director Program Management ARM Processor Division, November 2011 背景&#xff1a;ARM体系结构 从ARM精简指令集体系结构提出到现在已经有20多年了&#xff1b;ARMv7系列处理器是在ARMv4基础上设计的&#xff0c;随着ARMv7系列处理器大量应用&#xff0…