傳統(tǒng)servlet在spring中的應(yīng)用

一、Servlet
servlet用于生成動態(tài)內(nèi)容。webflux不是基于servlet容器。
靜態(tài)內(nèi)容由nginx生成,通過io的方式去讀取文件。
http(request,response):是一個(gè)單路的協(xié)議。一次請求完后就結(jié)束了。而且服務(wù)端是被動的一方。其實(shí)我們可以把http請求看作是一個(gè)消息,一個(gè)消息會有兩部分東西,一個(gè)是消息的content(body/payload),一個(gè)是消息的header,包含(destination)。
什么是雙路協(xié)議?
比如長連接,比如既有客戶端向服務(wù)端發(fā)送請求,也有服務(wù)端向客戶端推送響應(yīng)。比如websocket協(xié)議,以及http2。

請求頭或者請求體就是一個(gè)輸入,servlet APi負(fù)責(zé)解析這些內(nèi)容(一般由servlet容器完成)。

契約(API):一種編程模式
編程模型:按照一定規(guī)范去操作API
大家都實(shí)現(xiàn)javax.servlet api,至于你是什么容器,不care
servlet容器有:tomcat,jetty,undertow。
servlet容器就是提供servlet的運(yùn)行時(shí)環(huán)境。
什么是運(yùn)行時(shí)環(huán)境?
請求從我們的客戶端到服務(wù)端,服務(wù)端會解析一些客戶端的輸入,如請求url,請求體,請求頭等,正是有了運(yùn)行時(shí)環(huán)境,我不需要自己去解析這些請求頭啊請求體啊等等,servlet容器會幫我解析這些,我只要直接取出來用就好了。

MIME類型就是字描述消息。
http是文本協(xié)議,文本協(xié)議就意味著有格式,格式就會有很多種方式,
比如,html是一種格式,xml是一種格式,json是一種格式,
無論是哪種格式,我需要有對應(yīng)的視圖去進(jìn)行渲染。

servlet規(guī)范是屬于J2ee的一部分,
Wikipedia對servlet:
(1)Pluggability :表示servlet可以通過java API以編程的方式進(jìn)行配置,組裝,而不是僅僅是原來的web.xml配置方式。
(2)Ease of development :更加容易部署,為什么?可以通過jar包的形式進(jìn)行部署,而不需要利用web.xml的方式。
(3)Async Servlet: 異步
(4)Security:java security + servlet security(認(rèn)證+授權(quán))
(5)NIO:注意non blocking不代表異步,同步異步和阻塞非阻塞是兩個(gè)維度的概念。
(6)Http protocol upgrade mechanism(websocket): http協(xié)議升級,比如客戶端發(fā)出請求,想把http協(xié)議升級,升級后從http編程socket,需要瀏覽器支持。

Reactive streams APi規(guī)范,通過一套統(tǒng)一的API實(shí)現(xiàn)非阻塞編程。
Reactive streams是流式編程:process1->process2->process3
前面的計(jì)算和后面的計(jì)算必須有強(qiáng)關(guān)聯(lián),process1的結(jié)果result1,會作為process2的輸入,以此類推。它不關(guān)心你是同步還是異步。

二、Servlet組件


image.png

servlet組件:servlet,filter,listener
filter的執(zhí)行順序:部署描述符里面定義的order
The order the container uses in building the chain of filters to be applied for a
particular request URI is as follows:

  1. First, the <url-pattern> matching filter mappings in the same order that these
    elements appear in the deployment descriptor.
  2. Next, the <servlet-name> matching filter mappings in the same order that these
    elements appear in the deployment descriptor

jsp九大對象:
ApplicationContext,sessionContext,requestContext,pageContext,

JSP是WEB渲染視圖框架中性能最好的。為什么?
因?yàn)镴SP會編譯成java class,
運(yùn)行時(shí)解釋還是編譯時(shí)解釋?
靜態(tài)語言是編譯時(shí)解釋,動態(tài)語言是運(yùn)行時(shí)解釋。

