SpringMVC —— DispatcherServlet 配置

来源:互联网 发布:中国离婚率知乎 编辑:程序博客网 时间:2024/06/06 08:38

一、web.xml 中相关配置

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


二、dispatcherServlet.xml 配置

<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/mvc"     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.0.xsd        http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">                  <!-- mvc:resource 配置 -->         <mvc:resources location="/WEB-INF/views/" mapping="/pages/**"/> <mvc:resources location="file:D:\\" mapping="/images/**"/>         <!-- 定义一个转向默认servlet的bean,用于处理静态资源请求 -->         <mvc:default-servlet-handler/>                  <!-- 启动SpringMVC注解功能  即@Controller 、@RequestMapping等-->         <mvc:annotation-driven></mvc:annotation-driven>         <!-- 启用组件自动扫描 -->         <context:component-scan base-package="com.milan.web"></context:component-scan>          </beans>

1、mvc:resources

完成静态资源的映射,"/"开头代表是以工程文件夹为基准的相对路径,对应项目结构中即webapp目录的直接子文件。引用文件系统中的文件,须在前加:"file:",且注意文件系统路径是反斜杠。可以有多个此标签。

<mvc:resources location="/WEB-INF/views/" mapping="/pages/**"/><mvc:resources location="file:D:\\" mapping="/images/**"/>
测试成功:

1)、访问WEB-INF子目录 views中的test.html,访问路径:

localhost:8080/projectName/service/pages/test.html
2)、访问D盘下的img.jpg文件,访问路径:

localhost:8080/projectName/service/images/img.jpg

注意点:

mapping 属性格式都为:/subUrl/**,后面是两个星号。



2、mvc:annotation-driven 与 context:component-scan

使用@Controller 相关控制层注解时,两者必须配置。


3、mvc:default-servlet-handler

用于将静态资源的请求转向名为default的servlet处理(该servlet会自动创建)。



三、视图解析器配置
1、配置JSP 视图解析器





四、错误整理

1、视图解析器,prefix 属性值不能为mvc:resource 中的mapping 属性值,因为关联不到。


2、配置了jsp视图解析器,但没配置<mvc:default-servlet-handler />,路径是正确的,但客户端提示NOT_FOUND 错误,浏览器端不报错。因为jsp视图解析器没有真正返回视图,而是交给default (默认生成)的servlet 处理。而转向工作需要<mvc:default-servlet-handler />才能完成。此外,只转向default 的servlet还不够,还必须在web.xml中定义default处理jsp页面的映射:

<servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/service/*</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.jsp</url-pattern></servlet-mapping>













原创粉丝点击