注: 該章節(jié)主要為原創(chuàng)內(nèi)容,為后續(xù)的Spring MVC內(nèi)容做一個(gè)先行鋪墊
1.Servlet的構(gòu)建使用
(1) 選擇Maven -> webapp來(lái)構(gòu)建一個(gè)web應(yīng)用

(2) 構(gòu)建好后,打開pom.xml文件,一要注意打包方式為war包,二導(dǎo)入servlet依賴,如下
<!-- 打war包 -->
<packaging>war</packaging>
<!-- 導(dǎo)入servlet依賴 -->
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
(3) 替換webapp/WEB-INF/web.xml文件為如下內(nèi)容,采用Servlet 3.1版本
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
</web-app>
(4) 在main目錄下,新建java目錄和resources目錄,并在java目錄下新建包,最終項(xiàng)目目錄結(jié)構(gòu)如下

(5) 編寫一個(gè)簡(jiǎn)單的servlet如下
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("example...");
}
}
(6) 有了servlet后,我們得讓服務(wù)器知道哪個(gè)請(qǐng)求要交給哪個(gè)servlet處理,因此還需要配置web.xml如下
<!-- web.xml中 -->
<web-app ...>
<!-- 配置servlet,給指定的servlet取一個(gè)名字 -->
<servlet>
<servlet-name>exampleServlet</servlet-name>
<servlet-class>cn.example.springmvc.boke.servlet.ExampleServlet</servlet-class>
</servlet>
<!-- 配置哪個(gè)請(qǐng)求交由哪個(gè)servlet來(lái)進(jìn)行處理,這里為了方便使用 / ,即攔截所有的請(qǐng)求都交由exampleServlet來(lái)處理 -->
<servlet-mapping>
<servlet-name>exampleServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
(7) 然后,為了能夠在網(wǎng)頁(yè)上訪問(wèn),我們得把這個(gè)項(xiàng)目部署到tomcat服務(wù)器中
首先,在URL欄中,添加上項(xiàng)目名稱,此處為springmvc

然后,在Deployment中添加我們的項(xiàng)目

最后,注意 Application Context 中的值,應(yīng)與前面在URL欄中添加的項(xiàng)目名稱相同,此處均為springmvc

(8) 最后,啟動(dòng)tomcat服務(wù)器,在瀏覽器上輸入 http://localhost:8080/springmvc/example ,如果能看到 example... 字符串,則說(shuō)明項(xiàng)目配置成功
2.基于web.xml,整合Spring與Servlet
(1) 現(xiàn)在,web應(yīng)用已經(jīng)搭建好了,但是我們希望能夠在該應(yīng)用中使用Spring容器,該怎么辦呢? 在之前的非web環(huán)境中,我們都是在main方法中創(chuàng)建ioc容器(如 new ClassPathXmlApplicationContext()),然后直接使用的,但是現(xiàn)在沒有了main方法,該由誰(shuí)來(lái)創(chuàng)建ioc容器呢? 答案就是由我們的web容器,可以在web應(yīng)用初始化的時(shí)候來(lái)幫助我們創(chuàng)建,但創(chuàng)建好之后,我們?cè)撛趺传@取到ioc容器呢? Servlet規(guī)定了4大作用域,分別為page域(PageContext),當(dāng)前頁(yè)面有效; request域(HttpServletContext),一次請(qǐng)求內(nèi)有效; session域(HttpSession),一次會(huì)話內(nèi)有效; application域(ServletContext),在當(dāng)前整個(gè)web應(yīng)用內(nèi)有效,因此我們可以將創(chuàng)建好的ioc容器直接放到application域中,這樣在任何位置,我們都能拿到ioc容器進(jìn)行使用,具體示例如下
首先導(dǎo)入相關(guān)的Spring依賴包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.22.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.22.RELEASE</version>
</dependency>
</dependencies>
接著,修改我們的代碼,配置一個(gè)普通的bean
//創(chuàng)建一個(gè)普通的java類
public class ExampleService {
public String get() {
return "user";
}
}
//然后,在resources目錄下新建一個(gè)springmvc.xml,并將上面的ExampleService注冊(cè)為一個(gè)bean
<beans ....>
<bean class="cn.example.springmvc.boke.service.ExampleService"></bean>
</beans>
接下來(lái),我們就得讓web容器來(lái)為我們創(chuàng)建ioc容器了,具體由誰(shuí)來(lái)創(chuàng)建呢? Servlet有三大核心組件,即Servlet,用于處理請(qǐng)求;Filter,過(guò)濾器,用來(lái)攔截或修改請(qǐng)求;Listener,監(jiān)聽器,用于監(jiān)聽某個(gè)事件。顯然,這里使用Listener最合適,那就由Listener來(lái)為我們創(chuàng)建ioc容器
<!-- web.xml中 -->
<!-- 當(dāng)然,具體的Listener實(shí)現(xiàn)類代碼是不需要由我們來(lái)寫的,因?yàn)镾pring早已內(nèi)置了一個(gè)監(jiān)聽器(ContextLoaderListener),就是用于在基于web.xml的配置中來(lái)初始化ioc容器 -->
<web-app ....>
<!-- ContextLoaderListener實(shí)現(xiàn)了ServletContextListener,而這個(gè)ServletContextListener就是用于監(jiān)聽web應(yīng)用的生命周期的,當(dāng)web容器啟動(dòng)或終止web應(yīng)用的時(shí)候,會(huì)觸發(fā)ServletContextEvent事件,而該事件就會(huì)由ServletContextListener來(lái)處理,因此ContextLoaderListener就會(huì)在web應(yīng)用啟動(dòng)的同時(shí)創(chuàng)建ioc容器,加載配置文件,具體可詳見源碼 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 注意:如果未指定配置文件的路徑,那么默認(rèn)會(huì)尋找/WEB-INF/applicationContext.xml配置文件,如果這個(gè)配置文件找不到,啟動(dòng)時(shí)就會(huì)報(bào)錯(cuò)
基于web.xml的配置所創(chuàng)建的ioc容器是基于xml配置的ioc容器(XmlWebApplicationContext),它會(huì)在容器啟動(dòng)的時(shí)候讀取加載配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</context-param>
<servlet>
<servlet-name>exampleServlet</servlet-name>
<servlet-class>cn.example.springmvc.boke.servlet.ExampleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>exampleServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
現(xiàn)在ioc容器有了,而且被Spring以WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE為key放到了application域中,現(xiàn)在我們可以在任何地方被獲取到它,如下所示
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//獲取application域中的ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE屬性值,即我們的ioc容器
XmlWebApplicationContext ctx = (XmlWebApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//或者也可以使用Spring提供的工具類WebApplicationContextUtils來(lái)獲取ioc容器,如下
//XmlWebApplicationContext ctx = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
//使用ioc容器,獲取其中的bean
ExampleService exampleService = ctx.getBean(ExampleService.class);
resp.getWriter().write(exampleService.get());
}
}
//最后,重新啟動(dòng)容器,訪問(wèn) http://localhost:8080/springmvc/example,會(huì)發(fā)現(xiàn)頁(yè)面上出現(xiàn) user 字符串
當(dāng)然,向上面這樣每次都通過(guò)get方法獲取,很麻煩,我們可以借助Spring提供的工具類,在Servlet初始化的時(shí)候?qū)ervlet進(jìn)行依賴注入,如下
@WebServlet(urlPatterns = "/example")
public class ExampleServlet extends HttpServlet {
//使用@Autowired注解標(biāo)注需要進(jìn)行依賴注入的bean
@Autowired
private ExampleService exampleService;
//Servlet初始化方法
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
//獲取application域
ServletContext servletContext = config.getServletContext();
//使用Spring提供的自動(dòng)注入工具類SpringBeanAutowiringSupport,直接進(jìn)行依賴注入
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, servletContext);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println(exampleService.get());
}
}
3.基于Servlet擴(kuò)展接口,整合Spring與Servlet
(1) 在上一節(jié)中,我們將ioc的創(chuàng)建配置于web.xml中,但此外我們還可以利用java代碼的方式來(lái)創(chuàng)建ioc容器,可通過(guò)Servlet 3.0提供的ServletContainerInitializer接口,來(lái)在web容器啟動(dòng)的時(shí)候?yàn)榈谌浇M件提供初始化的機(jī)會(huì)(例如注冊(cè)Servlet等),如果要使用ServletContainerInitializer接口,那么就必須要在項(xiàng)目或所其依賴的jar包中的/META-INF/services目錄下創(chuàng)建一個(gè)名稱為javax.servlet.ServletContainerInitializer 的文件,而這個(gè)文件的具體內(nèi)容,就是ServletContainerInitializer實(shí)現(xiàn)類的全限定類名稱,然后,借助java的SPI技術(shù),web容器便會(huì)加載這些實(shí)現(xiàn)類,通常情況下,ServletContainerInitializer這個(gè)接口通常會(huì)配合@HandlesTypes注解一起使用,而這個(gè)@HandlesTypes注解的作用就是讓web容器收集我們項(xiàng)目中所有所指定的類,然后將這些類作為ServletContainerInitializer的onStartup方法參數(shù)傳入,這樣,在web容器啟動(dòng)的時(shí)候,我們就可以拿到這些我們所需的類然后創(chuàng)建它們
當(dāng)然,同上面web.xml中的ContextLoaderListener,Spring也提供了一個(gè)ServletContainerInitializer接口的實(shí)現(xiàn)類SpringServletContainerInitializer,來(lái)創(chuàng)建幫助我們簡(jiǎn)化ioc容器的創(chuàng)建,首先在spring-mvc jar包中,就定義了一個(gè)/META-INF/services/javax.servlet.ServletContainerInitializer文件,然后,在啟動(dòng)時(shí),web容器便會(huì)加載這個(gè)文件,讀取里面的內(nèi)容,為SpringServletContainerInitializer這個(gè)類

由于在SpringServletContainerInitializer上有注解@HandlesTypes標(biāo)注,而這個(gè)注解的值為WebApplicationInitializer,因此,在創(chuàng)建SpringServletContainerInitializer對(duì)象前,web容器會(huì)收集應(yīng)用內(nèi)所有WebApplicationInitializer接口的實(shí)現(xiàn)類,并將它們作為參數(shù)傳遞給onStartup方法中的webAppInitializerClasses,這樣,在web容器啟動(dòng)時(shí),我們就能初始化我們所指定的對(duì)象

總而言之,在應(yīng)用啟動(dòng)時(shí),web容器會(huì)調(diào)用ServletContainerInitializer實(shí)現(xiàn)類(這里為SpringServletContainerInitializer)中的onStartup方法,而這個(gè)onStartup方法中又調(diào)用了@HandlesTypes注解所指定的類或接口(此處為WebApplicationInitializer)的實(shí)現(xiàn)類中的onStartup方法,因此,我們可以編寫一個(gè)WebApplicationInitializer的實(shí)現(xiàn)類,來(lái)創(chuàng)建ioc容器,不過(guò),Spring已經(jīng)為我們提供了一個(gè)實(shí)現(xiàn)了WebApplicationInitializer接口的抽象類AbstractContextLoaderInitializer,它里面已經(jīng)封裝好了大部分的邏輯(比如將ioc容器置于application域中等),而我們所需要做的僅僅就是創(chuàng)建一下ioc容器而已,如下
public class IocInit extends AbstractContextLoaderInitializer {
@Override
protected WebApplicationContext createRootApplicationContext() {
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocation("classpath:springmvc.xml");
return ctx;
}
}
此外,不要忘了注釋掉web.xml中關(guān)于Spring的相關(guān)內(nèi)容,否則會(huì)產(chǎn)生產(chǎn)生兩個(gè)ioc容器
<web-app ....>
<!-- <!– ContextLoaderListener實(shí)現(xiàn)了ServletContextListener,而這個(gè)ServletContextListener就是用于監(jiān)聽web應(yīng)用的生命周期的,當(dāng)web容器啟動(dòng)或終止web應(yīng)用的時(shí)候,會(huì)觸發(fā)ServletContextEvent事件,而該事件就會(huì)由ServletContextListener來(lái)處理,因此ContextLoaderListener就會(huì)在web應(yīng)用啟動(dòng)的同時(shí)會(huì)創(chuàng)建ioc容器,加載配置文件,具體可詳見源碼 –>-->
<!-- <listener>-->
<!-- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>-->
<!-- </listener>-->
<!-- <!– 注意:如果未指定配置文件的路徑,那么默認(rèn)會(huì)尋找/WEB-INF/applicationContext.xml配置文件,如果這個(gè)配置文件找不到,啟動(dòng)時(shí)就會(huì)報(bào)錯(cuò)-->
<!-- 基于web.xml的配置所創(chuàng)建的ioc容器是基于xml配置的ioc容器(XmlWebApplicationContext),它會(huì)在容器啟動(dòng)的時(shí)候讀取加載配置文件 –>-->
<!-- <context-param>-->
<!-- <param-name>contextConfigLocation</param-name>-->
<!-- <param-value>classpath:springmvc.xml</param-value>-->
<!-- </context-param>-->
<servlet>
<servlet-name>exampleServlet</servlet-name>
<servlet-class>cn.example.springmvc.boke.servlet.ExampleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>exampleServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
最后,重啟項(xiàng)目,輸入http://localhost:8080/springmvc/example,看見user字符串則說(shuō)明成功
4.Spring MVC文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-439151.html
現(xiàn)在,我們將Servlet與Spring ioc容器整合到了一起,但如果我們需要處理新的請(qǐng)求的話,我們還得繼承HttpServlet來(lái)編寫新的Servlet,并將其配置到web.xml中,非常麻煩,因此,Spring變?yōu)槲覀兲峁┝艘粋€(gè)全新的框架 - Spring MVC來(lái)幫助我們進(jìn)行開發(fā)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-439151.html
到了這里,關(guān)于Spring MVC官方文檔學(xué)習(xí)筆記(一)之Web入門的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!