一、错误展示
1.错误描述: 在执行springmvc时,输入地址,发现报错,并且自定义拦截器类(Interceptor)没有执行
2.代码描述:
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- <mvc:default-servlet-handler/>-->
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.hnsoft.controller"/>
<!--配置视图解析器-->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/*"/>
<mvc:exclude-mapping path="/index.jsp"/>
<bean class="com.hnsoft.intercepter.LoginIntercepter"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
3.运行描述:
二、解决方式
1.在spring-mvc.xml中增加标签
<!--在Spring-mvc.xml文件中配置-->
<mvc:default-servlet-handler/>
2.配置web.xml文件
<!--配置拦截器:spring-config.xml文件-->
<servlet>
<servlet-name>springmvc</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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 该处填写: /
不能填: /* (/*会;拦截*.jsp) -->
<url-pattern>/</url-pattern>
</servlet-mapping>
3. <mvc:default-servlet-handler />将静态资源的处理经由Spring MVC框架交回Web应用服务器处理。而<mvc:resources />更进一步,由Spring MVC框架自己处理静态资源,并添加一些有用的附加值功能。
<mvc:resources location="/,classpath:/META-INF/publicResources/" mapping="/resources/**"/>
三、问题分析
因为mvc:default-servlet-handler/将在SpringMVC上下文中定义一个DefaultServletHttpRequestHandler,这个Handler的作用是去Servlet容器查找默认的Servlet来响应静态文件,而这会导致配置文件映射器和适配器失效,从而Controller失效,即RequestMapping下设置的方法失效了,从而界面无法跳转。