您的位置:首页 > 编程语言 > Java开发

SpringMVC——静态资源访问之<mvc:annotation-driven/>与<mvc:default-servlet-handler/>

2017-09-11 15:40 731 查看
web.xml 配置:

<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 配置 HiddenHttpMethodFilter: 把 POST 请求转为 DELETE、PUT 请求 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


SpringMVC.xml配置

<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.atguigu.springmvc"></context:component-scan>

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>


在做项目的时候,我希望静态资源由WEB服务器默认的Servlet来处理,所以我在SpringMVC.xml配置文件中添加了如下的语句:

<mvc:default-servlet-handler/>


但是我再次运行项目,并访问资源的时候,发现访问@RequestMapping(“/path1/path2”)都不能访问了,之前没有添加的时候是能够访问的。

解决方案是,在配置文件中再添加一句代码:

<mvc:annotation-driven/>


这样做的原因是:



当两种标签都没有的时候,框架默认注册的有AnnotationMethodHandlerAdapter这个bean,所以能够处理@RequestMapping这个注解,但是只配置了时所注册的三个bean都不能处理@RequestMapping注解,因此无法找到相应的Controller,进而无法进行访问路径的映射,当两种标签都有的时候,会注册一个RequestMappingHandlerAdapter的bean,这个bean能够处理@RequestMapping这个注解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