MyInterceptor.java
@Configuration // 声明这是一个配置 拦截器
public class MyInterceptor extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor interceptor = new 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 {
}
};
// 注册拦截器
// "/**" 表示拦截所有
registry.addInterceptor(interceptor).addPathPatterns("/**");
}
}
SpringApp.java
// 扫描的包 要包含拦截器
@SpringBootApplication(scanBasePackages = {"demo.controller", "demo.interceptor"})
public class SpringApplications2 {
@Bean
public HttpMessageConverters fastJsonMessageConverter(){
// 创建 fastjson的消息转换器
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
// 创建 fastjson的配置对象
FastJsonConfig config = new FastJsonConfig();
// 对 json 数据 进行格式化
config.setSerializerFeatures(SerializerFeature.PrettyFormat);
converter.setFastJsonConfig(config);
HttpMessageConverter<?> con = converter;
return new HttpMessageConverters(con);
}
public static void main(String[] args) {
SpringApplication.run(SpringApplications2.class, args);
}
}
追加,如果要实现 fastJson功能
application.properties
# 开启 fastjson
spring.http.encoding.force=true