Output an instance of JSON data in Action as Struts2

  • 2020-05-16 07:03:32
  • OfStack

Here is the complete code for the entire Action:


package cn.ysh.studio.struts2.json.demo.action; 
 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.HashMap; 
import java.util.Map; 
 
import javax.servlet.http.HttpServletResponse; 
 
import org.apache.struts2.ServletActionContext; 
 
import net.sf.json.JSONObject; 
 
import cn.ysh.studio.struts2.json.demo.bean.User; 
 
import com.opensymphony.xwork2.ActionSupport; 
 
public class UserAction extends ActionSupport { 
 
  /** 
   * 
   */ 
  private static final long serialVersionUID = 1L; 
 
  // Will be Struts2 Serialized as JSON Object of a string  
  private Map<String, Object> dataMap; 
 
  /** 
   *  A constructor  
   */ 
  public UserAction() { 
    // Initialize the Map object  
    dataMap = new HashMap<String, Object>(); 
  } 
 
  /** 
   *  The test pass action Returns as a view JSON data  
   * @return 
   */ 
  public String testByJSP() { 
    User user = new User(); 
    user.setId("123"); 
    user.setName("JSONActionJSP"); 
    user.setPassword("123"); 
    user.setSay("Hello world !"); 
    JSONObject jsonObject=new JSONObject(); 
    jsonObject.accumulate("user", user); 
    jsonObject.accumulate("success", true); 
    // Here in request In the object 1 a data , so struts the result Cannot be in configuration type="redirect" 
    ServletActionContext.getRequest().setAttribute("data", jsonObject.toString()); 
    return SUCCESS; 
  }; 
 
  /** 
   *  The test pass action In order to Struts2 Return by default JSON data  
   * @return 
   */ 
  public String testByAction() { 
    // dataMap The data in the Struts2 Converted to JSON String, so I'm going to clean it up first  
    dataMap.clear(); 
    User user = new User(); 
    user.setId("123"); 
    user.setName("JSONActionStruts2"); 
    user.setPassword("123"); 
    user.setSay("Hello world !"); 
    dataMap.put("user", user); 
    //  In the 1 Whether the operation was successful or not  
    dataMap.put("success", true); 
    //  Returns the result  
    return SUCCESS; 
  } 
 
  /** 
   *  through action Return in the traditional way JSON data  
   * @throws IOException 
   */ 
  public void doAction() throws IOException{ 
    HttpServletResponse response=ServletActionContext.getResponse(); 
    // The following code is derived from JSON.java It was copied in  
    response.setContentType("text/html"); 
    PrintWriter out; 
    out = response.getWriter(); 
    // Object to be returned to the client  
    User user=new User(); 
    user.setId("123"); 
    user.setName("JSONActionGeneral"); 
    user.setPassword("JSON"); 
    user.setSay("Hello , i am a action to print a json!"); 
    JSONObject json=new JSONObject(); 
    json.accumulate("success", true); 
    json.accumulate("user", user); 
    out.println(json.toString()); 
//    because JSON The data is passed as a normal string, so we can manually concatenate it JSON The syntax specification string is output to the client  
//    The function of the following two sentences and 38-46 The line of code does 1 This will be returned to the client 1 a User Object, and 1 a success field  
//   String jsonString="{\"user\":{\"id\":\"123\",\"name\":\"JSONActionGeneral\",\"say\":\"Hello , i am a action to print a json!\",\"password\":\"JSON\"},\"success\":true}"; 
//   out.println(jsonString); 
    out.flush(); 
    out.close(); 
  } 
   
  /** 
   * Struts2 When serializing a specified property, you must have the property of that property getter Method, in fact, if there are no properties, there are only getter The method is also ok  
   * @return 
   */ 
  public Map<String, Object> getDataMap() { 
    return dataMap; 
  } 
 
} 

The complete struts.xml configuration file is as follows:


<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  "http://struts.apache.org/dtds/struts-2.0.dtd"> 
<struts> 
  <package name="json" extends="json-default" namespace="/test"> 
    <action name="testByAction" 
      class="cn.ysh.studio.struts2.json.demo.action.UserAction" method="testByAction"> 
      <result type="json"> 
        <!--  Here specify will be Struts2 Serialized the property in the action There has to be a counterpart getter methods  --> 
        <!--  The default will be to sequence everything that has a return value getter The value of a method, whether or not the method has a corresponding property  --> 
        <param name="root">dataMap</param> 
        <!--  Specifies whether to serialize null properties  --> 
        <!-- 
        <param name="excludeNullProperties">true</param> 
        --> 
        <!--  This specifies that it will be serialized dataMap Those properties in  --> 
        <!--  
        <param name="includeProperties"> 
          userList.* 
        </param> 
         --> 
        <!--  This specifies that you will start from dataMap , which will not be serialized, 1 Half does not appear with the above parameter configuration  --> 
        <!--  
        <param name="excludeProperties"> 
          SUCCESS 
        </param> 
        --> 
      </result> 
    </action> 
  </package> 
  <package name="default" extends="struts-default" namespace="/"> 
    <action name="testJSONFromActionByGeneral" 
      class="cn.ysh.studio.struts2.json.demo.action.UserAction" method="doAction"> 
    </action> 
    <action name="testByJSP" 
      class="cn.ysh.studio.struts2.json.demo.action.UserAction" method="testByJSP"> 
      <result name="success">/actionJSP.jsp</result> 
    </action> 
  </package> 
</struts> 

Related articles: