1. 程式人生 > >Struts2返回Json資料(使用Struts2外掛)

Struts2返回Json資料(使用Struts2外掛)

這篇我將介紹如何使用Struts2的struts2-json-plugin.jar外掛返回JSON資料。

 

一、其中主要步驟有:

1.將struts2-json-plugin.jar外掛拷貝到專案的"/WEB-INF/lib"資料夾下;

2.編寫Action類檔案;

3.在struts.xml檔案中配置這個Action,這個Action所在的"<package.../>"必須繼承”json-default“, Action 的 Result  型別為  json ,即 type="json" ,而且不對應任何檢視資源。

 

二、示例程式碼:

Action類檔案:

複製程式碼

package com.example.action;

import java.util.ArrayList;

import com.opensymphony.xwork2.ActionSupport;

public class StrutsJsonAction extends ActionSupport {
    private int i=123;
    private String str="str";
    private int[] array={1,2,3};
    private ArrayList<String> list;
    
    public int getI() {
        return i;
    }
    public void setI(int i) {
        this.i = i;
    }
    public String getStr() {
        return str;
    }
    public void setStr(String str) {
        this.str = str;
    }
    public int[] getArray() {
        return array;
    }
    public void setArray(int[] array) {
        this.array = array;
    }
    public ArrayList<String> getList() {
        return list;
    }
    public void setList(ArrayList<String> list) {
        this.list = list;
    }
    public String execute(){
        list = new ArrayList<String>();
        list.add("red");
        list.add("green");
        list.add("yellow");
        return SUCCESS;
    }
}

複製程式碼

 

struts.xml檔案:

複製程式碼

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <package name="json-example" namespace="/" extends="json-default">
        <action name="JSONExample" class="com.example.action.StrutsJsonAction">
            <result name="success" type="json"/>
        </action>
    </package>
</struts>    

複製程式碼

然後在瀏覽器中訪問"   http://localhost:8080/Struts2_JSON/JSONExample  ",顯示結果如圖:

  JSON 外掛會將所有可序列化  Action  屬性序列化為 JSON  資料。

 

三、配置常用JSON型別的Result

瀏覽器是否快取JSON

<result type="json">
  <!-- 取消瀏覽器快取-->
  <param name="noCache">true</param>
</result>

 

 設定瀏覽器響應型別,預設為text/html

<result type="json">
  <!-- 設定伺服器響應型別-->
  <param name="contentType">application/json</param>
</result>

 

排除值為 null 的屬性

<result type="json">
  <!--排除值為null的屬性-->
  <param name="excludeNullProperties">true</param>
</result>

 

只序列化指定的Action屬性

<result type="json">
    <!--只序列化Action內的list屬性-->
    <param name="root">list</param>
</result>
序列化包含的屬性(逗號分隔的正則表示式列表)
<result type="json">
    <!--序列化list屬性-->
    <param name="includeProperties">list.*</param>
</result>
<result type="json">
    <!--序列化array屬性,\[和\]匹配陣列的[]括號,\d匹配數字,+表示一次或多次-->
    <param name="includeProperties">array\[\d+\]</param>
</result>
排除不需要被序列化的屬性(逗號分隔的正則表示式列表)
<result type="json">
     <!--排除list屬性-->
  <param name="excludeProperties"> list.* </param>
</result>

文章來源:https://www.cnblogs.com/liubaozhe/p/4418741.html