现在的位置: 首页 > 操作系统 > 正文

SpringMVC配置详解

2020年02月07日 操作系统 ⁄ 共 2588字 ⁄ 字号 评论关闭

一、Spring MVC处理流程

  1.Spring MVC将所有请求都交由DispatchServlet进行处理。

  2.DispatchServlet获取HandlerMapping(处理映射器),然后找到对应的HandlerBean处理Controller请求,并返回一个ModelAndView对象。

  3.DispatchServlet查询一个或多个ViewResolver视图解析器对象, 并把视图渲染返回给前端。

二、相关配置

  首先配置web.xml,我们根据组件启动顺序:全局参数<context-param>、Listener监听器、Filter过滤器、Servlet、的顺序配置。

<web-app version="2.5" xmlns="http://Java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<!-- 配置ContextLoaderListener监听器,使容器初始化spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param>

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

<!-- 为每个请求过程绑定一个HibernateSession,它将由spring自动管理,无需手动开启和关闭 此session的currentSession由SpringSessionContext管理而不是ThreadLocalSessionContext. --> <filter> <filter-name>openSessionInterceptor</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInterceptor</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

<!-- 字符集过滤器 --> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

<!-- spring mvc 配置--> <servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/spring-mvc.xml</param-value> </init-param> </servlet>

<servlet-mapping> <servlet-name>context</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></web-app>

  我们首先配置了org.springframework.web.context.ContextLoaderListener的Context监听器,我们以Tomcat为例:

  1、他启动的时候会去读取配置文件web.xml,首先读两个节点: <listener></listener> 和 <context-param></context-param>,然后创建一个ServletContext,整个web项目将共享这个Context。(意味着,我们这个项目将以spring MVC的context方式启动)

  2.容器将<context-param></context-param>的内容以键值对的形式交给Listener,配置中,我们配置了contextConfigLocation,也就是springmvc配置文件的位置,作为启动springContext的配置文件,这个值在容器启动的时候监听器执行contextInitialized方法可以拿到,然后sc.getInitParameter(CONFIG_LOCATION_PARAM)获得配置文件路径,再根据配置文件路径初始化容器。(Spring源码如下)

以上就上有关SpringMVC配置详解的相关介绍,要了解更多Spring MVC配置,SpringMVC,Spring MVC配置详解,编程,Linux编程,Linux Shell,Android,Android教程,JAVA,C语言,Python,HTML5内容请登录学步园。

抱歉!评论已关闭.