struts系列:返回json格式的响应

一、增加依赖库

// https://mvnrepository.com/artifact/org.apache.struts/struts2-json-plugin
compile group: 'org.apache.struts', name: 'struts2-json-plugin', version: '2.5.16'

二、struts.xml配置示例

  <package name="default-json" extends="json-default">
        <action name="hello" class="com.sanro.strutsDemo.action.HelloAction"
            method="execute">
            <result name="success">/pages/hello.jsp</result>
            <result name="errLogin" type="json">
                <!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 -->
                <param name="root">jsonData</param>
                <!-- 指定是否序列化空的属性 -->
                <param name="excludeNullProperties">true</param>
            </result>
        </action>
    </package>

三、action部分

    private String name;                   //GET请求参数
    private String password;               //GET请求参数
    private Map<String, String> jsonData;  //响应的数据结构(由strut-json插件自动转换成json格式)

    public String execute() {
        logger.debug("name=" + name);
        logger.debug("pwd=" + password);
        if ("lings".equals(name)) {
            return SUCCESS;
        } else {
            jsonData = new HashMap<String, String>();
            jsonData.put("user", name);
            jsonData.put("password", password);
            return "errLogin";
        }
    }
    
    //略去getter和setter方法

四、请求示例

http://localhost:8080/strutsDemo/hello?name=lings&password=123

五、响应示例

{"password":"123","user":"lings"}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值