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接口的更多相关文章

  1. 详解EBS接口开发之库存事务处理采购接收--补充

    除了可以用  详解EBS接口开发之库存事务处理采购接收的方法还可以用一下方法,不同之处在于带有批次和序列控制的时候实现方式不同 The script will load records into ...

  2. 详解EBS接口开发之采购申请导入

    更多内容可以参考我的博客  详解EBS接口开发之采购订单导入 http://blog.csdn.net/cai_xingyun/article/details/17114697 /*+++++++ ...

  3. 详解EBS接口开发之库存事务处理批次更新

    库存事务处理批次有时候出现导入错误需要更新可使用次程序更新,批次导入可参考博客 详解EBS接口开发之库存事务处理-物料批次导入 http://blog.csdn.net/cai_xingyun/art ...

  4. 供应商API补充(详解EBS接口开发之供应商导入)(转)

    原文地址  供应商导入的API补充(详解EBS接口开发之供应商导入) --供应商 --创建 AP_VENDOR_PUB_PKG.Create_Vendor ( p_api_version IN NUM ...

  5. springboot 详解RestControllerAdvice(ControllerAdvice)(转)

    springboot 详解RestControllerAdvice(ControllerAdvice)拦截异常并统一处理简介 @Target({ElementType.TYPE}) @Retentio ...

  6. 详解 Set接口

    (请关注 本人"集合"总集篇博文--<详解 Collection接口>) 在Collection接口的子接口中,最重要的,也是最常见的两个-- List接口 和 Set ...

  7. 集合类 Contains 方法 深入详解 与接口的实例

    .Net 相等性:集合类 Contains 方法 深入详解 http://www.cnblogs.com/ldp615/archive/2009/09/05/1560791.html 1.接口的概念及 ...

  8. 详解 List接口

    本篇博文所讲解的这两个类,都是泛型类(关于泛型,本人在之前的博文中提到过),我们在学习C语言时,对于数据的存储,用的差不多都是数组和链表. 但是,在Java中,链表就相对地失去了它的存在价值,因为Ja ...

  9. 详解EBS接口开发之应收款处理

    参考实例参考:杜春阳 R12应收模块收款API研究 (一)应收款常用标准表简介 1.1   常用标准表 如下表中列出了与应收款处理相关的表和说明: 表名 说明 其他信息 AR_BATCHES_ALL ...

随机推荐

  1. python学习一(Python中的列表)

    python中有两种列表,分别用()和[]表示: 例如: letter = ('a','b','c') letter = ['a','b','c'] 用小括号表示的列表初始化后不允许修改,而中中括号生 ...

  2. nginx图片缓存服务器配置实战

     1.图片目录设置: 假定服务器主目录为nginx的默认目录:/usr/local/nginx-0.8.32/html/ 图片存放目录为:/usr/local/nginx-0.8.32/html/SD ...

  3. HDU 5496——Beauty of Sequence——————【考虑局部】

    Beauty of Sequence Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Other ...

  4. arcgis 定位图斑,并且高亮显示

    ///图斑定位 function TabQuery(instance_id, layer_name) { require(["esri/map", "esri/geome ...

  5. 19.CentOS7下PostgreSQL安装过程

    CentOS7下PostgreSQL安装过程 装包 sudo yum install postgresql-server postgresql-contrib 说明: 这种方式直接明了,其他方法也可以 ...

  6. 基于android-uitableview扩展-uilistview项目

    这个项目是正如标题说的那样,是基于uitableview项目为基础进行二次封装的,目的是实现更多的展现形式,项目地址:点击打开 不过,这个使用起来你还必须得会用uitableview扩展(项目地址:点 ...

  7. MATLAB之折线图、柱状图、饼图以及常用绘图技巧

    MATLAB之折线图.柱状图.饼图以及常用绘图技巧 一.折线图 参考代码: %图1:各模式直接成本预测 %table0-table1为1*9的数组,记录关键数据 table0 = data_modol ...

  8. 【java】使用URL和CookieManager爬取页面的验证码和cookie并保存

    使用java的net包和io包下的几个工具爬取页面的验证码图片并保存到本地. 然后可以把获取的cookie保存下来,做进一步处理.比如通过识别验证码,进一步使用验证码和用户名,密码,保存下来的cook ...

  9. EF ObjectQuery查询及方法

      string esql = "select value c from NorthwindEntities.Customers as c order by c.CustomerID lim ...

  10. 修复SQL中的孤立账户

    EXEC sys.sp_change_users_login 'AUTO_FIX','登录名',NULL,'登录密码'