基于springboot2.0拦截器的使用案例

本文介绍了如何在Spring Boot中使用自定义拦截器并配置FastJson替换默认的Jackson作为JSON处理器,同时解决了中文乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在springboot2.0中加载拦截器是通过继承WebMvcConfigurationSupport来实现

首先springmvc中书写拦截器需要实现HandlerInterceptor接口如下

@Slf4j
@Component
public class AccessTokenInterceptor implements HandlerInterceptor {

	@Autowired
	private BaseRedisService baseRedisService;
	@Autowired
	private AppMapper appMapper;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
              Object handler)throws Exception {
		
		log.info("拦截器处理真实业务");
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,       
              Object handler,ModelAndView modelAndView) throws Exception {
		log.info("处理请求完成后视图渲染之前的处理操作");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
              Object handler, Exception ex)throws Exception {
		log.info("视图渲染之后操作");
	}
}

接着我们需要把写好的拦截器加载到springboot中,那么我们需要写一个配置类来完成,配置相应的拦截路径 如以下拦截 /openApi/**

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
	//注入拦截器
	@Autowired
	private AccessTokenInterceptor accessTokenInterceptor;
	
    
	@Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }

	@Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(accessTokenInterceptor).addPathPatterns("/openApi/**");
        super.addInterceptors(registry);
    }

    /**
     * 利用fastjson替换掉jackson,且解决中文乱码问题
     * @param converters
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
 
}

 

转载于:https://my.oschina.net/shxjinchao/blog/1860003

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值