struts2中json插件使用
1.struts2中怎样处理异步提交(ajax)
原始:
HttpServletResponse response = ServletActionContext.getResponse();
response.getWriter().write("hello " + msg);
response.getWriter().close();
还可以使用struts2中提供的json插件:
1.导入json插件包
在struts2的lib包下 struts2-json-plugin-2.3.15.1.jar。
2.在struts.xml文件中配置
1.<package extends="json-default">
2.设置视图<result type="json">
这样设置后,会将valueStack栈顶数据变成json。
对于我们的程序,也就是会将action对象转换成json。
struts.xml文件
<struts>
<package name="default" namespace="/" extends="json-default">
<action name="ajax1" class="cn.itcast.action.AjaxAction1">
<result type="json">
<param name="root">products</param> <!-- 不设置root的情况下是将action下所有的对象都转化为json。设置了就只转化设置的为json-->
</result>
</action>
</package>
</struts>
action文件
public class AjaxAction1 extends ActionSupport{
private List<Product> products;
private Product p;
public Product getP() {
return p;
}
public void setP(Product p) {
this.p = p;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
@Override
public String execute() throws Exception {
products = new ArrayList<Product>();
products.add(new Product(1, "洗衣机", "3200", 10));
products.add(new Product(2, "电视", "2344", 12));
products.add(new Product(3, "冰箱", "800", 18));
p = new Product(1, "电脑", "1222", 21);
System.out.println("this is ajaxAction1.......");
return SUCCESS;
}
}
jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function getXmlHttpRequest() {
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // 针对于现在的浏览器包括IE7以上版本
} else if (window.ActiveXObject) {
// 针对于IE5,IE6版本
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function showProduct() {
//1.得到XMLHttpRequest对象
var xmlhttp = getXmlHttpRequest();
//2.设置回调函数.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
alert(xmlhttp.responseText)
//var jsonObj=eval("("+xmlhttp.responseText+")");
}
};
//3.open
xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax1");
//4.send
xmlhttp.send(null);
}
</script>
</head>
<body>
<input type="button" value="提交" onclick="showProduct();">
</body>
</html>
<param name="root">p</param> 如果没有设置,可以理解成将整个action都转换成json的数据。也就是
在action中提供的getXxx方法,就是json中的一个属性。
如果设置了root,那么,只将指定数据转换成json.
--------------------------------------------------------
**怎样设置转换成json的对象中不包含特定的属性?
0.常规使用json转换时:
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{"customer"});//在转json时,去掉集合中order对象里的customer对象。
JSONArray jsonArray = JSONArray.fromObject(list,jsonConfig);
1. @JSON(serialize=false) 在getXxx方法上设置
2. 还可以通过json插件的interceptor完成.
<param name="includeProperties">ps\[\d+\]\.name,ps\[\d+\]\.price,ps\[\d+\]\.count</param>