SpringMvc Json接收和返回的处理

一、第一种处理方式

1、Controller 控制层

@RequestMapping(value = "/getXkzbhAndEntname",produces = "text/json;charset=UTF-8")
 @ResponseBody
 public String getXkzbhAndEntname(HttpServletRequest request, HttpServletResponse response, String xkzbh,String entname) throws Exception{
  JSONObject jObject = new JSONObject();
  PageData pd=new PageData();
  try {
   pd = qyjcxxService.getEntityByXkzbhAndEntname(xkzbh,entname);
   if (pd!=null) {
    //json格式
    jObject.put("flag", "true");
    jObject.put("msg", "");
    
    jObject.put("fddbr", pd.getString("fddbrfzr"));//法定代表人 fddbrfzr
    jObject.put("fzr", pd.getString("lxr"));//fzr 负责人  lxr
    jObject.put("lxdh", pd.getString("lxr_sjhm"));//lxdh 联系电话 lxr_sjhm
    jObject.put("xxdz", pd.getString("scjy_dz"));//xxdz 市场地址 scjy_dz
    jObject.put("qyjj", pd.getString("scfw"));//qyjj 简介  scfw
    
    jObject.put("ssjgjname", pd.getString("rcjdgljg_mc"));// 监管局名称 rcjdgljg_mc
    jObject.put("ssjgj", pd.getString("rcjdgljg_dm"));//ssjgj 监管局代码 rcjdgljg_dm
    
   } else {
    //json空格式
    jObject.put("flag", "flase");
    jObject.put("msg", "企业库不含有该企业信息,无法补全!");
    
    jObject.put("fddbr", "");//法定代表人 fddbrfzr
    jObject.put("fzr", "");//fzr 负责人  lxr
    jObject.put("lxdh", "");//lxdh 联系电话 lxr_sjhm
    jObject.put("xxdz", "");//xxdz 市场地址 scjy_dz
    jObject.put("qyjj", "");//qyjj 简介  scfw
    
    jObject.put("ssjgjname", "");// 监管局名称 rcjdgljg_mc
    jObject.put("ssjgj", "");//ssjgj 监管局代码 rcjdgljg_dm
    
   }
  } 
  catch (Exception e) 
  {
   e.printStackTrace();
   
   jObject.put("flag", "flase");
   jObject.put("msg", "获取企业库信息失败");
   
   jObject.put("fddbr", "");//法定代表人 fddbrfzr
   jObject.put("fzr", "");//fzr 负责人  lxr
   jObject.put("lxdh", "");//lxdh 联系电话 lxr_sjhm
   jObject.put("xxdz", "");//xxdz 市场地址 scjy_dz
   jObject.put("qyjj", "");//qyjj 简介  scfw
   
   jObject.put("ssjgjname", "");// 监管局名称 rcjdgljg_mc
   jObject.put("ssjgj", "");//ssjgj 监管局代码 rcjdgljg_dm
   
  }
  return jObject.toString();
 }

 

2、js处理

//获取企业库是否有数据
$("#btnGetData").click(function () {
 var ztbh = $("#txtZtbh").val();
 var ztmc = $("#txtZtmc").val();
 //取mySql的企业库数据
 $.ajax({
  url: "<%=basePath %>login/getXkzbhAndEntname.do",
  type: "POST",
  async: false,
  data: {
      xkzbh : ztbh,
      entname : ztmc
  },
  dataType: "text",
  contentType : "application/x-www-form-urlencoded; charset=utf-8",
  success: function (data) {
  var dataObj = JSON.parse(data);//转成json格式
  //alert(data);
  //alert(dataObj);
   if(dataObj.flag)
      {
    alert(dataObj.msg);
       if(dataObj.fddbr!=null)
       {
           $("#txtfddbr").val(dataObj.fddbr);
       }      
      }
   else
    {
     alert(dataObj.msg);        
    }
  },
  error: function (data) {
   alert('许可证号验证异常!');
  }
 });
});

 

 

返回值json格式:

 

二、第二种处理方式

判断记录是否存在的json处理

1、controller

@RequestMapping(value = "/existsZtmcUpdate")
    @ResponseBody
    public String existsZtmcUpdate(HttpServletRequest request, HttpServletResponse response, String ztmc,String ztid)throws Exception {

        Boolean existsResult = false;
        try {
            existsResult = 验证代码;

        } catch (Exception e) {
            e.printStackTrace();

        }
        if (existsResult) {
            return "1";
        } else {
            return "0";
        }
    }

 

 

2、js

//验证市场机构名称
     $("#txtZtbh").blur(function(){
       return verifyZtbh();
     });
     
     function verifyZtbh(){
      
      var ztbh = $("#txtZtbh").val();
      var flag = false;
      
      if(ztbh == ''){
       $("#msgZtbh").text('许可证号不能为空!');
       return false;
      }
      
      $.ajax({
             url: "<%=basePath %>login/existsZtbh.do",
             type: "POST",
             async: false,
             data: {
              ztbh : ztbh
             },
             dataType: "text",
          contentType : "application/x-www-form-urlencoded; charset=utf-8",
             success: function (data) {
              var json = eval(data);
              if(json == 1){
               $("#msgZtbh").text('许可证号已被注册!');
              }else{
               $("#msgZtbh").text('');
               flag = true;
              }
              
             },
             error: function (data) {
              $("#msgZtbh").text('许可证号验证异常!');
             }
         });
      if(flag){
       $("#msgZtbh").text('');
       return true;
      }else{
       return false;
      }
     }

 

 

