JSON Basics of STRUTS2 (10)

Source: Internet
Author: User
Tags i18n jquery library


Introduction to JSON

JSON (JavaScript Object Notation), a JavaScript objects symbol, is a lightweight data interchange format. It is based on a subset of ECMAScript. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, and so on). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and generate (typically used to improve network transfer rates).

JSON is primarily based on the following two types of data structures:

> byKey-value toComposition of the data structure. There are different implementations in various languages, such as: An object in JavaScript, a map structure in Java, and a struct in the C language. In other languages, it is possible to record, dictionary, hash table.

>ordered Collection。 In different languages, it is possible to implement a list, vector, array, or sequence.

These are common data structures. Almost all modern programming languages have a corresponding implementation. So JSON can be used as a common data Interchange format in programming languages. There are two main types of JSON syntax in JavaScript, one for creating objects and one for creating arrays.

Basic Structure

JSON can be easily understood as objects and arrays in JavaScript, and these two structures can represent a variety of complex structures.

1. Object: The object in JS is represented as "{}" in the content, the data structure is {Key:value,key:value,...} The structure of key-value pairs, in object-oriented languages, key is the property of the object, value is the corresponding property value, so it is easy to understand that the value method is the object. Key Gets the property value, the type of the property value can be a number, a string, an array, several objects.

2, array: The array in JS is the middle bracket "[]" in the content, data structure for ["Java", "JavaScript", "VB",...], the value way and all languages, using index get, the type of field value can be number, string, array, object several.
Through the object, the array 2 kinds of structure can be combined into a complex data structure.

Simply put, JSON can convert a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or in an asynchronous application passing a string from a WEB client to a server-side program. JavaScript can easily interpret this string, and JSON can represent a more complex structure than a name/value pair. For example, you can represent arrays and complex objects, not just simple lists of keys and values.

Creating objects using JSON syntax

Use JSON syntax to create an object without writing a function, without the new keyword, you can get a JavaScript object directly. Here's the syntax.



When you create an object, you always end with {start with}, each property name and attribute value is separated by a colon (:), and multiple attribute definitions are separated by commas (,), with the following syntax:

object = {    propertyName1 : propertyValue1,   propertyName2 : propertyValue2,   ...}


Note that not every attribute definition is followed by a comma (,), a comma (,) must be followed by a property definition, and the last property is followed by a comma (,).

When you create a JavaScript object in JSON syntax, the property value can be either a normal string or any basic data type, or it can be a function, an array, or even another JSON syntax to create an object.

person = {   ‘Jujiu‘,   ‘male‘,   //使用JSON语法为期指定一个属性   son : {      ‘yoyo‘,      1   },   //使用JSON语法为person值分配一个方法   function{      document.writeln("姓名:"this"性别:"this.sex);   }}


Creating an array using JSON syntax

syntax for creating arrays using JSON syntax.



, the JSON-created array is always started with parentheses ([) and then placed in the array element, separated by a comma (,) between the elements, and the last array element followed by a comma, but ended with the English opposition brackets (]). The syntax for creating an array using JSON is as follows:

...]


Similar to JSON-created objects, the last element of an array cannot have a comma (,) after it.

Because the JSON syntax is simple and easy to use, and as a data transmission carrier, the data transfer volume is smaller, so in the Ajax interaction, XML is often not used as the data Interchange format, but the use of JSON as a data interchange format. Suppose you need to swap an object personn with the Name property of the Jujiu,gender property of 29, which can be simply written using JSON syntax:

person ={   ‘Jujiu‘,   ‘male‘,   29}


In XML Data Interchange Format, you write:

<person>   <name>Jujiu</name>   <gender>male</gender>   <age>29</age></person>


As you can see, using JSON syntax is a bit simpler.

When the server returns a string that satisfies the JSON format, you can then convert the string to a JavaScript object using the JSON extension method. Login http:www.json.org/ Json2.js site, download the Jsonn2.js file, which provides a global JSON object that contains two methods: Stringify and Parse, where the former is responsible for converting a JSON object into a JSON-formatted string, which is responsible for converting a JSON-formatted string into a JSON object.

Implementing the Action Logic

