概要
我们上一篇文章已经将LigerUI表格的页面效果以及前端如何加载Json进行了介绍,下面我们来看下后台是如何处理得到Json的。
过程
URL跳转到action
上一篇文章中,我们通过url“statisticalQuery_list.action”跳转到这个StatisticalQueryAction类的list方法,从前台url如何跳转到这个action类的list方法,这是我们在struts.xml文件中配置的,如下:
<pre name="code" class="html"><!--统计查询 -->
<action name="statisticalQuery_*" class="statisticalQueryAction"
method="{1}">
<result name="tolist">/admin/jsp/StatisticalQuery/StatisticalQuery1.jsp
</result>
<result name="forupdatelist">/admin/jsp/StatisticalQuery/StatisticalQuery.jsp
</result>
<result name="toDetail">/admin/jsp/StatisticalQuery/detailInfo.jsp
</result>
<interceptor-ref name="checkAdminPrivilege" />
<interceptor-ref name="defaultStack" />
</action>
StatisticalQueryAction类
下面我们先来看下这个类的用到的方法:
//前台查询的条件
private String keyWord;
public String getKeyWord() {
return keyWord;
}
public void setKeyWord(String keyWord) {
this.keyWord = keyWord;
}
/**
*
* @MethodName : list
* @Description : 取到所有数据,让表格显示
* @return
* @throws Exception
*/
public String list() throws Exception {
try {
String page = ServletActionContext.getRequest().getParameter("page");
String pagesize = ServletActionContext.getRequest().getParameter("pagesize");
String strWhere="";
int statNum = (Integer.parseInt(page) - 1) * Integer.parseInt(pagesize)+1;
int endNum=Integer.parseInt(page)*Integer.parseInt(pagesize);
if (StringUtils.isNotBlank(keyWord)) {
strWhere = java.net.URLDecoder.decode(keyWord, "UTF-8");
}
System.out.println(strWhere);
//从视图中取到的数据,需要转换一下
//查询记录数
List<StatisticalQueryView> statisticalQueryViewsCount =statisticalQueryService.findAllBypage(strWhere);
//分页查询数据
List<StatisticalQueryView> statisticalQueryViews =statisticalQueryService.findAllBypage(statNum,endNum,strWhere);
//将视图集合转化成普通list集合然后转json
List<StatisticalQuery> statisticalQueries=viewNormal(statisticalQueryViews);
//将后台出来的实体集合转化为前台表格可以接收的特殊形式的json
String resultJson=JsonUtils.toJsonGirdN(statisticalQueries,statisticalQueryViewsCount);
System.out.println("resultJson"+resultJson);
outJson(ServletActionContext.getResponse(), resultJson);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @MethodName : viewNormal
* @Description : 将视图集合转化成普通list集
* @param statisticalQueryViews
* @return
*/
public List<StatisticalQuery> viewNormal(List<StatisticalQueryView> statisticalQueryViews){
//将视图list集合转化成普通集合
List<StatisticalQuery> statisticalQueries=new ArrayList<StatisticalQuery>();
StatisticalQuery statisticalQuery=null;
try {
for (int i = 0; i < statisticalQueryViews.size(); i++) {
statisticalQuery=new StatisticalQuery();
statisticalQuery=statisticalQueryViews.get(i).getStatisticalQuery();
statisticalQueries.add(statisticalQuery);
}
} catch (Exception e) {
e.printStackTrace();
}
return statisticalQueries;
}
/**
*
* @Title: outJson
* @Description: 输出结果到前台
* @param @param response
* @param @param result 设定文件
* @return void 返回类型
* @throws
*/
private void outPrint(HttpServletResponse response, String data) {
String encoding = "UTF-8";
String contentType = "application/json;charset=UTF-8";
response.setContentType(contentType);
response.setCharacterEncoding(encoding);
try {
PrintWriter out = response.getWriter();
out.print(data);
out.flush();
out.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
我们先解释上面的这三个方法,首先第一个“list“方法是通过“keyWord”属性的依赖注入得到前台传过来的条件,然后通过条件查询得到一个视图的list集合,因为前台其它特殊需求,所以用到了第二个方法“viewNormal”将视图list集合转化我们想要的集合;第三个方法是将Json数据传输到前台。
下面我们就重点来介绍下我们是如何将实体集合转为前台可接收的Json的,我们是调用JsonUtils类的toJsonGirdN方法来转化的。在这里我们用到了Gson,Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。
下面看下我们的这个类:
package cn.bjjczb.ybyy.util;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.omg.CORBA.PRIVATE_MEMBER;
import cn.bjjczb.ybyy.domain.Role;
import com.google.gson.Gson;
import com.google.gson.JsonNull;
import com.google.gson.reflect.TypeToken;
public class JsonUtils {
private static Gson gson = new Gson();
private JsonUtils(){
}
/**
*
* @MethodName : toJsonGird
* @Description : 将集合转化为ligerUI前台需求的表格形式的json串,zh新添加
* @param list
* @return
*/
@SuppressWarnings("unchecked")
public static String toJsonGirdN(List list,List list2){
String result = null;
try {
//将集合放到map中转化为json,仍然不是我们想要的,不过已经很接近了
Map listMap = new HashMap();
listMap.put("Rows", list);
String json=gson.toJson(listMap) ;
//System.out.println(json);
//结果为:{"Rows":[{"a":"测试1","b":"纯测试1"},{"a":"测试2","b":"纯测试2"},{"a":"测试3","b":"纯测试3"},{"a":"测试3","b":"纯测试3"}]}
String total= String.valueOf(list2.size());
String totalReplace="{\"Total\":"+total+",\"Rows\"";
result=json.replace("{\"Rows\"", totalReplace);
//System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}finally{
return result;
}
}
}
在上面的这个类中,我们首先将我们要转化为json的list实体集合放到map中,然后利用gson类的toJson方法将map转为Json,然后将Json进一步转化即可得到我们前台表格需要加载的Json数据。
拓展
下面我们将常用到的对象转化为Json和Json转为对象的方法一并给大家。
/**
*
* @MethodName : toJson
* @Description : 将对象转换为JSON串,
* 此方法能够满足大部分需求
* @param src:将要被转化的对象
* @return:
*/
public static String toJson(Object src) {
if (src == null) {
return gson.toJson(JsonNull.INSTANCE);
}
return gson.toJson(src);
}
/**
*
* @MethodName : fromJson1
* @Description : 用来将JSON串转换为对象,
* 此方法不可用来转带泛型的List
* @param <T>
* @param json
* @param classOfT
* @return
*/
public static<T> Object fromJson1(String json,Class<T> classOfT){
return gson.fromJson(json, (Type) classOfT);
}
/**
* 测试将json串转换为对象,转泛型不可用
* @MethodName : test
* @Description : 此方法为我做的测试Role为实体
*/
public void test(){
Role role = new Role();
String json="";
JsonUtils.fromJson1(json, role.getClass());
}
/**
*
* @MethodName : fromJson2
* @Description : 此方法用来将JSON串转化为对象,此方法可以用来转带泛型的List
* Type为new TypeToken<List<T>>()
* {}.getType(),其它类也可以用此方法调用,
* 就是将List<T>替换为你想要转成的类
* @param json
* @param typeOfT
* @return
*/
public static Object fromJson2(String json, Type typeOfT) {
return gson.fromJson(json, typeOfT);
}
/**
* 测试将json转换为泛型对象
* @MethodName : test1
* @Description : 此方法为我做的测试Role为实体
*/
public void test1(){
Type roles =new TypeToken<List<Role>>()
{}.getType();
String json="";
JsonUtils.fromJson2(json,roles);
}
上面这几个方法是将对象转为Json已经Json转为对象,包括Json转普通对象和Json转泛型对象,其中test和test1方法是我做的测试,大家可以根据需要进行扩展。
最后
关于Json和对象之间的互相转化第三方类库还是很多的,gson只是其中的一种,不过他们也都大同小异,用熟了一个,其它的也就都一样了。