struts中如何用gson和AJAX与jsp页面交互

来源:互联网 发布:js search方法 编辑:程序博客网 时间:2024/05/22 01:32

下面给出一段代码示例:

Action中代码

1. 通过输出流的方式输出json

////设置相应的格式utf-8HttpServletResponse res= ServletActionContext.getResponse();           res.setContentType("text/html;charset=utf-8");           try {            PrintWriter  out = res.getWriter();            list = new PetServiceImpl().getALLById(id);            //Action中传输gson对象到jsp页面            Gson gson = new Gson();            String jsonString = gson.toJson(list);            out.print(jsonString);            return "showPet";        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }

2.通过插件方式获取gson
前提是要导入一个
struts2-json-plugin-2.5.5.jar文件

public String  getJsonToPlugin(){          list = new ArrayList<Person>();          Person p = new Person(1,"插件1", 20);          Person p1 = new Person(2,"插件2", 40);          Person p2 = new Person(3,"插件3", 26);          list.add(p);          list.add(p1);          list.add(p2);           person = new Person(4, "新人类",100000);          name = "新名字";         return SUCCESS;      }

jsp页面中ajax代码

//jsp中编写ajax代码var str="";            $.ajax({                 type:"post",                 url:"pet_showPet", //配置的action的名称                 dataType:"json",                 success:function(data){                     $.each(data,function(i){                         alert(data[i].pet_name);                         $("#pet_id").val(data[i].pet_id);                         $("#pet_name").val(data[i].pet_name);                         $("#pet_sex").html(data[i].pet_sex);                         $("#pet_type").html(data[i].pet_type);                         $("#pet_ownner").val(data[i].pet_ownner);                                 $.each(data[i].petDairySet,function(j){                                     str +="<tr><td>"+data[i].petDairySet[k].dairy_date                                          +"</td><td>"+data[i].petDairySet[k].dairy_title                                         +"</td><td>"+data[i].petDairySet[k].dairy_weather +"</td></tr>";                                 });                     });                     $("#showDiary").val(str);                 }              });
0 0
原创粉丝点击