Struts2 use Json

来源:互联网 发布:始作俑者,其无后乎 编辑:程序博客网 时间:2024/06/15 12:36
 Struts2返回json需要jsonplugin-0[1].25的包

然后我们的配置文件中需要继承json-default
struts.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>   
  2. <!DOCTYPE struts PUBLIC   
  3.         "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.         "http://struts.apache.org/dtds/struts-2.0.dtd">   
  5.   
  6. <struts>   
  7.   
  8.     <package name="com.action.testJson" extends="json-default" namespace="/" >   
  9.         <action name="jsonUser" class="com.action.testJson.JsonAction" method="testUser">   
  10.             <result type="json"/>   
  11.         </action>   
  12.         <!-- Add actions here -->   
  13.     </package>   
  14. </struts>  


然后我们的Action中需要返回的json信息需要加上注解
Java代码  
  1. //pizza  
  2. package com.action.testJson;   
  3.   
  4. import java.util.ArrayList;   
  5. import java.util.List;   
  6.   
  7. import com.googlecode.jsonplugin.annotations.JSON;   
  8. import com.opensymphony.xwork2.ActionSupport;   
  9.   
  10. public class JsonAction extends ActionSupport {   
  11.   
  12.     private static final long serialVersionUID = -4082165361641669835L;   
  13.        
  14.     Users user=new Users();   
  15.     List userList=new ArrayList();   
  16.        
  17.        
  18.     public String testUser(){   
  19.         System.out.println("in the json Acton");   
  20.         userInit();   
  21.         userList.add(user);   
  22.         return SUCCESS;   
  23.     }   
  24.            
  25.     public void userInit(){   
  26.         user.setAge(1);   
  27.         user.setName("张泽峰");   
  28.         user.setPassword("nofengPassword");   
  29.     }   
  30.        
  31.     @JSON(name="userString")   
  32.     public Users getUser() {   
  33.         return user;   
  34.     }   
  35.   
  36.     @JSON(name="userList")   
  37.     public List getUserList() {   
  38.         return userList;   
  39.     }   
  40.        
  41.     public void setUser(Users user) {   
  42.         this.user = user;   
  43.     }   
  44.   
  45.     public void setUserList(List userList) {   
  46.         this.userList = userList;   
  47.     }   
  48.        
  49.   
  50. }  
原创粉丝点击