1、在基于Struts2的web工程中,首先引入 struts2-json-plugin-2.1.8.jar jar包插件
2、在Struts2的配置文件中设置包继承
3、在对应的Action方法中进行设置
package com.action;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.dao.TYuangongDAO;
import com.model.TYuangong;
import com.opensymphony.xwork2.ActionSupport;
public class yuangongAction extends ActionSupport {
private Map jsonData = new HashMap();
public Map getJsonData() {
return jsonData;
}
public void setJsonData(Map jsonData) {
this.jsonData = jsonData;
}
public String yuangongToEdit() {
TYuangong yuangong = yuangongDAO.findById(id);
// jsonData对象必须设置有get set方法 ,其次这个jsonData对象在Struts的配置文件中进行参数配置配置
jsonData.put("yuangong"; yuangong);
return ActionSupport.SUCCESS;
}
}
4、在Struts2的配置文件中进行对当前Action进行配置,配置如下
<action name="yuangongToEdit" class="yuangongAction" method="yuangongToEdit">
<result name="success" type="json">
<!-- 设置返回对象根目录参数为 jsonData ,这个参数名称就是对应的action程序里面设置要返回的对象 -->
<param name="root">jsonData</param>
</result>
</action>
5、浏览器访问
输入 http://localhost:8080/xxxx/yuangongToEdit.action?id=10
浏览器返回:
{"yuangong":{"address":"江苏省南京市","age":"22","del":"no","id":8,"loginname":"11","loginpw":"11","name":"文之秀","quanxian":"putongyuangong","sex":"男","tel":"12121212"}}