Take a look at the code first.

 PackageCom.afy.app.action;ImportJava.util.HashMap;ImportJava.util.Map;ImportCom.opensymphony.xwork2.Action;ImportOrg.apache.struts2.json.annotations.JSON; Public  class jsonexample{    //The member variable that simulates the result of processing    Private int[] INTs = {Ten, -};Privatemap<string, string> map =NewHashmap<string, string> ();PrivateString Customname ="Customer";//Package three member variables for request parameters    PrivateString field1;member variables modified by//' transient ' are not serialized    Private transientString Field2;//member variables without setter and getter methods are not serialized    PrivateString field3; PublicStringExecute() {Map.put ("Name","Crazy Java Handout");returnaction.success; }//Use annotations to change the name of the member variable after serialization    @JSON(name="NewName") PublicMapGetmap(){return  This. map; }//Customname Setter and getter Method     Public void Setcustomname(String customname) { This. customname = Customname; } PublicStringGetcustomname(){return  This. Customname; }//Field1 Setter and getter Method     Public void SetField1(String field1) { This. field1 = field1; } PublicStringGetField1(){return  This. field1; }//Field2 Setter and getter Method     Public void setField2(String field2) { This. field2 = Field2; } PublicStringgetField2(){return  This. field2; }//Field3 Setter and getter Method     Public void setField3(String field3) { This. field3 = field3; } PublicStringgetField3(){return  This. field3; }}


Here is the action class code that handles a page request, which contains three form fields that correspond to three request parameters, so you should use the action to encapsulate the three request parameters. The name of the three form fields is Field1, Field2, field3, respectively.

In the above code, the @json annotation is used and the Name property is specified when using the annotation, and the Name property is used to change the property name of the JSON object. In addition, the @JSON supports several properties as follows.

>serialize: Sets whether the serial number is the property.

> Deserialize: Sets whether the property is deserialized.

>format: Sets the format for formatting output, resolving Date form fields. such as "Yyyy-mm-dd ' T ' HH:mm:ss".

JSON plug-in with result of JSON type

The JSON plug-in provides a JSON-type result that, once specified with a result of type JSON for an action, does not map to any view resource. Because the JSON plug-in is responsible for serializing the state information in the action into a JSON-formatted string and returning the string to the client browser.

The JSON plug-in allows the action to be invoked asynchronously in JavaScript on the client page, and the action no longer needs to use the view resource to display the state of the action, but rather the JSON plugin returns the state information from the action to the calling page, in this way, You can complete the Ajax interaction.

You can add a JSON plugin for the Struts2 app by copying the Struts2-json-plugin-2.3.16.3.jar file under the Lib subdirectory of the Struts2 directory to the Web-inf\lib directory of the Web App.

The next configuration provides an action that returns a JSON string, to configure a result of type JSON for the action, and this result does not require any view resources to be configured. The Struts.xml file that configures the action is as follows.

<?xml version= "1.0" encoding= "GBK"?><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.3//en" "Http://struts.apache.org/dt Ds/struts-2.3.dtd "><struts>    <constant name="struts.i18n.encoding" value="UTF-8"/>     < package name="Example" extends= "json-default">         <action name= "jsonexample" class=" Org.crazyit.app.action.JSONExample ">            <!--configuration Type JSON result---            <result type="json">                <!--specify parameters for the result--                <param name="NoCache">True</param>                <param name="ContentType">Text/html</param>                <!--Set the Map property of the sequence action only--                <!--param name= "root" >map</param --            </result>        </Action>        <action name="*">            <result>/web-inf/content/{1}.jsp</result>        </Action>    </Package ></struts>


The two places to note are:

①. When configuring Struts.i18n.encoding constants, GBK encoding is not used, and UTF-8 is used because Ajax post requests are encoded in UTF-8 manner.

②. Own package to inherit the Json-default package, instead of inheriting the default defaults package, because only this package has the JSON type of result.

When you configure a view name to result of a JSON type, you do not need to specify any view resources, and the JSON plugin sends the action to the client after it is serialized.

Implementing JSP Pages

To facilitate AJAX interaction, this page uses jquery, which allows you to simply access the DOM nodes in the page, including better Ajax interactions, avoiding the tedious steps of creating XMLHttpRequest objects and sending asynchronous requests. See the JSP page code below.

<%@ page contenttype="text/html; CHARSET=GBK " language=" java " errorpage="" %><%@ taglib prefix="s" uri="/struts-tags" %><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title>Using the JSON plugin</title>    <script src="${pagecontext.request.contextpath}/jquery-1.11.1.js"type ="Text/javascript">         </script>    <script type="Text/javascript">         function gotclick(){$("#show"). Hide ();//Specify to send a request to Jsonexample to convert the form control contained in the form with ID Form1 to the request parameter$.post ("Jsonexample", $("#form1"). Serializearray (),//Specify callback function                 function(data, statustext){$("#show"). Height ( the). Width ( -). CSS ("Border","1px solid black"). CSS ("Border-radius","15px"). CSS ("Background-color","#efef99"). CSS ("Color","#ff0000"). CSS ("padding","20px"). empty ();//Traverse each property of a JavaScript object                     for(varPropNameinchData) {$ ("#show"). Append (propname +" --"+ Data[propname] +"<br/>"); }                    $("#show"). Show ( -); },//Specify server response as JSON data                "JSON"); }</script></head><body><s:form id="Form1">    <s:textfield name="field1" label="Field 1"/>    <s:textfield name="Field2" label="Field 2"/>     <s:textfield name="field3" label="Field 3"/>     <tr><TD colspan="2">    <input type="button" value="Commit" onclick=" Gotclick (); " />    </td></tr></s:form><div id="Show"></div></body></html>


In order to use the jquery library, you import the code library of jquery to that page. The page can take the state information of the entire action instance, including each property name in the action instance, and the corresponding property value, so that the result of Struts2 's processing of the request can be fully obtained, and the rest is that the processing results are displayed through DOM manipulation.

JSON Basics of STRUTS2 (10)

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.