zoukankan      html  css  js  c++  java
  • [Spring MVC]学习笔记--DispatcherServlet

    在上一篇我们介绍了Servlet,这一篇主要来看一下MVC中用到的DispatcherServlet(继承自HttpServlet)。

    1. DispatcherServlet在web.xml中被声明。

    <web-app>
        <servlet>
            <servlet-name>example</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>example</servlet-name>
            <url-pattern>/example/*</url-pattern>
        </servlet-mapping>
    
    </web-app>

    注:我们也可以在代码中去进行设置,具体参考http://docs.spring.io/spring/docs/4.0.6.RELEASE/spring-framework-reference/htmlsingle/#mvc-container-config

    2. DispatcherServlet包含的一些beans

    3. 除了步骤2种默认提供的bean以外,Spring MVC还会在WEB-INF文件夹下寻找一个 [servlet-name]-servlet.xml 文件(步骤1中,会寻找example-servlet.xml这个文件), 创建这个文件中定义的beans。

    如果需要修改默认的bean,可以在这个里面进行定义,加载时会覆盖默认的bean。

    4. 我们可以通过DispatcherServlet中的初始化方法,配置步骤3中的xml的路径。

    或者,如果你想用一个公用的xml,可以配置context-param并且不设置contextConfigLocation的值就可以了。

    <web-app>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/root-context.xml</param-value>
        </context-param>
        <servlet>
            <servlet-name>dispatcher</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>dispatcher</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    </web-app>

    5. 如果要让mvc下的annotation起作用,需要在 [servlet-name]-servlet.xml 中增加一行。

    <?xml version=1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <mvc:annotation-driven />
    
    </beans>
  • 相关阅读:
    springMVC 错误页面配置
    设计模式 11 —— 代理模式
    JAVA RMI 实例
    设计模式 10 —— 状态模式
    设计模式 9 —— 模板方法模式
    Java EE : 三、图解Session(会话)
    Java EE : 二、图解 Cookie(小甜饼)
    Java EE : 一、图解Http协议
    《JAVA与模式》之单例模式
    Java中如何克隆集合——ArrayList和HashSet深拷贝
  • 原文地址:https://www.cnblogs.com/lemonbar/p/3903273.html
Copyright © 2011-2022 走看看