SpringBoot中配置拦截器WebMvcConfigurer

在SpringBoot2.0及Spring5.0中WebMvcConfigurerAdapter已被废弃 。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport,方式一实现WebMvcConfigurer接口(推荐使用),方式二继承WebMvcConfigurationSupport类。

这里就介绍第一种方式。

首先咱们看一下WebMvcConfigurer的里面的方法。

我使用的是JDK8,8里面增加了default特性。

package org.springframework.web.servlet.config.annotation;

import java.util.List;

import org.springframework.core.convert.converter.Converter;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;


public interface WebMvcConfigurer {

	default void configurePathMatch(PathMatchConfigurer configurer) {
	}

	
	default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
	}


	default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
	}

	
	default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
	}

	
	default void addFormatters(FormatterRegistry registry) {
	}

	//拦截器配置
	default void addInterceptors(InterceptorRegistry registry) {
	}
	
    //静态资源处理
	default void addResourceHandlers(ResourceHandlerRegistry registry) {
	}

	//解决跨域问题
	default void addCorsMappings(CorsRegistry registry) {
	}

	//视图跳转控制器
	default void addViewControllers(ViewControllerRegistry registry) {
	}

	//配置视图解析器
	default void configureViewResolvers(ViewResolverRegistry registry) {
	}

	default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
	}

	
	default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
	}

	
	default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
	}

	
	default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
	}

	default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
	}

	
	default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
	}

	@Nullable
	default Validator getValidator() {
		return null;
	}

	
	@Nullable
	default MessageCodesResolver getMessageCodesResolver() {
		return null;
	}

}

实例演示:

后台系统身份验证拦截器

AdminLoginInterceptor类

package com.cc.interceptor;

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

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

/**
 * 后台系统身份验证拦截器
 */
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();
        if (uri.startsWith("/admin") && null == request.getSession().getAttribute("loginUser")) {
            request.getSession().setAttribute("errorMsg", "请重新登陆");
            response.sendRedirect(request.getContextPath() + "/admin/login");
            return false;//return false 不放行,拦截住
        } else {
            request.getSession().removeAttribute("errorMsg");
            return true; //return true 放行
        }
    }
/*
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }*/
}

MyBlogWebMvcConfigurer类

package com.cc.config;

import com.cc.interceptor.AdminLoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyBlogWebMvcConfigurer implements WebMvcConfigurer {

    @Autowired(required = false)
    private AdminLoginInterceptor adminLoginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加一个拦截器,拦截以/admin为前缀的url路径
        registry.addInterceptor(adminLoginInterceptor).
                addPathPatterns("/admin/**").
                excludePathPatterns("/admin/login").  //excludePat路径hPatterns 不需要拦截的
                excludePathPatterns("/admin/dist/**").
                excludePathPatterns("/admin/plugins/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**").addResourceLocations("file:" + Constants.FILE_UPLOAD_DIC);
    }
}

在我配置了上述拦截器之后,

我访问 http://localhost:8081/admin/index

就会自动跳转到 http://localhost:8081/admin/login页面去登录。

你可能感兴趣的:(SpringBoot)