Detailed steps for binding custom parameters in SpringBoot and springboot
Under normal circumstances, parameters passed by the front-end can be directly received by SpringMVC, but there may also be some special circumstances, such as the Date object. When a Date is sent from the front-end, you need to bind custom parameters on the server to convert the frontend date. It is easy to bind custom parameters in 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 receives a string parameter, which is a Date string sent from the front end. The string meets the format of yyyy-MM-dd AND is converted to a Date object through SimpleDateFormat.
2. Configure the converter
Custom WebMvcConfig inherits WebMvcConfigurerAdapter and is configured in the addFormatters method:
@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new DateConverter()); }}
OK. After the above two steps, we can receive a string Date from the front end on the server and convert it into a Date object in Java. The front-end Date control is 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", "added successfully! ");} Return new RespBean (" error "," failed to add! ");}
The Employee has an attribute named birthday. The data type of this attribute is a Date.