SpringBoot custom parameter binding steps detailed
- 2021-01-22 05:07:22
- OfStack
Normally, parameters passed by the front end can be directly received by SpringMVC, but there are some special cases, such as Date object, when I send a date from the front end, the server needs to define the parameter binding to convert the front end date. Customizing parameter bindings is also simple and consists of two steps:
1. Custom parameter converter
The custom parameter converter implements the Converter interface as follows:
public class DateConverter implements Converter<String,Date> {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
@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;
}
}
The convert method takes a string argument, which is the date string from the front end. This string is in the yyyy-MM-dd format, and it is returned by SimpleDateFormat as an Date object.
2. Configure the converter
Custom WebMvcConfig inherits WebMvcConfigurerAdapter and is configured in the addFormatters method:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
}
OK, after the above two steps, we can on the server receives a front end of the string from the date and place it into Java Date object, front end date controls are as follows:
<el-date-picker
v-model="emp.birthday"
size="mini"
value-format="yyyy-MM-dd HH:mm:ss"
style="width: 150px"
type="date"
placeholder=" Date of birth ">
</el-date-picker>
The server interface is as follows:
@RequestMapping(value = "/emp", method = RequestMethod.POST)
public RespBean addEmp(Employee employee) {
if (empService.addEmp(employee) == 1) {
return new RespBean("success", " Add a success !");
}
return new RespBean("error", " Add failure !");
}
There is an attribute named birthday in Employee, whose data type is 1 Date