码迷,mamicode.com
首页 > Web开发 > 详细

组合查询--表单对象转化为json对象

时间:2017-08-03 17:42:00      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:lan   get   string   转换   ext   action   hashmap   ati   .class   

//1.将page和rows封装到pageable中
  Pageable pageable = new PageRequest(page, rows);
  //2.创建组合条件查询条件对象
  Specification<FixedArea> spec = new Specification<FixedArea>() {

   @Override
   public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    //2.1创建存放已拼装条件的list集合
    ArrayList<Predicate> predicates = new ArrayList<Predicate>();
    
    //2.2进行组合查询条件的拼装
    String id = model.getId();
    if(StringUtils.isNotBlank(id)){
     
     predicates.add(cb.equal(root.get("id").as(String.class), id));
     
    }
    String company = model.getCompany();
    if(StringUtils.isNotBlank(company)){
     
     predicates.add(cb.like(root.get("company").as(String.class), "%"+company+"&"));
     
    }
    
    //2.3创建存放拼装条件的predicate数组
    Predicate[] predicateArr = new Predicate[predicates.size()];

    //2.4返回拼装好的条件
    return query.where(predicates.toArray(predicateArr)).getRestriction();
   }
  };
  
  //3.执行分页查询
  Page<FixedArea> page = fixedAreaService.pageQuery(spec,pageable);
  
  //4.去除会造成no session 的 FixedArea实体类中的"many"字段
  String[] excludes = { "subareas", "couriers" };
  
  //调用baseAction中的方法将查询到的结果转化成json发送到前台
  this.write2JsonObject(page, excludes);

-------------------------------------------------------------------------------------------------------------

baseAction中:

public void write2JsonObject(Page<?> page, String[] excludes) throws IOException {

  // 构建json对象型数据
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("total", page.getTotalElements());
  map.put("rows", page.getContent());

  // JsonConfig: 配置转换的json数据中不需要的属性
  JsonConfig jsonConfig = new JsonConfig();

  jsonConfig.setExcludes(excludes);

  // 将map转化为json
  String json = JSONObject.fromObject(map, jsonConfig).toString();
  ServletActionContext.getResponse().setContentType("test/json;charset=UTF-8");
  ServletActionContext.getResponse().getWriter().print(json);

 }

组合查询--表单对象转化为json对象

标签:lan   get   string   转换   ext   action   hashmap   ati   .class   

原文地址:http://www.cnblogs.com/xubing520/p/7280709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!