浅谈struts2和json的集成

    该例子以非常简单的形式描述了struts2和json的集成开发。。和大家共同学习。。
我用到的是struts2.2.3的jar包。
除了导入struts2的jar包外,还引入struts2-json-plugin.jar


jsonexample.java

package com.lysf.json;

import java.util.hashmap;
import java.util.map;

import org.apache.struts2.json.annotations.json;

import com.opensymphony.xwork2.action;

public class jsonexample {
    private string field1 = "str";
    private int[] ints = {10, 20};
    private map map = new hashmap();
    private string customname = "custom";

    //'transient' fields are not serialized
    private transient string field2;

    //fields without getter method are not serialized
    private string field3;

    public string execute() {
        map.put("john", "galt");
        return action.success;
    }

    public string getfield1() {
        return field1;
    }

    public void setfield1(string field1) {
        this.field1 = field1;
    }

    public int[] getints() {
        return ints;
    }

    public void setints(int[] ints) {
        this.ints = ints;
    }

    public map getmap() {
        return map;
    }

    public void setmap(map map) {
        this.map = map;
    }

    @json(name="newname")
    public string getcustomname() {
        return this.customname;
    }
}

struts.xml

<package name="example" extends="json-default">
     <action name="jsonexample" class="com.lysf.json.jsonexample">
      <result type="json"/>
     </action>
    </package>

web.xml

<filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>




最后得到的结果为:

{"newname":"custom","field1":"str","ints":[10,20],"map":{"john":"galt"}}
 

你可能感兴趣的:(java,工作)