三、第三种处理方式,数组方式批量上报数据

1、controller

 

@RequestMapping(value = "/receivedata", method = RequestMethod.POST)
    @ResponseBody
    public ReturnJsonInfo receivedata(HttpServletRequest request,HttpServletResponse response,@RequestBody Fasttestinfo fasttestinfo) {
        ReturnJsonInfo returninfo=new ReturnJsonInfo();
        try {
             String username=fasttestinfo.getUsername();
            String password=fasttestinfo.getPassword();
            String areacode="";
            String areaname="";
            String ssjgjcode="";
            String ssjgjname="";
            
            Boolean ischeck=false;
            //验证username和密码if(ischeck)
            {
                //查看有几组数据
                //System.out.println(fasttestinfo.getItems().length);
                //组织数据进行数据写入
                //System.out.println(fasttestinfo.getItems()[0].getSamplenum() + " " + fasttestinfo.getUsername());
                
                if(fasttestinfo.getItems().length>0)
                {
                    //将数据处理到List中
                    List<FasttestinfoInfo> fasttestinfoList = new ArrayList<FasttestinfoInfo>();
                    int errorItem=0;
                    
                    // 包装对象
                    for (int i = 0; i < fasttestinfo.getItems().length; i++) {
                        FasttestinfoInfo fasttestinfoInfo = new FasttestinfoInfo();
                        String id = UuidUtil.get32UUID();
                        fasttestinfoInfo.setId(id);
                        fasttestinfoInfo.setUserName(username);
                        
                        fasttestinfoInfo.setQueryId(fasttestinfo.getItems()[i].getQuery_id());
                        fasttestinfoInfo.setGallery(fasttestinfo.getItems()[i].getGallery());
                        fasttestinfoInfo.setSamplenum(fasttestinfo.getItems()[i].getSamplenum());
                        fasttestinfoInfo.setSamplename(fasttestinfo.getItems()[i].getSamplename());
                        
                        fasttestinfoInfo.setCov(fasttestinfo.getItems()[i].getCov());
                        fasttestinfoInfo.setSymbol(fasttestinfo.getItems()[i].getSymbol());
                        
                        fasttestinfoInfo.setCovUnit(fasttestinfo.getItems()[i].getCov_unit());
                        fasttestinfoInfo.setStandNum(fasttestinfo.getItems()[i].getStand_num());
                        

                        fasttestinfoInfo.setCreateTime(DateUtil.getCurrentTime());
                        fasttestinfoInfo.setPosttype(1);

                        fasttestinfoList.add(fasttestinfoInfo);
                    }
                    
//                    if(errorItem>0)
//                    {
//                        returninfo.setFlag("false");
//                        returninfo.setMsg("json中items第"+errorItem+"项不是时间格式");
//                        return returninfo;
//                    }
                    //插入数据库
                    if(fasttestinfoService.addBatch(fasttestinfoList))
                    {
                        returninfo.setFlag("true");
                        returninfo.setMsg("数据接收成功!");
                    }
                    else
                    {
                        returninfo.setFlag("false");
                        returninfo.setMsg("上报数据接收失败");
                    }
                    
                }
                else
                {
                    returninfo.setFlag("false");
                    returninfo.setMsg("json中items数组为空");
                }
            }
            else
            {
                //企业不存在,或企业用户名和密码有误
                returninfo.setFlag("false");
                returninfo.setMsg("企业不存在或企业用户名和密码有误!");
            }
            
        } catch (Exception e) {
            returninfo.setFlag("false");
            returninfo.setMsg(e.toString());
        }
        return returninfo;
        
    }

 ReturnJsonInfo类

/**
 * 返回json格式 实体类
 * 2017-11-19 22:04:45
 */ 
public class ReturnJsonInfo{
    
    private String flag;

    private String msg;
    
    /**
     * 重写toString方法
     */ 
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }
    
    public void setMsg(String msg){
        this.msg = msg;
    }

    public String getMsg(){
        return msg;
    }

}

 

2、js处理

$.ajax({
                url:'http://localhost:8080/interface/receivedata.do',
            
                type:'POST',
                dataType:'json',
                contentType:'application/json;charset=UTF-8',
                data:JSON.stringify({
                    username:'aaa',
                    password:'123456',
                    items:[{
                            query_id:'检测记录id2',
                            gallery:'通道id断模块的依据2',
                            samplenum:'样品编号2',
                            samplename:'样品名称2',
                            cov:'判定值sy2',
                            symbol:'判定符号2',
                            cov_unit:'检测单位2',
                            stand_num:'判定标准号2',
                            prosecutedunits:'被检单位2'

                            }
                        ]
                }),
                success : function(result) {
                    alert(JSON.stringify(result));
                },
                error:function(XMLHttpRequest, textStatus, errorThrown) 
                {
                    alert(XMLHttpRequest);
                    alert(textStatus);
                    alert(errorThrown);
                }
            });

 

posted on 2017-12-20 09:53  wuzx-blog  阅读(2939)  评论(0编辑  收藏  举报