Spring MVC 配置拦截器后无法访问

练习spring mvc 拦截器时发现不能访问项目了

spring-mvc.xml 配置

<?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-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">                    

    <!-- 使用扫描机制扫描控制器类 -->
    <context:component-scan base-package="com.zjf"/>

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

    <mvc:interceptors>
       <!--  配置一个全局拦截器,拦截所有请求 -->
        <bean class="com.zjf.interceptor.TestInterceptor" />
    </mvc:interceptors>
</beans>

 

拦截器 

package com.zjf.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class TestInterceptor implements HandlerInterceptor{

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        System.out.println("afterCompletion方法在控制器的处理请求之前执行,既试图渲染之后执行");
        
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        System.out.println("postHandle方法在控制器的处理请求调用之后,解析试图之前执行");
        
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        System.out.println("preHandle方法在控制器的处理请求之前执行");
        return false;
    }

}

 

访问 路径 http://localhost:8080/springmvc/login 以前没写拦截器是可以正常访问的

调试后发现  preHandle 方法返回的是false 大意了

改为 true后 可以正常访问了  使用注解时还要注意  如果controller 跟拦截器不在一个包中,配置自动扫描的包要是两个共同的父类

    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        System.out.println("preHandle方法在控制器的处理请求之前执行");
        return true;
    }

 

posted @ 2021-04-06 20:47  奋斗的渣渣  阅读(350)  评论(0编辑  收藏  举报