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. Vim相关问题

    1.vim格式修改 进入配置文件: $ sudo vim /etc/vim/vimrc 在文件末尾添加: #默认查找忽略大小写 set ignorecase #如果有一个大写字母,则切换到大小姐敏感查 ...

  2. Docker | 第四章:Dockerfile简单介绍及使用

    前言 前一章节,介绍了Docker常用的命令.在基本使用上,熟悉这些常用的命令基本上就够了.但在一些场景下,比如在部署SpringBoot应用时,通常我们都是打成Jar包,然后利用java命令进行运行 ...

  3. 排序算法对比,步骤,改进,java代码实现

    前言 发现是时候总结一番算法,基本类型的增删改查的性能对比,集合的串并性能的特性,死记太傻了,所以还是写在代码里,NO BB,SHOW ME THE CODE! github地址:https://gi ...

  4. Oracle存储函数jdbc调用

    package com.jckb.procedure; import java.sql.CallableStatement; import java.sql.Connection; import ja ...

  5. 【踩坑】服务器部署springboot应用时报错--端口被tomcat占用

    今天将本机尬聊一下项目(基于netty-socketio)的服务端程序调试好以后,通过jar包部署在服务器的时候,出现了报错,提示tomcat已经占用了端口. 之前在部署iReview项目时的确是通过 ...

  6. 玩转Docker之常用API(四)

    原文地址:http://accjiyun.cn/wan-zhuan-dockerzhi-chang-yong-api-si/ 任何一个开发的平台都会向开发者开发API,以供开发者更加自由地使用平台所提 ...

  7. ngnix入门配置

    文件1.首先到ngnix下载页面下载你操作系统对应的ngnix压缩包    http://nginx.org/en/download.html 博主我是window10操作系统  上面是我解压之后放的 ...

  8. Struts2笔记1

    一.简介 1.作用于web层:Struts2是一种基于MVC模式的轻量级Web框架; 2.各文件夹简介:     apps:该文件夹存用于存放官方提供的Struts2示例程序,这些程序可以作为学习者 ...

  9. javascript设计模式之外观模式

    /* * 外观模式 * 外观模式的主要意义在于简化类的接口,使其易于调用 */ // 你常常在不经意中使用了外观模式,尤其类库中更多(处理兼容性问题) var addEvent = function ...

  10. 【迷你微信】基于MINA、Hibernate、Spring、Protobuf的即时聊天系统:11.定制化Log输出

    欢迎阅读我的开源项目<迷你微信>服务器与<迷你微信>客户端 前言 在<迷你微信>服务器中,我们用了Log4J来进行输出,这可以在我们程序出现异常的时候找到错误发生时 ...