精通SpringBoot:详解WebMvcConfigurer接口
SpringBoot 确实为我们做了很多事情, 但有时候我们想要自己定义一些Handler,Interceptor,ViewResolver,MessageConverter,该怎么做呢。在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated。因此我们只能靠实现WebMvcConfigurer接口来实现。接下来让我们来看看这个接口类吧!(列举下常用的方法供参考)
package com.developlee.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.developlee.configurer.USLocalDateFormatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* @TODO //
* @Author Lensen
* @Date 2018/7/21
* @Description 实现WebMvcConfigurer接口,
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 添加类型转换器和格式化器
* @param registry
*/
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldType(LocalDate.class, new USLocalDateFormatter());
}
/**
* 跨域支持
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600 * 24);
}
/**
* 添加静态资源--过滤swagger-api (开源的在线API文档)
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//过滤swagger
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/swagger-resources/**")
.addResourceLocations("classpath:/META-INF/resources/swagger-resources/");
registry.addResourceHandler("/swagger/**")
.addResourceLocations("classpath:/META-INF/resources/swagger*");
registry.addResourceHandler("/v2/api-docs/**")
.addResourceLocations("classpath:/META-INF/resources/v2/api-docs/");
}
}
/**
* 配置消息转换器--这里我用的是alibaba 开源的 fastjson
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//1.需要定义一个convert转换消息的对象;
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//2.添加fastJson的配置信息,比如:是否要格式化返回的json数据;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteDateUseDateFormat);
//3处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//4.在convert中添加配置信息.
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
//5.将convert添加到converters当中.
converters.add(fastJsonHttpMessageConverter);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ReqInterceptor()).addPathPatterns("/**");
}
}
添加一个Interceptor,作为测试
package com.developlee.configurer;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @TODO //
* @Author Lensen
* @Date 2018/7/21
* @Description 请求Interceptor
*/
public class ReqInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Interceptor preHandler method is running !");
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Interceptor postHandler method is running !");
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("Interceptor afterCompletion method is running !");
super.afterCompletion(request, response, handler, ex);
}
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Interceptor afterConcurrentHandlingStarted method is running !");
super.afterConcurrentHandlingStarted(request, response, handler);
}
}
写个controller测试下
@Controller
@RequestMapping("/locale")
public class LocaleController {
@GetMapping("/date")
@ResponseBody
public String locale(Locale locale){
System.out.println("Controller is running !");
return "Hello" + USLocalDateFormatter.getPattern(locale);
}
}
请求地址: http://localhost:8080/locale/date ,看看控制台打印信息
//SpringMvc请求处理的执行过程
Interceptor preHandler method is running !
Controller is running !
Interceptor postHandler method is running !
Interceptor afterCompletion method is running
精通SpringBoot:详解WebMvcConfigurer接口的更多相关文章
- 详解EBS接口开发之库存事务处理采购接收--补充
除了可以用 详解EBS接口开发之库存事务处理采购接收的方法还可以用一下方法,不同之处在于带有批次和序列控制的时候实现方式不同 The script will load records into ...
- 详解EBS接口开发之采购申请导入
更多内容可以参考我的博客 详解EBS接口开发之采购订单导入 http://blog.csdn.net/cai_xingyun/article/details/17114697 /*+++++++ ...
- 详解EBS接口开发之库存事务处理批次更新
库存事务处理批次有时候出现导入错误需要更新可使用次程序更新,批次导入可参考博客 详解EBS接口开发之库存事务处理-物料批次导入 http://blog.csdn.net/cai_xingyun/art ...
- 供应商API补充(详解EBS接口开发之供应商导入)(转)
原文地址 供应商导入的API补充(详解EBS接口开发之供应商导入) --供应商 --创建 AP_VENDOR_PUB_PKG.Create_Vendor ( p_api_version IN NUM ...
- springboot 详解RestControllerAdvice(ControllerAdvice)(转)
springboot 详解RestControllerAdvice(ControllerAdvice)拦截异常并统一处理简介 @Target({ElementType.TYPE}) @Retentio ...
- 详解 Set接口
(请关注 本人"集合"总集篇博文--<详解 Collection接口>) 在Collection接口的子接口中,最重要的,也是最常见的两个-- List接口 和 Set ...
- 集合类 Contains 方法 深入详解 与接口的实例
.Net 相等性:集合类 Contains 方法 深入详解 http://www.cnblogs.com/ldp615/archive/2009/09/05/1560791.html 1.接口的概念及 ...
- 详解 List接口
本篇博文所讲解的这两个类,都是泛型类(关于泛型,本人在之前的博文中提到过),我们在学习C语言时,对于数据的存储,用的差不多都是数组和链表. 但是,在Java中,链表就相对地失去了它的存在价值,因为Ja ...
- 详解EBS接口开发之应收款处理
参考实例参考:杜春阳 R12应收模块收款API研究 (一)应收款常用标准表简介 1.1 常用标准表 如下表中列出了与应收款处理相关的表和说明: 表名 说明 其他信息 AR_BATCHES_ALL ...
随机推荐
- json java simple-json
http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object javac ...
- 搭建Node.js Redis开发环境
创建项目 初始化为node项目 $npm init 安装redis 安装@types/node, @types/redis, typescript 初始化TypeScript 配置ts ...
- C 碎片四 流程控制
前面介绍了程序中用到的一些基本要素(常量,变量,运算符,表达式),他们是构成程序的基本成分,下面将介绍C语言中流程控制的三种结构:顺序结构.分支结构.循环结构 一.顺序结构 顺序结构的程序设计是最简单 ...
- 个人整理的jsp、EL表达式、JSTL标签库的笔记,少概念多实用,需要的留下邮箱,会第一时间分享原稿PDF给大家!
jsp 第一章 jsp介绍及对比servlet 作用: 动态网页技术,动态的从数据库获取数据 jsp和servlet的优缺点: jsp优点:页面表现方便,利于写html代码 jsp缺点:业务逻辑处理麻 ...
- Ubuntu下eclipse无法识别手机驱动(以小米2S为例子)
google官方开发向导里对Android手机已经设置了允许安装非market程序,并且处于usb调试模式,但是仍然在usb连接电脑后无法被识别的问题作了解释. 在Ubuntu Linux环境下需要添 ...
- It's the loneliest feeling not to know who you are.
It's the loneliest feeling not to know who you are.最孤独的感觉莫过于不知道自己是谁.
- FMCW 雷达原理(转)
FMCW(Frequency Modulated Continuous Wave),即调频连续波.FMCW技术和脉冲雷达技术是两种在高精度雷达测距中使用的技术.其基本原理为,发射波为高频连续波,其频率 ...
- 关于HTML中时间格式以及查询数据库的问题
1.默认时间格式,加入属性dateFormate="yyyy-MM-dd" 2.设置默认值,value="2017-6-22" 3.在JavaScript中将获 ...
- Reduce侧连接
1.reduce side join 在reduce端进行表的连接,该方法的特点就是操作简单,缺点是map端shffule后传递给reduce端的数据量过大,极大的降低了性能 连接方法: (1)map ...
- WORD窗体保护密码清除
Word 2003破解方法如下:1.用Word打开已设置有密码的“保护文档”(原始DOC文件):2.菜单中选择“文件”→“另存为Web页”,保存为HTML文件然后关闭Word:3.用文本编辑器(如:记 ...