SpringBoot入门六(整合之SpringMVC拦截器)

官网的一段话:

如果你想要保持Spring Boot的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器,
视图控制器,消息转换器等等),你应该让一个类实现WebMvcConfigurer,并且添加@Configuration注解,但是
,千万不要加@EnableWebMvc注解,如果你想要自定义HandlerMapping,HandlerAdapter,ExceptionResolver等组件,
你可以创建一个WebMvcRegistrationsAdapter实例 来提供以上组件。

如果你想要完全自定义SpringMVC,不保留SpringBoot提供的一些特征,你可以自定义类并且添加@Configuration注解
和@EnableWebMvc注解

步骤:
1.编写拦截器(在学习MVC时知道要实现HandlerInterceptor接口)接口里面有三个方法(前置后置完成时)

2.编写配置类实现WebMvcConfigurer,在类中添加各种组件

3.测试

 

=============

1.编写拦截器

package com.cc8w.interceptor;


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

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


public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("前置...");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

 

2.编写配置类实现WebMvcConfigurer,在类中添加各种组件

package com.cc8w.config;

import com.cc8w.interceptor.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {


    //1.注册拦截器
    @Bean
    public MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }
    //2.添加拦截器到Spring Mvc拦截器链
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor()).addPathPatterns("/*");//对所有路径生效
    }
}

 

3.目录或测试

 

posted @ 2020-10-15 15:33  与f  阅读(221)  评论(0编辑  收藏  举报