Spring MVC4 using and JSON date conversion solutions __js

Source: Internet
Author: User
Tags dateformat static class string format tojson

When it comes to the new development environment, it is always not exempt from the Internet to search the current framework. Spring is a necessary framework for web development, so it downloads the latest spring4.0.3 and, increasingly, does not want to use struts2 to try Spring MVC, Also spring-webmvc4.0.3 down, invested two days to study, found that it is quite elegant, especially from 3.0, spring MVC using the annotation method, as well as the rest style support, is very perfect.
Below is a summary of the issues that have been studied over the next two days for reference. The
1.request object gets
Mode 1:
adds the request parameter to the Controller method, and spring is automatically injected, such as: Public String list ( HttpServletRequest request,httpservletresponse response)
Mode 2: add @resource Private in the controller class HttpServletRequest Request property, spring is automatically injected, so it is not known whether threading problems occur because a controller instance serves multiple requests and is not tested.
Mode 3: write code directly in the controller method get HttpServletRequest request = (servletrequestattributes) Requestcontextholder.getrequestattributes ()). Getrequest ();
Mode 4: Add the following method to controller, which executes before executing this controller method

@ModelAttribute
private void Initservlet (HttpServletRequest request,httpservletresponse response) {
    // String p=request.getparameter ("P");
    this.req=request;//instance variables, thread security issues, can be saved using threadlocal mode
}

2.response Objects can be obtained by referring to the above request for Access mode 1 and Mode 4, mode 2 and Mode 3 are not valid for the response object.
3. Data filling of form submission

By adding entity object parameters directly to the method, Spring automatically populates the properties in the object, and the object property names are populated with the name of <input>, such as public Boolean Doadd (Demo demo) 4. Form submission Data Conversion-date type

By adding a @DateTimeFormat (pattern= "Yyyy-mm-dd HH:mm:ss") on a property or a Get method of an entity class, the date string in the form is correctly converted to the date type. There are @numberformat annotations, temporarily useless, do not introduce, a look will know is to convert to digital. 5.json Data Return
Add @responsebody to the method, and the method returns a value of the entity object, and spring automatically converts the object to JSON format and returns to the client. As shown below:

@RequestMapping ("/json1")
@ResponseBody public
demo Json1 () {
    demo demo=new demo ();
    Demo.setbirthday (New Date ());
    Demo.setcreatetime (New Date ());
    Demo.setheight (170);
    Demo.setname ("Tomcat"); 
    Demo.setremark ("JSON test"); 
    Demo.setstatus ((short) 1); 
    return demo;
}
Note: The spring configuration file should be added: <mvc:annotation-driven/&gt, and also introduce Jackson-core.jar,jackson-databind.jar, Jackson-annotations.jar (2.x packets) will automatically convert JSON
This approach is provided by spring, we can also customize output JSON, the second is not to get the response object, get the response object, let the developer slaughter, want to how to return to return.
method does not have a return value, as follows:
@RequestMapping ("/json2") public
void Json2 () {
    demo demo=new demo ();
    Demo.setbirthday (New Date ());
    Demo.setcreatetime (New Date ());
    Demo.setheight (170);
    Demo.setname ("Tomcat");
    Demo.setremark ("JSON test");
    Demo.setstatus ((short) 1);
    String Json=jsonutil.tojson (obj);//;json processing Tool class
    httpservletresponse response =//Get Response object
    Response.getwriter (). print (JSON);
OK, everything is perfect. Then the disgusting question comes to you. When the date type is converted to a JSON string, it returns a long time value, and if you want to return the string in the format "Yyyy-mm-dd HH:mm:ss", it is also customized. I'm surprised that there is no @datetimeformat annotation, why not use it. Is it not necessary for @datetimeformat to convert a string to a date type only when the form is submitted, and when the date type is converted to a JSON string. With a puzzled search source, the original spring using Jackson to convert JSON characters, and @datetimeformat is the class in the Spring-context package, Jackson How to convert, Spring inconvenient too much interference, So you can only follow Jackson's conversion rules, custom date converters.
First write a date converter, as follows:
public class Jsondateserializer extends jsonserializer<date> {
   private SimpleDateFormat dateformat=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
   @Override public
   void Serialize (date date, Jsongenerator Gen, Serializerprovider provider)
           throws IOException, jsonprocessingexception {
       String value = Dateformat.format (date);
       Gen.writestring (value);
   }
}
Configure the use of the converter on the Get method of the entity class as follows:
@DateTimeFormat (pattern= "Yyyy-mm-dd HH:mm:ss")
@JsonSerialize (using=jsondateserializer.class)
public Date Getcreatetime () {return
    this.createtime;
}
OK, here we go.
Are you really satisfied with such an elegant solution, assuming that the birthday attribute is like this, only the month and the day
@DateTimeFormat (pattern= "YYYY-MM-DD") public
Date Getbirthday () {return
    this.birthday;
}
Which means, it's going to have to customize a jsondate. 2Serializer the converter, and then configure it like this
@DateTimeFormat (pattern= "Yyyy-mm-dd")
@JsonSerialize (using=jsondate2serializer.class) public
Date Getbirthday () {return
    this.birthday;
}
Suppose you have a date field in another format, and you have to customize another converter for it. My God, please forgive my sins, don't make me feel so bad
After analyzing the source code, find a good solution, this scheme will no longer use @jsonserialize, but only the use of @datetimeformat configuration date format, Jackson can be correctly converted, but @datetimeformat can only be configured on the Get method, It doesn't matter.
The following classes are introduced first, and this class makes annotation scanning interception for Jackson's Objectmapper class so that it can apply date formatting rules to the @datetimeformat get method.
Package com.xxx.utils;
Import java.io.IOException;
Import java.lang.reflect.AnnotatedElement;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Org.springframework.format.annotation.DateTimeFormat;
Import org.springframework.stereotype.Component;
Import Com.fasterxml.jackson.core.JsonGenerator;
Import com.fasterxml.jackson.core.JsonProcessingException;
Import Com.fasterxml.jackson.databind.JsonSerializer;
Import Com.fasterxml.jackson.databind.ObjectMapper;
Import Com.fasterxml.jackson.databind.SerializerProvider;
Import com.fasterxml.jackson.databind.introspect.Annotated;
Import Com.fasterxml.jackson.databind.introspect.AnnotatedMethod;

Import Com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; /** * JSON processing tool class * @author Zhangle */@Component public class Jsonutil {private static final String Default_da
        te_format= "Yyyy-mm-dd HH:mm:ss";
        
        Private static final Objectmapper mapper;
  Public Objectmapper Getmapper () {              return mapper;
                
                } static {SimpleDateFormat DateFormat = new SimpleDateFormat (Default_date_format);
                Mapper = new Objectmapper ();
                Mapper.setdateformat (DateFormat);
                        Mapper.setannotationintrospector (New Jacksonannotationintrospector () {@Override
                                        Public Object Findserializer (annotated a) {if (a instanceof Annotatedmethod) {
                                        Annotatedelement m=a.getannotated ();
                                        DateTimeFormat an=m.getannotation (Datetimeformat.class); if (an!=null) {if (! Default_date_format.equals (An.pattern ()) {return new Jsondateser
                                                Ializer (An.pattern ());
          }                              } return Super.findseriali
                        Zer (a);
        }
                }); public static String Tojson (Object obj) {try {return MAPPER.W
                Ritevalueasstring (obj);
                catch (Exception e) {throw new RuntimeException ("Convert JSON character failed!");
                        } public <T> T toobject (String json,class<t> clazz) {try {
                Return Mapper.readvalue (JSON, clazz);
                catch (IOException e) {throw new RuntimeException ("Failed to convert JSON characters to Objects!"); } public static class Jsondateserializer extends jsonserializer<date>{privat
            e SimpleDateFormat DateFormat; Public Jsondateserializer (String format) {DateFormat = NEW SimpleDateFormat (format); @Override public void serialize (date date, Jsongenerator gen, Serializerprovider PR Ovider) throws IOException, jsonprocessingexception {String value = Dateformat.format
                (date);
            Gen.writestring (value); }
        }
}
Then change the <mvc:annotation-driven/> to the following configuration, configure a new JSON converter, and set its Objectmapper object to the Objectmapper object in Jsonutil. This converter has a higher priority than the JSON built-in, so the JSON-related transformations will be used preferentially by spring.
<mvc:annotation-driven>
	<mvc:message-converters>
		<bean class= " Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter ">
			<property name=" Objectmapper "value=" #{jsonutil.mapper} "/>
			<property name=" Supportedmediatypes ">
				<list>
					<value>text/json;charset=UTF-8</value>
				</list>
			</property>  
		</bean >
	</mvc:message-converters>
</mvc:annotation-driven>

You can then configure the entity classes so that Jackson can also convert the date type correctly

@DateTimeFormat (pattern= "Yyyy-mm-dd HH:mm:ss") Public
Date Getcreatetime () {return
    this.createtime;
}
@DateTimeFormat (pattern= "YYYY-MM-DD") public
Date Getbirthday () {return
    this.birthday;
}

Finished, everything is perfect.


Following is the 2014/4/21 supplement

Wrote so much, found white busy, the original Jackson also has a @jsonformat annotation, configure it to the date type of Get method, Jackson will be in the configuration format conversion date type, but not custom converter class, want to cry no tears AH. Hard work so much, in fact, others have already provided, just did not find it.

Don't say, directly to the plan.

The 1.spring configuration is still the same:

<mvc:annotation-driven>

2.JsonUtil is OK, but if you want to output JSON from the response object, you can still use it, but instead

package com.xxx.utils;
Import java.io.IOException;
Import Java.text.SimpleDateFormat;
Import org.springframework.stereotype.Component;

Import Com.fasterxml.jackson.databind.ObjectMapper; /** * JSON processing tool class * @author Zhangle */@Component public class Jsonutil {private static final String Default_date_form
	at= "Yyyy-mm-dd HH:mm:ss";

	Private static final Objectmapper mapper;
		static {SimpleDateFormat DateFormat = new SimpleDateFormat (Default_date_format);
		Mapper = new Objectmapper ();
	Mapper.setdateformat (DateFormat);
		public static String Tojson (Object obj) {try {return mapper.writevalueasstring (obj);
		catch (Exception e) {throw new RuntimeException ("Convert JSON character failed!");
		} public <t> T Toobject (String json,class<t> clazz) {try {return Mapper.readvalue (JSON, clazz);
		catch (IOException e) {throw new RuntimeException ("Failed to convert JSON characters to Objects!"); } {}</t></t> 

3. The entity class's Get method requires one more @jsonformat annotation configuration

@DateTimeFormat (pattern= "Yyyy-mm-dd HH:mm:ss")
@JsonFormat (pattern= "Yyyy-mm-dd HH:mm:ss", timezone = "gmt+8") Public
Date Getcreatetime () {return
this.createtime;
}
@DateTimeFormat (pattern= "Yyyy-mm-dd")
@JsonFormat (pattern= "Yyyy-mm-dd", timezone = "gmt+8") public
Date Getbirthday () {return
	this.birthday;
}

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.