三、Listener ->Application LifeCycle Event

四、spring運(yùn)用


image.png

1, RootWebApplicationContext
2,ServletWebApplicationContext
RootWebApplicationContext is the parent of ServletWebApplicationContext.
RootWebApplicationContext是讀不到ServletWebApplicationContext的bean的。子類是可以獲取得到父類所管理的bean。
所以ServletWebApplicationContext中的bean是可以讀到RootWebApplicationContext中的bean,但是,RootWebApplicationContext中的bean是讀不到ServletWebApplicationContext中的bean的。原因是雙親委派模型。
所以我們從來不會在Service中引用被標(biāo)記為Controller的對象,而只在Controller中引用被標(biāo)記為Service的對象。

可以試試看在Service中引用Controller.

<web-app>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-context.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>

</web-app>

web.xml中
1,首先會定義一個(gè)ContextLoaderListener
ContextLoaderListener是ServletContextListener的實(shí)現(xiàn)類,負(fù)責(zé)初始化ServletContext(也就是ApplicationContext)。
ServletContext是servlet規(guī)范中的概念,
ApplicationContext是Spring中的概念。

    public void contextInitialized(ServletContextEvent event) {
        this.initWebApplicationContext(event.getServletContext());
    }

在ServletContext(container)啟動的時(shí)候,會調(diào)用父類ContextLoader的initWebApplicationContext().
實(shí)例化初始化一個(gè)RootWebApplicationContext,然后在instantiate a ServletWebApplicationContext,注意這個(gè)時(shí)候DispatcherServlet還沒有被初始化。servlet是在container啟動之后才會進(jìn)行加載和初始化的。

2,然后再定義一個(gè)DispatcherServlet
為什么要這樣?

3,servletContext,HttpSession,ServletRequest的那幾個(gè)Listener,其實(shí)關(guān)系到他們的生命周期。ServletContextListener的任務(wù)就是初始化ServletContext,所以它的實(shí)現(xiàn)必須在ServletContext初始化之前。
**contextConfigLocation:config location for the root context

4,打包。嵌入式的包,其實(shí)就是把war包打成Jar包,然后以java jar的形式運(yùn)行。
打包命令:mvc clean package
pom.xml中配置通過maven打一個(gè)嵌入式的jar包:

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <id>tomcat-run</id>
                        <goals>
                            <goal>exec-war-only</goal>
                        </goals>
                        <phase>package</phase>
                        <configuration>
                            <path>/</path>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

打完后,在target目錄下會出現(xiàn)一個(gè)servlet-in-spring-1.0-SNAPSHOT-war-exec.jar和
servlet-in-spring-1.0-SNAPSHOT.war,你會發(fā)現(xiàn)jar比war大很多,為什么?因?yàn)閖ar包中包含了嵌入式的tomcat。
查看target目錄:

27608 -rw-r--r--   1 xixi  staff  14128471 Apr 24 15:47 servlet-in-spring-1.0-SNAPSHOT-war-exec.jar
10304 -rw-r--r--   1 xixi  staff   5275316 Apr 24 15:46 servlet-in-spring-1.0-SNAPSHOT.war

5,增加app-context.xml,注意在/webapp/META-INF/app-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

</beans>

6,運(yùn)行java -jar servlet-in-spring-1.0-SNAPSHOT-war-exec.jar

