Spring mvc的配置

一,配置分发器
DispatcherServlet 是Spring MVC 的入口
所有进入Spring Web 的 Request 都经过 DispatcherServlet
需要在 web.xml 中注册 DispatcherServlet

dispatherContext

org.springframework.web.servlet.DispatcherServlet

1


加载 DispatcherServlet 时 Spring 会尝试读取配置文件
默认的配置文件位于 web.xml 相同的路径下 文件名与注册的 Servlet
名有关 Servlet注册名跟上 -servlet.xml
例如:上面的 Servlet 注册名为 dispatcherContext 那么 默认的
配置文件名位:dispatcherContext-servlet.xml

当然 也可以明确配置文件 需要在注册 servlet 时 设定初始化参数

contextConfigLocation





注册 DispatcherServlet 后 还应指定有 Spring 处理的 url 模板

dispatherContextServlet
*.do


这样 请求 .do 的处理 就全部交由 Spring 处理了

当程序越来越大 配置文件中的 越来越多 而且变得关系错综复杂
难于维护 此时应该考虑 将配置文件拆分成多个
为了让 Spring 能够读到这些配置文件 并察觉到他们的变化
需要注册配置文件读取器
对于 Servlet 2.3 以上标准 且 web 容器支持监听器
可以 在 web.xml 中注册监听


org.springframework.web.context.ContextLoaderListener



对于 Servlet 2.3 以下版本 由于不支持监听器 所以需要注册 Servlet

contextLoader

org.springframework.web.context.ContextLoaderServlet

1


配置文件读取器 注册成功后 需要设定配置文件列表
设置全局参数 contextConfigLocation
置为 配置文件列表 以逗号分隔 注意路径

contextConfigLocation

/WEB-INF/dispatcherContext-servlet.xml,

classpath*:hibernateContext.xml



二,配置映射响应器(HandlerMapping)
当 DispatcherServlet 接到请求后 会向 HandlerMapping 询问
请求所对应的控制器
BeanNameUrlHandlerMapping Spring 默认的映射响应器 根据 的 name 属性查找控制器处理请求
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />

SimpleUrlHandlerMapping Spring 中最常用的映射响应器 通过对其 mappings 进行设置 从而获得更为灵活的
控制器查找机


class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">







CommonsPathMapHandlerMapping 应用了 jdk1.5 后的新特性 通过 Controller 中的注释 进行映射
在类的主是中加入 @@https://www.360docs.net/doc/216089678.html,monsattributes.PathMap("/path.do")
class="https://www.360docs.net/doc/216089678.html,monsPathMapHandlerMapping" />

三,配置控制器(Controller)
当 DispatcherServlet 接到请求后 通过 HandlerMapping 询问请求所对应的处理控制器后
在 dispatcherContext-servlet.xml 中 查找相对应得 处理请求

当选用了 BeanNameUrlHandlerMapping 映射响应器时 各个处理控制器应保证 的 name
属性即为请求的 url 模板 例如:


当选用了 SimpleUrlHandlerMapping 映射响应器时 各个处理控制器应保证 的 id
属性与 SimpleUrlHandlerMapping 中的 mappings 对应 例如:


class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">


homeAction




当选用了 CommonsPathMapHandlerMapping 映射响应器时
/**
* @@org.springframework.web.servlet.handler.
commonsattributes.PathMap("/hello.do")
*/
public class HelloController
extends AbstractCommandController {
...
}


四,配置试图解析器(ViewResolver)






相关主题
相关文档
最新文档