springboot控制层消息null值处理

文章介绍了在SpringMVC中,如何配置WebMvc。重点对比了WebMvcConfigurerAdapter(已过时)、WebMvcConfigurer接口和WebMvcConfigurationSupport类的使用。WebMvcConfigurerAdapter不推荐使用,WebMvcConfigurer用于添加拦截器、消息转换器等定制配置,而WebMvcConfigurationSupport则涉及更多全局配置,但会阻止SpringBoot的自动配置生效。示例代码展示了如何配置FastJsonHttpMessageConverter并处理消息转换。

大概了解三种方式:

1.区别在于WebMvcConfigurerAdapter 新版本过期,不建议使用。

2.剩下两种不建议同时使用,WebMvcConfigurationSupport是webmvc的配置类,如果在springboot项目中,有类继承了WebMvcConfigurationSupport,那么webmvc的自动配置类WebMvcAutoConfiguration就会失效,导致挂载页面访问不到。

3.如果继承WebMvcConfigurer重写configureMessageConverters但没生效,转换器是列表添加的形式,add进去后就是最后一个,所以没有生效。添加到第一位即可

converters.add(converter);改为converters.add(0,converter);

1.继承WebMvcConfigurerAdapter


import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ming.core.utils.SpringBeanManagerUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 拦截器配置
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        converters.add(fastJsonHttpMessageConverter);        
    }
}

2.实现WebMvcConfigurer接口

@EnableWebMvc
@RequiredArgsConstructor
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final RequestIntercept requestIntercept;


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 1.需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        // 2:添加fastJson的配置信息;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        // 把值是空的直接过滤掉,去掉循环转换
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse
        );
       
        // 4.在convert中添加配置信息.
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
        converters.add(converter);
    }

}

3.继承WebMvcConfigurationSupport

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @CreateTime: 2023-03-20 16:10
 * @Description: TODO
 */
@Configuration
public class JsonMessageConfig extends WebMvcConfigurationSupport {


    /**
     * 使用阿里 fastjson 作为JSON MessageConverter
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                // 保留map空的字段
                SerializerFeature.WriteMapNullValue,
                // 将String类型的null转成""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将Number类型的null转成0
                SerializerFeature.WriteNullNumberAsZero,
                // 将List类型的null转成[]
                SerializerFeature.WriteNullListAsEmpty,
                // 将Boolean类型的null转成false
                SerializerFeature.WriteNullBooleanAsFalse,
                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect);

        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        List<MediaType> mediaTypeList = new ArrayList<>();
        // 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        converters.add(converter);
    }
}

WebMvcConfigurationSupportWebMvcConfigurer都是Spring MVC框架中用于配置WebMvc的接口/类,但是它们有一些不同之处:

  1. WebMvcConfigurationSupport是一个类,而WebMvcConfigurer是一个接口。WebMvcConfigurationSupport提供了一个基本的WebMvc配置类,您可以继承该类并覆盖它的方法来自定义您的配置。WebMvcConfigurer则是一个接口,它定义了一系列回调方法,您可以在您的应用程序中实现这些方法以自定义Spring MVC的配置。
  2. WebMvcConfigurationSupport可以用来配置全局的WebMvc配置,例如ViewResolverArgumentResolver等。您可以使用@EnableWebMvc注解来启用它。而WebMvcConfigurer则可以用于配置局部的WebMvc配置,例如添加拦截器、解析器等。您可以使用@Configuration注解配合@EnableWebMvc注解来启用它。
  3. WebMvcConfigurationSupport可以使用@Autowired注解来注入其他的Bean,例如ConversionServiceValidator等。而WebMvcConfigurer则不能使用@Autowired注解,因为它是一个接口。 总的来说,WebMvcConfigurationSupport提供了更全面的WebMvc配置,但是它也更为复杂,适用于全局的配置。而WebMvcConfigurer则提供了更为灵活的配置方式,适用于局部的配置。
### Spring Boot 控制层的优点和特性 Spring Boot控制层主要依托于 Spring MVC 提供的功能,并在此基础上进行了优化和增强。以下是 Spring Boot 控制层的主要优点和特性: #### 1. **自动配置** Spring Boot 使用 `@EnableAutoConfiguration` 注解实现了自动配置功能,能够根据类路径中的依赖项自动生成所需的 Bean 和配置文件[^1]。这意味着开发者无需手动编写大量的 XML 配置或 Java 配置代码即可快速搭建 RESTful API 或 Web 应用。 #### 2. **简洁的注解支持** Spring Boot控制层充分利用了 Spring MVC 的注解机制,例如 `@RestController`, `@RequestMapping`, `@GetMapping`, `@PostMapping` 等。这些注解使得控制器方法的定义更加直观和易读[^2]。 - `@RestController`: 将返回的对象直接序列化为 JSON 或 XML 响应给客户端。 - `@RequestMapping`: 定义请求映射规则。 - `@PathVariable`, `@RequestParam`: 方便提取 URL 参数或查询参数。 #### 3. **内置嵌入式服务器** Spring Boot 默认集成了 Tomcat, Jetty 或 Undertow 这样的嵌入式服务器,因此不需要额外安装或配置外部容器即可运行应用程序。这极大地简化了开发和部署过程。 #### 4. **强大的异常处理能力** 通过 `@ControllerAdvice` 和 `@ExceptionHandler` 注解,Spring Boot 能够全局捕获并统一处理 HTTP 请求中的异常情况[^2]。这种设计不仅提高了代码的可维护性,还增强了用户体验的一致性。 #### 5. **灵活的消息转换器** Spring Boot 自动加载了许多消息转换器(Message Converters),比如 Jackson、Gson 等用于 JSON 数据解析的工具。它们允许开发者轻松实现数据格式之间的相互转化而无需关心底层细节。 #### 6. **测试友好型架构** 借助 `spring-boot-starter-test` 模块,Spring Boot 提供了一套完整的单元测试和集成测试解决方案[^3]。其中包括 MockMvc 测试框架来验证 Controller 层逻辑是否正常工作,从而保障高质量交付。 ```java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public ResponseEntity<User> getUserById(@PathVariable Long id) { User user = userService.findById(id); if (user != null) { return new ResponseEntity<>(user, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } } ``` 上述代码片段展示了如何利用 Spring Boot 创建一个简单的 REST 接口以获取指定 ID 的用户信息。 --- ### 问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Qrind

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值