Spring MVC automatic Date formatting bindings

Source: Internet
Author: User

in Springmvc, we will often use its automatic binding parameters, binding date often reported 400 error → Bad Request (
The request was faulted and the server was unable to understand the request due to a malformed syntax. The client program cannot repeat this request without modification .)
Nonsense not much to say, directly on the code,
There are a number of workarounds:
   the first type:     
   Pre name= "code" class= "HTML" ><bean id= "Conversionservice" class= " Org.springframework.format.support.FormattingConversionServiceFactoryBean "><property name=" formatters " ><set><bean class= "Com.sfbf.util.DateFormatter" ></bean></set></property></ Bean> 

I wrote a dateformatter in the background to implement the Formatter<date> interface:
Import Java.text.parseexception;import java.text.simpledateformat;import java.util.date;import Java.util.Locale; Import Org.springframework.format.formatter;public class Dateformatter implements formatter<date> {@ Overridepublic String Print (Date arg0, Locale arg1) {//TODO auto-generated method Stubreturn null;} @Overridepublic Date Parse (String text, locale locale) throws parseexception {SimpleDateFormat format = new Simpledateform At ("Yyyy-mm-dd HH:mm:ss");D ate Date = null;try {if (! "). Equals (text) &&null!=text) date = Format.parse (text);} catch (Exception e) {format = new SimpleDateFormat ("YYYY-MM-DD");d ate = Format.parse (text);} return date;}}
The second method:You can add annotations directly to the method @ResponseBody return the JSON data if the JavaBean property contains data of the date type:
   like the blog I wrote earlier http://blog.csdn.net/u012169499/article/details/45026411  
write a jsondateserializer to let it inherit Jsonserializer, and then adds the specified annotation on the property methodof the corresponding entity:@JsonSerialize  can be implemented. 

Spring MVC automatic Date formatting bindings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.