四月 24, 2019 5:18:40 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-bio-8080"]
四月 24, 2019 5:18:40 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service Tomcat
四月 24, 2019 5:18:40 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/7.0.37
四月 24, 2019 5:18:42 下午 org.apache.catalina.core.ApplicationContext log
信息: No Spring WebApplicationInitializer types detected on classpath
四月 24, 2019 5:18:42 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring root WebApplicationContext
四月 24, 2019 5:18:42 下午 org.springframework.web.context.ContextLoader initWebApplicationContext
信息: Root WebApplicationContext: initialization started
四月 24, 2019 5:18:42 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing Root WebApplicationContext: startup date [Wed Apr 24 17:18:42 CST 2019]; root of context hierarchy
四月 24, 2019 5:18:42 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from ServletContext resource [/WEB-INF/app-context.xml]
四月 24, 2019 5:18:45 下午 org.springframework.web.context.ContextLoader initWebApplicationContext
信息: Root WebApplicationContext: initialization completed in 2865 ms
四月 24, 2019 5:18:45 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring FrameworkServlet 'app'
四月 24, 2019 5:18:45 下午 org.springframework.web.servlet.FrameworkServlet initServletBean
信息: FrameworkServlet 'app': initialization started
四月 24, 2019 5:18:45 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing WebApplicationContext for namespace 'app-servlet': startup date [Wed Apr 24 17:18:45 CST 2019]; parent: Root WebApplicationContext
四月 24, 2019 5:18:45 下午 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
信息: Looking for @ControllerAdvice: WebApplicationContext for namespace 'app-servlet': startup date [Wed Apr 24 17:18:45 CST 2019]; parent: Root WebApplicationContext
四月 24, 2019 5:18:46 下午 org.springframework.web.servlet.FrameworkServlet initServletBean
信息: FrameworkServlet 'app': initialization completed in 257 ms
四月 24, 2019 5:18:46 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-bio-8080"]

從日志中,我們可以發(fā)現(xiàn)啟動順序:
1,Starting Servlet Engine: Apache Tomcat/7.0.37
2,No Spring WebApplicationInitializer types detected on classpath
3, Initializing Spring root WebApplicationContext:
contextConfigLocation:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>

先創(chuàng)建一個(gè)RootServletContext,然后configure這個(gè)RootServletContext,配置的過程中會通過getInitParameter("contextConfigLocation")就可以獲取到WEB-INF/app-context.xml,然后在loadBeanDefinitions的時(shí)候就可以讀取app-context.xml中的內(nèi)容。

4, Root WebApplicationContext: initialization started
5, Refreshing Root WebApplicationContext
6,Loading XML bean definitions from ServletContext resource [/WEB-INF/app-context.xml]
7, Root WebApplicationContext: initialization completed in 2865 ms
8, Initializing Spring FrameworkServlet 'app',其實(shí)就是DispatcherServlet

 <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

'app'就是DispatcherServlet的別名。
在RootWebApplicationContext啟動之后,才會去初始化DispatcherServlet。
DispatcherServlet extends FrameworkServlet extends HttpServletBean
那么什么時(shí)候去加載和實(shí)例化DispatcherServlet?
一般是容器啟動后的時(shí)候,
而初始化DispatcherServlet是去調(diào)用Servlet的init(ServletConfig config).
最后會去調(diào)用HttpServletBean的init()。
我們配置的init-param會放在ServletConfig中。怎么實(shí)現(xiàn)的?
也就是說配置文件中的<param-name>contextConfigLocation</param-name>怎么和FrameworkServlet類中的字段contextConfigLocation進(jìn)行綁定?
HttpServletBean#init()中的這段代碼實(shí)現(xiàn)了這個(gè)功能。如下:

BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
                ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
                bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
                initBeanWrapper(bw);
                bw.setPropertyValues(pvs, true);

采用了java bean的內(nèi)省機(jī)制。
你也可以配置多個(gè)<init-param>,只要是對應(yīng)的Servlet的字段,都可以通過內(nèi)省機(jī)制讓你的配置項(xiàng)的值和相應(yīng)的字段綁定上。其實(shí)就是將我的Servlet配置信息和我的Servlet Bean進(jìn)行綁定上。
contextLoader必然在DispatcherServlet之前執(zhí)行?為什么?
ContextLoaderListener負(fù)責(zé)加載,實(shí)例化,配置RootWebApplicationContext,會作為我的DispatcherServelet所在的ServletWebApplicationContext的父類?
ServletWebApplicationContext其實(shí)是由DispatcherServelet去初始化的。
看代碼:
HttpServletBean#init()->
FrameworkServlet#initServletBean()->
首先initWebApplicationContext()

