springboot接口入参的一些问题

本文探讨了SpringBoot接口中遇到的入参类型转换错误问题,介绍了如何通过注解实现日期参数的转换,定义数据绑定类,以及创建自定义的参数转换器。同时,文章讲解了当入参错误时,如何设置全局异常处理,利用@RestControllerAdvice返回错误JSON对象,以适应接口返回需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springboot接口入参的一些问题

最近在工作中遇到一个接口入参类型转换错误未被处理的问题,于是整理了一些关于springmvc入参的问题

入参绑定

1、入参中我们最常见的是date类型的参数转换,这个可以通过注解来实现参数类型的转换,只需在bean对象的属性上方添加注解@DateTimeFormat(pattern=“yyyy-MM-dd”),pattern为时间对象的格式化
在这里插入图片描述

2、在controller类里定义数据绑定类

/**
     * 在controller层中加入一段数据绑定代码
     * @param webDataBinder
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) throws Exception{
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        simpleDateFormat.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class , new CustomDateEditor(simpleDateFormat , true));
    }

3、定义全局的参数类型转换器
首先建立一个实现Converter的转换器

 public class DateConverter implements Converter<String,Date> {
     private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     @Override
     public Date convert(String s) {
         if ("".equals(s) || s == null) {
            return null;
         }
         try {
            return simpleDateFormat.parse(s);
         } catch (ParseException e) {
             e.printStackTrace();
         }
         return null;
     }
 }

然后将该参数转换器绑定到springmvc的配置中

@Configuration
public class WebConfigBeans {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    /**
     * 增加字符串转日期的功能
     */

    @PostConstruct
    public void initEditableAvlidation() {

        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)handlerAdapter.getWebBindingInitializer();
        if(initializer.getConversionService()!=null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();           

            genericConversionService.addConverter(new StringToDateConverter());

        }

    }

}

入参错误全局异常处理

在springmvc的模型中,若参数转换出现异常,会直接跳转到默认的错误400页面,如果我们做的为接口,需返回一个代表错误的json对象时,我们可以使用一个全局的异常处理类,类上添加注解@RestControllerAdvice使得异常处理后返回rest风格的对象,使用@ControllerAdvice返回页面

@RestControllerAdvice
public class ControllerAdvice  {
@ExceptionHandler(value = {org.springframework.validation.BindException.class})
    public BaseResp dealDateFarmatException(Throwable exception) {
        BaseResp resp = new BaseResp();
        resp.setCode("400");
        resp.setStatus(false);
        resp.setMsg("参数类型错误");
        return resp;
    }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值