当前位置:网站首页>Use of interceptors webmvcconfigurer

Use of interceptors webmvcconfigurer

2022-06-13 03:05:00 good_ boys

1 Introduce

WebMvcConfigurer The configuration class is actually Spring An internal configuration , use JavaBean Instead of the traditional xml The configuration file is customized for the framework , You can customize some Handler,Interceptor,ViewResolver,MessageConverter. be based on java-based The way of spring mvc To configure , You need to create a configuration class and implement WebMvcConfigurer Interface ;

stay Spring Boot 1.5 Versions are rewritten WebMvcConfigurerAdapter To add a custom interceptor , Message converter, etc .SpringBoot 2.0 after , This class is marked as @Deprecated( Abandoning ). The official recommendation is implemented directly WebMvcConfigurer Or direct inheritance WebMvcConfigurationSupport, The first way is to realize WebMvcConfigurer Interface ( recommend ), Mode 2 inheritance WebMvcConfigurationSupport class , See this article for specific implementation .https://blog.csdn.net/fmwind/article/details/82832758

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
@EnableWebMvc
public class InterceptorConfiguration implements WebMvcConfigurer {

    @Resource
    private SessionInterceptor sessionInterceptor;

    @Resource
    private WechatInterceptor wechatInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessionInterceptor)
                .addPathPatterns("/**")
                .order(Ordered.HIGHEST_PRECEDENCE);

        registry.addInterceptor(wechatInterceptor)
                .addPathPatterns("/testApp/**")
                .order(Ordered.LOWEST_PRECEDENCE);
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 */
@Component
public class WechatInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // todo  Do something 
        ContextUtil.put(HeaderConstant.STORE_SHOP_USER,dto);
        return true;
    }

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

原网站

版权声明
本文为[good_ boys]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280534303684.html