WebApplicationContext rootContext =
            WebApplicationContextUtils.getWebApplicationContext(getServletContext());

在初始化ServletWebApplicationContext的過程中會去讀取RootWebApplicationContext,
我們之前把RootWebApplicationContext保存在ServletContext中(見ContextLoader#initWebApplicationContext(ServletContext servletContext))。
所以現(xiàn)在可以從ServletContext中取出來。
然后initFrameworkServlet()

9,FrameworkServlet 'app': initialization started

10,Refreshing WebApplicationContext for namespace 'app-servlet': startup date [Wed Apr 24 17:18:45 CST 2019]; parent: Root WebApplicationContext

11,Looking for @ControllerAdvice: WebApplicationContext for namespace 'app-servlet': startup date [Wed Apr 24 17:18:45 CST 2019]; parent: Root WebApplicationContext

12,FrameworkServlet 'app': initialization completed in 257 ms

7,filter或Servlet的類的字段,好像都可以使用web.xml中的<init-param>進(jìn)行配置。

8,web.xml中關(guān)于servlet的配置信息會放在ServletConfig中,關(guān)于FIlter的配置信息會放在FilterConfig中。注意,F(xiàn)ilter的配置無論是在前面還是后面,filter都會比它攔截的Servlet要先執(zhí)行,這事關(guān)生命周期,于配置的順序無關(guān)。

9,<load-on-startup>1</load-on-startup>可以指定Servlet的initialize順序,按1,2,3...初始化。

五、FIlter
1,在web.xml中配置,映射到相應(yīng)的Servlet-name上面。

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <servlet-name>app</servlet-name>
    </filter-mapping>

CharacterEncodingFilter#init()->
GenericFilterBean#init()
在GenericFilterBean#init()中也會有一段代碼,將你在web.xml中配置的值與CharacterEncodingFilter的對應(yīng)字段相綁定。和HttpServletBean#init()套路差不多。

BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
                ResourceLoader resourceLoader = new ServletContextResourceLoader(filterConfig.getServletContext());
                Environment env = this.environment;
                if (env == null) {
                    env = new StandardServletEnvironment();
                }

                bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, (PropertyResolver)env));
                this.initBeanWrapper(bw);
                bw.setPropertyValues(pvs, true);

2,如果有多個(gè)Filter1,F(xiàn)ilter2都攔截同一個(gè)Servlet,那么這兩個(gè)Filter的執(zhí)行順序如何安排?
Filters that match a request are chained in the order in which they are declared in the web.xml.
也就是說Filter會按照它們在web.xml中配置的順序進(jìn)行執(zhí)行。

六、Listener的調(diào)用順序
1,實(shí)現(xiàn)了javax.servlet.ServletContextListener的監(jiān)聽器的()將會以聲明時(shí)的順序調(diào)用,而contextDestroyed()將會以相反的順序調(diào)用。
2,實(shí)現(xiàn)了javax.servlet.ServletRequestListener的監(jiān)聽器的requestInitialized()將會以聲明時(shí)的順序調(diào)用,而requestDestroyed()將會以相反的順序調(diào)用。
3,。。。

七、
1,當(dāng)在 web.xml、web-fragment.xml 和 注解之間解析發(fā)生沖突時(shí) web 應(yīng)用的 web.xml具有最高優(yōu)先級。
2,如果web.xml的metadata-complete屬性被設(shè)置為True,則將會忽略所有的注解配置和web-fragment.xml的配置。如果是web-fragment.xml的metadata-complete=true,則忽略web-fragment.xml的配置不會忽略注解的配置。
3,

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容