zoukankan      html  css  js  c++  java
  • 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"}
  • 相关阅读:
    set用法
    01分数规划
    unique && stl的全排列
    lower_bound() && upper_bound()
    spfa判负环
    倍增求LCA
    数据生成c++程序模板
    samba
    vsftp快速配置
    grub丢失的修复
  • 原文地址:https://www.cnblogs.com/yoyotl/p/9325976.html
Copyright © 2011-2022 走看看