Struts2 ---- 返回 json 数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38637558/article/details/79960987

还是好久以前写的,整理一下,简洁明了的给大家展示一波


这边需要注意的就是 :
类上面的注释:@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”} ,那么我们定义的两个属性就都返回了
这里写图片描述

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页