Struts2 ---- 返回 json 数据

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


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值