手机版
你好,游客 登录 注册
背景:
阅读新闻

Spring MVC配置详解

[日期:2017-10-28] 来源:Linux社区  作者:caijh [字体:大 中 小]

一、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源码如下)

1 String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
2         if (configLocationParam != null) {
3             wac.setConfigLocation(configLocationParam);
4         }

  其中,ConfigLocationPraram是常量

1 public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";

  3.接下来是两个过滤器,分别是openSessionInterceptor为了给每个请求绑定HibernateSession的,在GetCurrentSession的时候可以由Spring进行统一管理,无需手动干扰,另外一个是字符集过滤器,将请求的编码统一。

  4.最后是DispatchServlet调度器,他是SpringMVC的核心,他拦截了所有请求,并将请求统一管理。注意:拦截路径必须写成<url-pattern>/</url-pattern>,不能写成<url-pattern>/*</url-pattern>,因为“/*”意为拦截所有请求,只要是请求一律拦截,而“/”意为将DispatcherServlet作为default Servlet(默认是org.apache.catalina.servlets.DefaultServlet),所有其他路径映射未匹配情况下才会交由它处理。而由于隐式映射的关系,使得 .jsp 扩展名被映射到静态资源进而被执行。 

  例如配置成“/*”执行过程中遇到的:

  配置成“/*”他将拦截所有请求,当返回视图路径资源时,请求资源的请求被当成了servlet给拦截了,进而想要执行对应的Controller,发现没有对应的视图,但是根本不存在导致404错误。 

  接下来配置springMVC配置文件

<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" xmlns:mvc="http://www.springframework.org/schema/tool"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd">

    <!-- 扫描spring注解包 -->
    <context:component-scan base-package="controll" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RequestMapping"/>
    </context:component-scan>

    <!-- 配置Spring默认返回路径前缀和后缀 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

   这是spring mvc配置文件,因为我们使用注解方式开发,所以要使用<context:component-scan/>扫描包,扫描注解,其实默认就是扫描注解的,所以可以直接写成:

<context:component-scan base-package="controll" />

 

   第二个是视图解析器,他将配合控制器使用:

  控制器代码如下:

@Controller
public class LoginController{
    @Resource
    private UserService userService;

    @RequestMapping("/index.do")
    public String index(){
        return "index";
    }
}

     @Controller注解说明这是一个控制器Bean,他会被HandlerMapping管理到,

   @RequestMapping注解,声明了servlet的访问路径,里面有多个属性:

      • value:指定请求的实际地址
      • method:  指定请求方式,GET、POST、PUT、DELETE等;(默认Get请求)
      • consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

      • produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
      • params: ��定request中必须包含某些参数值是,才让该方法处理。

      • headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

  最后返回的“index字符串将会和视图解析器的前缀和后缀进行拼接形成新的路径”:即/WEB-INF/pages/index.jsp;

  请求的时候只要http://地址:端口/项目名/实际的RequestMapping名称即可,如:http:localhost:8080/springDemo/index.do

SpringMVC注解之@ResponseBody和@RequestBody  http://www.linuxidc.com/Linux/2017-06/145173.htm

关于SpringMVC之认识Validation  http://www.linuxidc.com/Linux/2017-07/145340.htm

关于SpringMVC前台日期作为实体类对象参数类型转换错误解决  http://www.linuxidc.com/Linux/2017-06/145204.htm

SpringMVC4 注解配置实例  http://www.linuxidc.com/Linux/2017-01/139642.htm

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-10/148056.htm

linux
相关资讯       SpringMVC  Spring MVC配置 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款