一,需求如下
1.前端js封装map对象,通过ajax发起请求,后端通过springboot进行参数的处理
二,js前端数据结构,其中id为业务中的指标编号
var map = {};
var obj = {
leaderId : leaderId,
uuid : uuid,
quotaId:id,
scroe:parseInt(scroe)+1,
}
map[id] = obj;
ajax部分代码,关键部分为maoJson:map,
$.ajax({
type : "POST",
dataType : "json",
url : "/user/noNameSubmit",
data : {
gid: gid,
mapJson: map,
yearDetailId:yearDetailId,
},
async : false,
success : function(data) {
alert(data)
});
二,后台controller层代码,说明:quotaIdIndex = quotaIdIndex.substring(8, 13); 这一段获取quotaId指标编号 业务中指标编号为5位,与前端封装的quotaId对应
/**
* 获取领导成员评分明细
*
* @param fdusername
* @return
*/
@PostMapping("/user/noNameSubmit")
@Transactional
public @ResponseBody ResponseBase noNameSubmit(HttpServletRequest request,String gid,String yearDetailId) {
Enumeration<String> enuq = request.getParameterNames();
List<String> listQuotaId = new ArrayList<String>();
while (enuq.hasMoreElements()) {
String name = (String) enuq.nextElement();
// 获取quotaId 封装成 集合再遍历
if (name.contains("quotaId")) {
listQuotaId.add(name);
}
}
List<LeaderQuotaJson> listQuotaJsons = new ArrayList<LeaderQuotaJson>();
// 获取quotaId 封装成 集合再遍历
for (int i = 0; i < listQuotaId.size(); i++) {
String quotaIdIndex = listQuotaId.get(i);
quotaIdIndex = quotaIdIndex.substring(8, 13);
Integer leaderId = Integer.parseInt(request.getParameter("mapJson[" + quotaIdIndex + "][leaderId]"));
String uuid = request.getParameter("mapJson[" + quotaIdIndex + "][uuid]");
Integer quotaId = Integer.parseInt(request.getParameter("mapJson[" + quotaIdIndex + "][quotaId]"));
Integer scroe = Integer.parseInt(request.getParameter("mapJson[" + quotaIdIndex + "][scroe]"));
LeaderQuotaJson leaderQuotaJson = new LeaderQuotaJson(leaderId, uuid, quotaId, scroe);
listQuotaJsons.add(leaderQuotaJson);
}
//循环调用插入方法
for (LeaderQuotaJson leaderQuotaJson : listQuotaJsons) {
iSysIndexService.saveQuotaComment(leaderQuotaJson.getLeaderId(), leaderQuotaJson.getUuid(), "",
leaderQuotaJson.getQuotaId(), leaderQuotaJson.getScroe(),yearDetailId);
}
return setResultSuccess("提交成功");
}
三,原理说明
代码中业务代码较多,这里简单说明一下实现的原理,前端,实际上使用的数组,var map={} 数据结构的存储效果类似于java中的map集合,同一key后插入的数据会替换之前的数据;
后端也在网上找了很多框架接收map集合的方法,都未实现成功,决定用最原始的request中获取对象,进行分析和重新封装,并与业务进行结合,第一步获取map中的所有key值
Enumeration<String> enuq = request.getParameterNames();
List<String> listQuotaId = new ArrayList<String>();
while (enuq.hasMoreElements()) {
String name = (String) enuq.nextElement();
// 获取quotaId 封装成 集合再遍历
if (name.contains("quotaId")) {
listQuotaId.add(name);
}
}
第二步,从request.getParameter("mapJson[" + quotaIdIndex + "][leaderId]")获取对应参数的值即可,其中mapJson为js中传入参数的参数名称