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;
}
}