JAVA实现JSON后端向前端传递数据
1 后端两个辅助类
ConcurrentDateUtil.Java,用于生成我们需要格式的时间
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ConcurrentDateUtil { private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); } }; public static Date parse(String dateStr) throws ParseException { return threadLocal.get().parse(dateStr); } public static String format(Date date) { return threadLocal.get().format(date); } }
JsonResult.java,JsonResult封装,用于后端向前端传递数据
import com.sf.utils.ConcurrentDateUtil; import java.util.Date; public class JsonResult<T> { public static int NEED_RE_LOGIN = 1; public static int NEED_RETRY = 2; private int errCode; private String message; private String timestamp = ConcurrentDateUtil.format(new Date()); private T data; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getTimestamp() { return timestamp; } public T getData() { return data; } public void setData(T data) { this.data = data; } public int getErrCode() { return errCode; } public void setErrCode(int errCode) { this.errCode = errCode; } }
上面这两个类完成之后,我们就可以在web层的controller中使用JsonResult封装数据并传递到前端。
接下来介绍两种情况,看看前端怎么取数据出来
2 前端JS怎么取出数据
如果后端传给前端的JsonResult封装的是一个Map,例如
@ResponseBody @RequestMapping(value = "/user/getUserAmount", method = RequestMethod.POST) public JsonResult<Map<String, Integer>> getUserAmount() { JsonResult<Map<String, Integer>> result = new JsonResult<>(); try { //已签到人数 Integer signedAmount = userService.getSignedAmount(); //总人数 Integer totalUserAmount = userService.getTotalUserAmount(); Map<String, Integer> amountMap = new HashMap<>(); amountMap.put("signed", signedAmount); amountMap.put("sum", totalUserAmount); result.setData(amountMap); //这里举个例子,如果觉得setData穿的信息不够,还可以用setMessage方法多传一个字符串过去 result.setMessage("这是签到界面"); } catch (Exception e) { log.warn(ExceptionUtils.getStackTrace(e)); } return result; }
现在想在前端JS把已签到人数和总人数两个数据取出来,要怎么做呢?只需要在”.”后面跟着Map的Key就好了,如下所示:
function getSignedAmount(){ $.ajax({ type: "post", url : getContextPath() + "/user/getUserAmount", dataType:'json', data: { }, success: function(data){ var amount = data.data; //取出总人数 var totalAmount = amount.sum; //总人数减去已经签到的人数,就是未签到的人 var unsignedNumber = amount.sum-amount.signed; //取出后端controller中setMessage方法传过来的字符串 var logMessage = data.message; } }); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)