Many times the front end needs to invoke the background service to implement interactive functions, the common data Interchange format is mostly JSON or XML, here is the main explanation spring MVC for the front-end to provide JSON-formatted data and to achieve interaction with the foreground.
I. Summary
JSON (JavaScript object Notation, JS tag) is a lightweight data interchange format. It is based on a subset of ECMAScript (the JS specification developed by the consortium) that stores and represents data in a text format that is completely independent of the programming language. The simplicity and clarity of the hierarchy makes JSON an ideal data exchange language. Easy for people to read and write, but also easy to machine analysis and generation, and effectively improve the network transmission efficiency.
In the JS language, everything is an object. Therefore, any supported type can be represented by JSON, such as strings, numbers, objects, arrays, and so on. However, objects and arrays are two of the more special and common types.
(1) To implement a conversion from an object to a JSON string, use the Json.stringify () method:
var json = json.stringify ({A: ' Hello ', B: ' World '}); The result is ' {' A ': ' Hello ', ' B ': ' World '} '
(2) To implement a conversion from JSON to an object, use the Json.parse () method:
var obj = Json.parse (' {"A": "Hello", "B": "World"} '); The result is {a: ' Hello ', B: ' World '}
Example:
<! DOCTYPE html>ifLTE IE 8]> <script type= "Text/javascript" src= "//res.wx.qq.com/a/wx_fed/webwx/res/json3.min.js" ></ Script> <! [endif]--> //JS Objectvar user = { "Name": "Jacky", "Address": "Hong Kong, China" }; //convert an object to a charactervar str =json.stringify (user); alert (str); //Convert a string to a JSON objectvar zxy =json.parse (str); Alert (Zxy.name+ "," +zxy.address); </script> </body>View CodeOperation Result:
Second, the use of Modelandview
Pom.xml added to Jackson's dependency
<!--https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId> jackson-databind</artifactid> <version>2.9.2</version> </dependency>
View CodeAdd an action to the user controller
@RequestMapping (value = "/users") public Modelandview users () { Modelandview Mav= New Modelandview (new Mappingjackson2jsonview ()); Mav.addobject (Userservice.queryallusers ()); return Mav; }
View CodeOperation Result:
Iii. use of @responsebody and Jackson
Modify Pom.xml to add a dependency on Jackson
<!--https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId> jackson-databind</artifactid> <version>2.9.2</version> </dependency>
View CodeAdd an action, use annotation @responsebody, response body instead of path
@RequestMapping (value = "/userjson", produces = "Application/json;charset=utf-8") @ResponseBody Public String Userjson () { objectmapper mapper=new objectmapper (); Try { return mapper.writevalueasstring (Userservice.queryallusers ()); Catch (jsonprocessingexception e) { e.printstacktrace (); } return NULL ; }
View CodeOperation Result:
Four, garbled problem
(1) Method One: Declare the encoding format on the action
@RequestMapping (path= "/json", produces = "application/json;charset=utf-8")
View Code(2) Method Two: Modify the Spring configuration file
The previous method is cumbersome, and if there are many actions in the project, each one is added and can be specified uniformly by spring configuration
<mvc:annotation-driven> <mvc:message-converters register-defaults= "true" > class= " Org.springframework.http.converter.StringHttpMessageConverter "> <constructor-arg value=" UTF-8 "/> </bean> class= "Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > < Property name= "Objectmapper" > class= " Org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean "> <property name=" Failonemptybeans "value=" false "/> </bean> </property> </bean> </MVC :message-converters></mvc:annotation-driven>
View CodeV. Date formatting issues
The default date format becomes a number, which is the number of milliseconds from January 1, 1970 to the current date:
Jackson By default is turned into timestamps form
(1) Method One: Note Field
Format dates with @jsonformat annotations on entity fields
@JsonFormat (locale= "zh", timezone= "gmt+8", pattern= "Yyyy-mm-dd HH:mm:ss")
Code:
/** * Date of birth * * @JsonFormat (locale= "zh", timezone= "gmt+8", pattern= " Yyyy-mm-dd HH:mm:ss ") private Date birthday;
View CodeOperation Result:
(2) Method two: Cancel timestamps form
If you cancel, you will get a default date format that looks like this:
Of course the custom output format is allowed
@RequestMapping (value = "/userjson", produces = "Application/json;charset=utf-8") @ResponseBody PublicString Userjson () {Objectmapper mapper=NewObjectmapper (); //do not use the time difference methodMapper.configure (Serializationfeature.write_dates_as_timestamps,false); //Custom Date Format ObjectsSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); //Specify date formatMapper.setdateformat (SDF); Try { returnmapper.writevalueasstring (Userservice.queryallusers ()); } Catch(jsonprocessingexception e) {e.printstacktrace (); } return NULL; }
View CodeOperation Result:
Six, Tool class
Tool classes can reuse code to improve development efficiency, such as the serialized JSON above:
Packagecom.zhangguo.springmvc08.utils;Importcom.fasterxml.jackson.core.JsonProcessingException;ImportCom.fasterxml.jackson.databind.ObjectMapper;Importcom.fasterxml.jackson.databind.SerializationFeature;ImportJava.text.SimpleDateFormat;/*** JSON tool class, auxiliary class **/ Public classJsonutil { Public StaticString Getjson (Object object) {returnGetjson (Object, "Yyyy-mm-dd HH:mm:ss"); } Public StaticString Getjson (Object object,string dateformat) {objectmapper mapper=NewObjectmapper (); //do not use the time difference methodMapper.configure (Serializationfeature.write_dates_as_timestamps,false); //Custom Date Format ObjectsSimpleDateFormat SDF =NewSimpleDateFormat (DateFormat); //Specify date formatMapper.setdateformat (SDF); Try { returnmapper.writevalueasstring (object); } Catch(jsonprocessingexception e) {e.printstacktrace (); } return NULL; }}
View CodeCall:
@RequestMapping (value = "/userjson", produces = "Application/json;charset=utf-8") @ResponseBody Public String Userjson () { return Jsonutil.getjson (Userservice.queryallusers (), "YYYY-MM-DD"); }
View CodeSPRINGMVC Implementing JSON