Spring Boot 04 整合Web(上)
返回JSON数据
spring-boot-starter-web依赖默认加入了jackson-databind作为JSON处理器
创建实体类与Controller类,返回实体对象就行
默认的jackson-databind
publicclassPeople{privateString name;@JsonIgnoreprivateString gender;@JsonFormat(pattern ="yyyy-MMM")privateLocalDate birthday;}@RestControllerpublicclassPeopleController{@GetMapping("/people")publicPeoplegetPeople(){People people =newPeople(); people.setName("张三"); people.setGender("男"); people.setBirthday(LocalDate.now());return people;}}最终界面会打印如图数据

@JsonFormat规定了birthday的输出格式
gender数据由于写了@JsonIgnore注解,因此就没有出现
Gson
一个开源的JSON解析框架,需要先除去默认的jackson-databind,再加入Gson依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></exclusion></exclusions></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId></dependency>Spring Boot中提供了Gson的自动转换类GsonHttpMessageConvertersConfiguration,因此添加完依赖后就可以直接像jackson-databind一样直接使用Gson了
如果需要对日期数据惊醒格式化,则需要自定义HttpMessageConverter:
GsonHttpMessageConvertersConfiguration中有以下源码:
@ConditionalOnMissingBean注解表示当前项目没有提供GsonHttpMessageConverter时才会使用,所以自己自定义一个即可起到替代作用
可以写一个Gson的配置类GsonConfig
此外还需要在properties中写入优先使用gson的配置信息
@ConfigurationpublicclassGsonConfig{@BeanpublicGsonHttpMessageConvertergsonHttpMessageConverter(){GsonHttpMessageConverter converter =newGsonHttpMessageConverter();GsonBuilder builder =newGsonBuilder(); builder.setDateFormat("yyyy-MMM-dd"); builder.excludeFieldsWithModifiers(Modifier.PROTECTED);Gson gson = builder.create(); converter.setGson(gson);return converter;}}builder的第二行的作用是将修饰符为protected的字段在解析时被过滤掉
properties文件添加:
spring.http.converters.preferred-json-mapper=gson 使用fastjson
fastjson是阿里的一个开源解析框架,解析速度十分快速
但是与前两种不同的是需要提供相应的HttpMessageConverter后才能使用
1. 引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></exclusion></exclusions></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency>2. 配置 HttpMessageConverter
@Configuration public classMyFastJsonConfig{@Bean public FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){ FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM"); config.setCharset(StandardCharsets.UTF_16); config.setSerializerFeatures( SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse ); converter.setFastJsonConfig(config);return converter;}}setSerializerFeatures完成了JSON解析过程中的一些细节WriteClassName =>写入类的名称,输出时会显示类的名称
“@type”:“fm.douban.chapter03.model.People”
WriteNullListAsEmpty =>当对象字段类型为集合且值为null时,将其序列化为空数组
WriteMapNullValue => 用于控制Map或者JavaBean中对象的值为null时的行为,因为FastJSON解析时默认会忽略值为null的字段,并不会打印它们
剩余的便是对null值情况的处理,例如null值转为0,false等
实测了一下,如果不使用UTF_16编码,直接使用UTF_8会显示中文乱码,需要加上额外的响应编码配置
在properties中写入spring.servlet.encoding.force-response=true即可
静态资源过滤
什么是静态资源过滤
静态资源过滤是指在Web应用中,对静态资源文件(如CSS、JS、图片、HTML等)的请求进行特殊处理,不让这些请求经过某些过滤器或拦截器。
为什么需要静态资源过滤?
- 性能考虑
- 静态资源不需要业务逻辑处理
- 避免不必要的过滤器链执行
- 提高响应速度
- 功能需求
- 登录验证过滤器不应该拦截CSS/JS文件
- 权限检查过滤器通常不需要处理图片资源
- 日志记录过滤器可能不需要记录静态资源访问
默认策略
Spring Boot 中对静态资源过滤提供了自动化配置,可以简化静态资源过滤配置。
Spring Boot中对于Spring MVC 地自动化配置都在WebMvcAutoConfiguration类中
在WebMvcAutoConfiguration类地一个静态内部类WebMvcAutoConfigurationAdapter中实现了WebMvcConfigurer接口(还有ServletContextAware接口),其中包含一个方法addResourcehandlers用来配置静态资源过滤
WebProperties里有以下内容:
WebMvcAutoConfiguration类的addResourceHandler的主要内容:
publicvoidaddResourceHandlers(ResourceHandlerRegistry registry){if(!this.resourceProperties.isAddMappings()){ logger.debug("Default resource handling disabled");}else{this.addResourceHandler(registry,this.mvcProperties.getWebjarsPathPattern(),"classpath:/META-INF/resources/webjars/");this.addResourceHandler(registry,this.mvcProperties.getStaticPathPattern(),(Consumer)((registration)->{ registration.addResourceLocations(this.resourceProperties.getStaticLocations());if(this.servletContext !=null){ServletContextResource resource =newServletContextResource(this.servletContext,"/"); registration.addResourceLocations(newResource[]{resource});}}));}}下文还有两个addResourceHandler的方法重载,用于最终添加路径的实现
可以从源码中看出静态资源位置的优先级:META-INF\resourcesresourcesstaticpublic
当访问同名文件时将按优先级从上到下去检索访问
自定义策略
1. 在配置文件自定义
spring.mvc.static-path-pattern=/static/** spring.resources.static-locations=classpath:/static 第一行指定哪些url请求应该被映射到静态资源处理器
第二行为静态资源位置,静态资源位置也可以添加多个,用逗号分开即可
2. Java编码定义
实现WebMvcConfigurer接口的addResourceHandlers方法即可
@ConfigurationpublicclassMyWebMvcConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddResourceHandlers(ResourceHandlerRegistry registry){ registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");}}addResourceHandler定义映射访问的url路径
addResourceLocations定义静态资源的位置