Detail Struts2 in json mutual reference dead loop solution

  • 2020-05-30 20:07:07
  • OfStack

Method 1: filter effects can be achieved with the configurable results supported by Struts 2. Action's result configuration supports regular expressions.

But if the object returned is an array of Json data. For example, peson Bean has an object persion1... person9, while I only need json data of person1, I can use the following regular expression.


<struts>
  <constant name="struts.objectFactory" value="spring"/>  
  <include file="struts-admin.xml"></include>
  <package name="default" extends="json-default">
    <action name="person" class="com.person.PersonAction" method="view">
    <result type="json">
      <param name="includeProperties">     
      person/[/d+/]/.person1
      </param>>     
    </result>
    </action>
  </package>   
</struts>

The use of the excludeProperties interceptor is the same, if only one object is intercepted, if the entire object of person Bean is intercepted.


<struts>
  <constant name="struts.objectFactory" value="spring"/>  
  <include file="struts-admin.xml"></include>
  <package name="default" extends="json-default">
    <action name="person" class="com.person.PersonAction" method="view">
    <result type="json">
      <param name="excludeProperties">     
      person
      </param>>     
    </result>
    </action>
  </package>   
</struts>

Method 2: it is important to note that if you use the JSON plug-in, the return result is JSON. The principle of JSON is that the get method is serialized in ACTION

So the previous get method will execute if it's not serialized. If the method 1 must be named get* (such as what interface is implemented), you can annotate the method to declare that it does not serialize.

The way to comment is: @JSON (serialize=false)

In addition, the JSON annotation supports the following fields:

serialize: sets whether to serialize the property deserialize: sets whether to deserialize the property. format: sets the format used to format the output and parse the date form field. For example, "yyyy MM - dd 'T HH: mm: ss".

// Use annotation syntax to change the property name after the property is serialized   

@JSON(name="newName")
 public String getName()
 {
  return this.name;
 }

Need to introduce import org. apache. struts2. json. annotations. JSON;


@JSON(serialize=false)
public User getUser() {
  return this.User;
}

@JSON(format="yyyy-MM-dd")
public Date getStartDate() {
  return this.startDate;
}

Related articles: