还是好久以前写的,整理一下,简洁明了的给大家展示一波
这边需要注意的就是 :
类上面的注释:@ParentPackage(“json-default”)
方法上面的注释:@Result
package com.test.action;
import com.opensymphony.xwork2.ActionSupport;
import com.test.entity.Dept;
import com.test.entity.Emp;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
/**
* @author Ming
* @date 2017/11/16 12:46
*/
@ParentPackage("json-default")
@Namespace("/test")
public class test extends ActionSupport {
// Emp 和 Dept 只是两个实体类
private Emp emp;
// Dept 的定义只是为了测试test()方法的 params 标签 : ,params = { "root","emp"}
private Dept dept;
@Action(value = "test", results = {
@Result(name = "success", type = "json", params = {
// emp,不然我们定义的private的属性都会返回
"root","emp"
})
})
public String test() {
dept = new Dept();
dept.setDeptno(7934);
dept.setDname("sale");
emp = new Emp();
emp.setEmpno(7934);
emp.setEname("cat");
emp.setJob("clerk");
emp.setDeptByDeptno(dept);
return SUCCESS;
}
public Emp getEmp() {
return emp;
}
public void setEmp(Emp emp) {
this.emp = emp;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
}
<%--
Created by IntelliJ IDEA.
User: Ming
Date: 2017/11/16
Time: 12:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>Title</title>
<script src="js/jquery.min.js"></script>
</head>
<body>
</body>
<script>
$.get("test/test.action", {}, function (result) {
alert(result.ename);
alert(result.deptByDeptno.deptno);
}, "json")
</script>
</html>
这个就是我们返回的json数据,
如果不定义 , params = {“root”,”emp”} ,那么我们定义的两个属性就都返回了