Spring boot 梳理 - WebMvcConfigurer接口 使用案例
转:https://yq.aliyun.com/articles/617307
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 !
题外话:从WebMvcConfigurer这个接口中,可以看到JDK8的一些新特性——在接口中新增了default方法和static方法,这两种方法可以有方法体。大家可以业余时间去了解下。这两种新特性为我们编写代码带来了更多改变,让代码变得更加简洁
Spring boot 梳理 - WebMvcConfigurer接口 使用案例的更多相关文章
- Spring Boot 之:接口参数校验
Spring Boot 之:接口参数校验,学习资料 网址 SpringBoot(八) JSR-303 数据验证(写的比较好) https://qq343509740.gitee.io/2018/07/ ...
- Spring boot 梳理 -@SpringBootApplication、@EnableAutoConfiguration与(@EnableWebMVC、WebMvcConfigurationSupport,WebMvcConfigurer和WebMvcConfigurationAdapter)
@EnableWebMvc=继承DelegatingWebMvcConfiguration=继承WebMvcConfigurationSupport 直接看源码,@EnableWebMvc实际上引入一 ...
- spring boot与jdbcTemplate的整合案例2
简单入门了spring boot后,接下来写写跟数据库打交道的案例.博文采用spring的jdbcTemplate工具类与数据库打交道. 下面是搭建的springbootJDBC的项目的总体架构图: ...
- spring boot https --restful接口篇
我们写的接口默认都是http形式的,不过我们的接口很容易被人抓包,而且一抓全是明文的挺尴尬的 spring boot配置https生成证书大的方向有3种: 1.利用keytool自己生成证书 2.从免 ...
- Spring Boot 集成 FreeMarker 详解案例(十五)
一.Springboot 那些事 SpringBoot 很方便的集成 FreeMarker ,DAO 数据库操作层依旧用的是 Mybatis,本文将会一步一步到来如何集成 FreeMarker 以及配 ...
- 解决spring boot中rest接口404,500等错误返回统一的json格式
在开发rest接口时,我们往往会定义统一的返回格式,列如: { "status": true, "code": 200, "message" ...
- Spring Boot 整合 Thymeleaf 完整 Web 案例
Thymeleaf 是一种模板语言.那模板语言或模板引擎是什么?常见的模板语言都包含以下几个概念:数据(Data).模板(Template).模板引擎(Template Engine)和结果文档(Re ...
- Spring Boot 实现ErrorController接口处理404、500等错误页面
在项目中我们遇到404找不到的错误.或者500服务器错误都需要配置相应的页面给用户一个友好的提示,而在Spring Boot中我们需要如何设置. 我们需要实现ErrorController接口,重写h ...
- Spring boot 梳理 - @Conditional
@Conditional(TestCondition.class) 这句代码可以标注在类上面,表示该类下面的所有@Bean都会启用配置,也可以标注在方法上面,只是对该方法启用配置. spring框架还 ...
随机推荐
- 实战jmeter入门压测接口性能
什么是Jmeter? 是Apache组织开发的基于Java的压力测试工具. 准备工作: 一.安装配置好环境及压测工具 Jmeter下载地址:http://mirrors.tuna.tsinghua.e ...
- Django之上传图片,分页,三级联动
Django1.8.2中文文档:Django1.8.2中文文档 上传图片 配置上传文件保存目录 1)新建上传文件保存目录. 2)配置上传文件保存目录. 后台管理页面上传图片 1)设计模型类. 2)迁移 ...
- ZYNQ Block Design中总线位宽的截取与合并操作
前言 在某些需求下,数据的位宽后级模块可能不需要原始位宽宽度,需要截位,而某些需求下,需要进行多个数据的合并操作. 在verilog下,截位操作可如下所示: wire [7:0] w_in; wire ...
- lightoj 1097 - Lucky Number(线段树)
Lucky numbers are defined by a variation of the well-known sieve of Eratosthenes. Beginning with the ...
- Python 单元测试框架系列:聊聊 Python 的单元测试框架(一):unittest
作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...
- Keras之注意力模型实现
学习的一个github上的代码,分析了一下实现过程.代码下载链接:https://github.com/Choco31415/Attention_Network_With_Keras 代码的主要目标是 ...
- 【Redis】SpringBoot+Redis+Ehcache实现二级缓存
一.概述 1.1 一些疑惑? 1.2 场景 1.3 一级缓存.两级缓存的产生 1.4 流程分析 二.项目搭建 一.概述 1.1 一些疑惑? Ehcache本地内存 Redis 分布式缓存可以共享 一级 ...
- vue基础技术点列表(一)
一. vue编写需要注意的细节1.vue初始化实例时使用首字母大写,在添加全局配置时也要首字母大写(如添加组件Vue.component("",{template:"&q ...
- Kafka的安全认证机制SASL/PLAINTEXT
一.背景 kafka提供了多种安全认证机制,主要分为SSL和SASL2大类.其中SASL/PLAIN是基于账号密码的认证方式,比较常用.最近做了个kafka的鉴权,发现官网上讲的不是很清楚,网上各种博 ...
- 2019本科se第一次作业-博客初体验-chris
(1)第一章 计算机专业术语总结: 软件=程序+软件工程.程序=数据结构+算法.软件.程序.用户.需求.应用程序.软件服务.源程序.软件架构(Software Architecture).软件设计与 ...