日期:2014-05-16  浏览次数:20356 次

Struts2中使用JSON
Struts2对JSON的良好支持让我们可以更加方便的使用ajax和json。

需要的jar包有(附件里面都有,可以下载):
json-lib-2.1-jdk15.jar,
ezmorph-1.0.3.jar,
struts2-json-plugin-2.2.1.jar,(也就是googlecode(http://jsonplugin.googlecode.com/files/jsonplugin-0.34.jar)上面的jsonplugin,在struts2_2.2.1的里面叫struts2-json-plugin-2.2.1.jar),
struts2-core-2.2.1.jar
xwork-core-2.2.1.jar


struts.xml的配置:
 <package name="test"  extends="json-default">
   <action name="*Area" class="com.yeepay.agent.action.AreaAction" method="{1}">
	 <interceptor-ref name="json" /><!--处理以JSON文本提交的请求-->  
	 <result name="findProvince" type="json" />  
	 <result name="findCityByProvince" type="json" />
    </action>
</package>


Action的代码:
@SuppressWarnings("serial")
public class AreaAction extends BaseAction{
public static final Logger log = Logger.getLogger(AreaAction.class);
	private String areaList=null;
	private AreaBaseService areaBaseService;
  public String findProvince(){
	try {
		List<Area> list=areaBaseService.findProvince();
		JSONArray arrayObject=JSONArray.fromObject(list);
		areaList=arrayObject.toString();
	} catch (SQLException e) {
		log.error(e);
	}
	return "findProvince";
  }
	public String getAreaCode() {
		return areaCode;
	}
	public void setAreaCode(String areaCode) {
		this.areaCode = areaCode;
	}
	public AreaBaseService getAreaBaseService() {
		return areaBaseService;
	}
	public void setAreaBaseService(AreaBaseService areaBaseService) {
		this.areaBaseService = areaBaseService;
	}
}


jsp里用jquery发送ajax请求:
       $.getJSON("findProvinceArea.action",null,function(msg){
				alert(msg);
       });