For the use of Strut2's built-in Json plug-in, Strut2's built-in Json plug-in

Source: Internet
Author: User

For the use of Strut2's built-in Json plug-in, Strut2's built-in Json plug-in

Configuration notes:

  • Under the introduction of the original Struts2 framework jar package, an additional Json plug-in package (struts2-json-plugin-2.3.7.jar) needs to be added)
  • In the struts. xml configuration file, the package must inherit json-default and change the result type to json.
  •  <package name="xxx" extends="json-default">
    <result name="success" type="json"></result>

 

1. Let's take a simple example. Use Struts2 + jQuery + JSON for Asynchronous interaction and return a string

1. index. jsp

A simple page uses Ajax to asynchronously send a post request to test1.action, pass a parameter name, and then display the value returned by the callback function on the page.

1 <% @ page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %> 2 <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 3 

2. TestAction. java

The page sends a parameter named name. Here we use Attribute injection to assign values to a member variable's setter method, and return a getter method as the return value of the callback function.

Struts2 Json plugin,By default, the top object of the value stack (root) is returned (all getter methods) without ModelDriven, the top object of the value stack is Action (that is, all the getter methods in the Action are returned. If there are different methods, you only need to add a @ JSON (serialize = false) annotation to the method)

For example:

@ JSON (serialize = false) public String getAge () {return "I am 10 years old ";}

 

1 package com. lcw. struts. json; 2 3 import com. opensymphony. xwork2.ActionSupport; 4 5 public class TestAction extends ActionSupport {6 7 private String name; 8 private String info; 9 10 public String getInfo () {11 return "I am:" + name; 12} 13 14 public void setName (String name) {15 this. name = name; 16} 17 18 public String test1 () {19 return "success"; 20 21} 22}

Struts. xml

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4     "http://struts.apache.org/dtds/struts-2.3.dtd"> 5  6 <struts>     7         <constant name="struts.i18n.encoding" value="UTF-8"/> 8         <constant name="struts.devMode" value="true" /> 9         <package name="strutsjson" extends="json-default" namespace="/">10             <action name="test1" class="com.lcw.struts.json.TestAction">11                 <result name="success" type="json">/index.jsp</result>12             </action>13         </package>14 </struts>

 

The following is the page effect: (here is a simple example. You can also implement some business logic functions. For example, to verify the user's account, you can call the data query at the persistent layer of Action to return a Boolean value, perform further operations in the callback function)

2. For more practical instances, for example, how to return a List set, objects, and other complex data, the front-end can only recognize the information of character types, such as Xml, json and Html characters cannot identify List sets. What should we do?

TestAction. java

This time, the model Driver Class is added to the Action, a User class is defined, and the setter and getter methods are provided to add the object to a List set, the getter method is provided to return data.

1 package com. lcw. struts. json; 2 3 import java. util. arrayList; 4 import java. util. list; 5 6 import com. opensymphony. xwork2.ActionSupport; 7 import com. opensymphony. xwork2.ModelDriven; 8 9 public class TestAction extends ActionSupport implements ModelDriven <User> {10 11 private User user = new User (); 12 13 public User getModel () {14 return user; 15} 16 17 private List <User> list; 18 19 public List <User> getList () {20 return list; 21} 22 23 public String test1 () {24 list = new ArrayList <User> (); 25 User user = new User (); 26 list. add (new User ("1", "Zhang San"); 27 list. add (new User ("2", ""); 28 return "success"; 29} 30 31}

User. java

package com.lcw.struts.json;public class User {    private String id;    private String name;    public User() {    }    public User(String id, String name) {        super();        this.id = id;        this.name = name;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

Keep the configuration file unchanged. Let's take a look at the results on the page:

Open firebug debugging and check, you will find

Why is the passed data empty? I wonder if you have noticed the above sentence.

Struts2 Json plugin,By default, the top object of the value stack (root) is returned (all getter methods) without ModelDriven, the top object of the value stack is Action (that is, all the getter methods in the Action)

We have implemented the Model Driver Class above, which means that the stack top object of the value stack is no longer an Action, but a Model, so the returned data is empty. What should we do? In fact, it is very simple. We only need to change the default returned team object and set it to Action.

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"    "http://struts.apache.org/dtds/struts-2.3.dtd"><struts>            <constant name="struts.i18n.encoding" value="UTF-8"/>        <constant name="struts.devMode" value="true" />        <package name="strutsjson" extends="json-default" namespace="/">            <action name="test" class="com.lcw.struts.json.TestAction" method="test1">                <result name="success" type="json">                    <param name="root">action</param>                </result>            </action>        </package></struts>

You just need to add a parameter root in result and set it to action. Let's take a look at the effect at this time:

We can use (data. list [x]. name, etc.) to retrieve the data.

So can we not return all the data together, but only part of the data? In addition to the Json annotation mentioned earlier (as long as @ JSON annotation, attributes will never be involved in json return), Struts2 provides us with a more flexible method in struts. in the xml configuration file, we can also set as needed, for example:

1 <param name="includeproperties">list\[\d+\]\.name</param>

IncludeProperties indicates the parameter to be included. The value is a regular expression, because the returned data is a list set and the name is list [\ d +]. name (representing the name attribute of all array indexes under the list) The backslash above is an escape character. (If you want to return the model-driven object, it is model [\ d +])

The complete configuration file is as follows:

Struts. xml

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4     "http://struts.apache.org/dtds/struts-2.3.dtd"> 5  6 <struts>     7         <constant name="struts.i18n.encoding" value="UTF-8"/> 8         <constant name="struts.devMode" value="true" /> 9         <package name="strutsjson" extends="json-default" namespace="/">10             <action name="test" class="com.lcw.struts.json.TestAction" method="test1">11                 <result name="success" type="json">12                     <param name="root">action</param>13                     <param name="includeproperties">14                         list\[\d+\]\.name15                     </param>16                 </result>17             </action>18         </package>19 </struts>

 

Let's look at the data returned from the page at this time:

In this way, we can filter out the desired data.

 


Struts2 json plug-in problems

Struts2 json returns an object ,,,

Struts2 uses the jsonplugin plug-in to escape the list generic output json data

Struts2 has a JsonUtil. serializable (Object obj); serialized into json, and the front-end js accepts and retrieves data.
 

Related Article

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.