美文网首页
[Struts2]17-使用Struts2的JSON插件来实现J

[Struts2]17-使用Struts2的JSON插件来实现J

作者: 我相信你爱过gg | 来源:发表于2017-05-07 20:45 被阅读166次

想要实现此功能第一步需要Struts2的核心架包,第二步需要struts2-json-plugin-2.3.30架包,在lib文件夹下可以找到。

还是借用上次的笔记来继续写,这个时候我们就不需要用到Servlet了,要使用到Action。

配置xml

<!-- (1)定义package,并继承json-default -->  
<package name="json" namespace="/" extends="json-default">  
  
    <action name="*ShowAction" class="action.ShowAction" method="{1}">  
        <!-- (2)result的type类型为“json”,将返回序列化的json格式数据 -->  
        <result name="success" type="json">  
            <!-- (3)指定需要格式化的跟对象 -->  
            <param name="root">result</param>  
        </result>  
    </action>  
</package>  

Action中的写法

public class ShowAction extends ActionSupport {  
  
    //要将返回的JSON数据放到值栈范围,这里不需要我们手动转换struts2的json插件会为我们转换  
    Map<String, Object> result = new HashMap<String, Object>(0);  
  
    public String show(){  
  
        Users users = new Users("张三", "q123");  
  
        //将Users对象转换为JSONObject  
        JSONObject jsonObject = JSONObject.fromObject(users);  
  
        //使用JSONObject的toString()方法将JSONObject转换成字符串  
        System.out.println( "users:" + jsonObject.toString() );  
  
        List<String> listStr = new ArrayList<String>(0);  
        listStr.add("小明");  
        listStr.add("小红");  
        JSONArray jsonListStr = JSONArray.fromObject(listStr);  
  
        List<Users> listUsers = new ArrayList<Users>(0);  
        listUsers.add(new Users("大名", "123"));  
        listUsers.add(new Users("大红", "456"));  
        JSONArray jsonListUsers = JSONArray.fromObject(listUsers);  
  
        Map<String, String> mapStr = new HashMap<String, String>(0);  
        mapStr.put("彩虹", "彩彩");  
        mapStr.put("豆豆", "小豆");  
        JSONObject jsonMapStr = JSONObject.fromObject(mapStr);  
  
        Map<String, Users> mapUser = new HashMap<String, Users>(0);  
        mapUser.put("1", new Users("小彩虹", "123"));  
        mapUser.put("2", new Users("小豆豆", "123"));  
        JSONObject jsonMapUser = JSONObject.fromObject(mapUser);  
  
        result.put("jsonListStr", jsonListStr);  
        result.put("jsonListUsers", jsonListUsers);  
        result.put("jsonMapStr", jsonMapStr);  
        result.put("jsonMapUser", jsonMapUser);  
        result.put("users", jsonObject);  
  
        return Action.SUCCESS;  
    }  
  
  
    public Map<String, Object> getResult() {  
        return result;  
    }  
  
    public void setResult(Map<String, Object> result) {  
        this.result = result;  
    }  
  
}  

前台的jsp页面就需要访问action了

<script>  
  
  $(function () {  
    $.ajax({  
      type:"POST",  
      dataType:"JSON",  
      url:"/showShowAction",  
      success:function(data){  
  
      }  
    });  
  });  

相关文章

网友评论

      本文标题:[Struts2]17-使用Struts2的JSON插件来实现J

      本文链接:https://www.haomeiwen.com/subject/knlptxtx.html