目前我的项目中用到过的:------提交数组------------------------
前端如下:
$.post(
url,
{
forward_or_reverse: forward_or_reverse,
report_type: report_type,
billingaddresses: billingaddresses,
snos: snos,
search_start_time: search_start_time,
search_end_time: search_end_time,
remark: remark
},
function(data){
if ('SUCC' == data.result) {
msgAlert('提示', '已成功生成报告,请在BRAM/GBPP报告列表中查看!', 'success')
setTimeout(function () {
$(obj).attr("disabled", false);
$("#toCreatReport").modal('hide');
}, 200);
} else {
msgAlert('提示', data.result, 'error');
}
}
);
后端如下:
@RequestMapping(value = "/creatReport", method=RequestMethod.POST)
@ResponseBody
public synchronized Map<String, String> creatReport(BramGbppReport bramGbppReport, HttpSession session) {
Map<String, String> result = new HashMap<>();
result.put("result", "SUCC");
try {
Employee employee = (Employee)session.getAttribute(Constants.EMPLOYEE_INFO_SESSION);
String operator = employee.getUserName();
bramGbppReport.setCreator(operator);
log.info("creatReport操作,operator:{},bramGbppReport:{}",operator,bramGbppReport);
// bramGbppReportService.creatReport(bramGbppReport);
} catch (Exception e) {
result.put("result", "FAIL");
log.error("添加数据异常!");
log.error(StringUtil.getExceptionDetail(e));
}
return result;
}
实体类如下:
@Data
public class BramGbppReport {
private Long id;
/**
* 报告编号
*/
private String reportno;
/**
* 类型:BRAM类型为1,GBPP类型为2
*/
private String report_type;
/**
* 包含编码:BRAM_GBPP表中的sno字段的集合如(A001,A002)
*/
private String snos;
private String[] snosArr;
/**
* 包含编码:BRAM_GBPP表中的billingaddress字段的集合如(a01.com,a02.com)
*/
private String[] billingaddresses;
/***
* 查询时间段(开始)
*/
private String search_start_time;
/***
* 查询时间段(结束)
*/
private String search_end_time;
/** 创建人 */
private String creator;
/** 创建时间 */
@DateTimeFormat(pattern="yyyy/MM/dd")
private Date createTime;
/***
* 生成时间(开始)
*/
private String create_start_time;
/***
* 生成时间(结束)
*/
private String create_end_time;
/***
* 1:正向时间 2:反向时间
*/
private String forward_or_reverse;
}
目前我的项目中用到过的:-------------------------------
前端如下:
function saveChargebackFineSetting() {
var json={
"id":2,
"customerId":2,
"merNo":"200051,200052",
"fineMoneytype":2,
"creditCardId":"3,4",
"computeMode":2,
"cbFineSettingAndDetails":[
{
"id":null,
"cbfineSettingId":2,
"startTime":"2022-08-01",
"endTime":"2022-08-03",
"chargebackFineSettingDetailForPages":[
{
"startCbRate":0.01,
"endCbRate":0.03,
"amount":10
},
{
"startCbRate":0.03,
"endCbRate":0.05,
"amount":20
},
{
"startCbRate":0.05,
"endCbRate":0.08,
"amount":30
}
]
},
{
"id":null,
"cbfineSettingId":2,
"startTime":"2022-08-04",
"endTime":"2022-08-05",
"chargebackFineSettingDetailForPages":[
{
"startCbRate":0.02,
"endCbRate":0.04,
"amount":100
},
{
"startCbRate":0.04,
"endCbRate":0.06,
"amount":200
}
]
},
{
"id":null,
"cbfineSettingId":2,
"startTime":"2022-08-10",
"endTime":"2022-08-15",
"chargebackFineSettingDetailForPages":[
{
"startCbRate":0.02,
"endCbRate":0.04,
"amount":100
}
]
}
],
"settingDetailSumNum":6,
"remark":"test",
"creator":"admin",
"createTime":1659931470000,
"lastOperator":"1",
"lastOperationTime":1659931473000
};
alert("json");
var url = "${ctx}/chargebackFineSetting/saveChargebackFineSetting";
$.ajax({
url : url,
async : false,
type : "POST",
contentType : 'application/json',
dataType : 'json',
data :JSON.stringify(json),
success : function(data) {
alert("111");
}
});
}
----------并接的代码发下:
var cbFineSettingAndDetails = [];
$("#content_id .settings").each(function(i){
var id="content_id_rate_"+i+" .form-group";
var startTime=$(this).find("input[name='startTime']").val();
var endTime=$(this).find("input[name='endTime']").val();
var chargebackFineSettingDetailForPages = [];
$(this).find("#"+id).each(function(){
var startCbRate=$(this).find("input[name='startCbRate']").val();
var endCbRate=$(this).find("input[name='endCbRate']").val();
var amount=$(this).find("input[name='amount']").val();
chargebackFineSettingDetailForPages.push({"startCbRate":startCbRate,"endCbRate":endCbRate,"amount":amount});
});
cbFineSettingAndDetails.push({"startTime":startTime,"endTime":endTime,"chargebackFineSettingDetailForPages":chargebackFineSettingDetailForPages});
});
var json={
"customerId":customerId,
"merNo":merNos,
"fineMoneytype":fineMoneytype,
"creditCardId":creditCardIds,
"computeMode":computeMode,
"cbFineSettingAndDetails":cbFineSettingAndDetails
};
console.info(json);
var url = "${ctx}/chargebackFineSetting/saveChargebackFineSetting";
$.ajax({
url : url,
async : false,
type : "POST",
contentType : 'application/json',
dataType : 'json',
data :JSON.stringify(json),
success : function(data) {
if ('SUCC' == data.result) {
msgAlert('提示', '保存成功!', 'success');
setTimeout(function () {
$('#addChargebackFineSetting').modal('hide');
queryChargebackFineSettingList();
}, 1000);
} else {
msgAlert('提示', data.result, 'error');
}
}
});
后台如下:
@Data
public class ChargebackFineSetting {
/** 主键 */
private Long id;
/**
* 客户ID
*/
private Long customerId;
/** 商户号 */
private String merNo;
/** 罚款币种 */
private Long fineMoneytype;
/** 卡种id(1: Visa,2:Master,3:Jcb,4:AE,5:Diners,6:UnionPay,7:IntegrationPayment)*/
private String creditCardId;
/** 拒付率统计方式(1:分别计算,2:统一计算) */
private Integer computeMode;
List<CbFineSettingAndDetail> cbFineSettingAndDetails;
private Integer settingDetailSumNum;
/** 备注 */
private String remark;
/** 创建人 */
private String creator;
/** 创建时间 */
@DateTimeFormat(pattern="yyyy/MM/dd")
private Date createTime;
/** 最后操作人 */
private String lastOperator;
/** 最后操作时间 */
@DateTimeFormat(pattern="yyyy/MM/dd")
private Date lastOperationTime;
}
@Data
public class CbFineSettingAndDetail {
/** 主键 */
private Long id;
private Long cbfineSettingId;
/** 生效开始时间 */
// @DateTimeFormat(pattern="yyyy/MM/dd")
private String startTime;
/** 生效结束时间 */
// @DateTimeFormat(pattern="yyyy/MM/dd")
private String endTime;
List<ChargebackFineSettingDetailForPage> chargebackFineSettingDetailForPages;
}
@Data public class ChargebackFineSettingDetailForPage { /** 拒付率限制起始值(判断时不包含此值,即大于此值) */ private Double startCbRate; /** 拒付率结束值(判断时包含此值,即小于等于此值) */ private Double endCbRate; /** 阶段拒付罚金*/ private Double amount; }
------------------------------------------------
单个参数或者几个参数接收比较好处理,直接使用@RequestParam注解即可,或者不用注解都可以接收。而复杂的json格式就稍微有点麻烦,有时注解用的不对,会花费大量时间去试验。
例如要传递的json格式如下所示:
{
"list": [
{
"reportId": 1,
"reportName": "报告1",
"completeDate": "2019-07-24 23:12:39"
},
{
"reportId": 2,
"reportName": "报告2",
"completeDate": "2019-07-25 23:12:39"
}
],
"id": "2"
}
java 后台要接收类似复杂的json格式字符串,有两种思路可供参考
第一种:在后台定义两个实体类
第二种:直接用map接收,再转换
一、第一种方式
先创建两个类,一个Report实体。一个接收类,里面属性包含list
public class Report{
private Integer reportId;
private String reportName;
private Date completeDate;
...
}
public class RequestParam{
private String id;
private List<Report> list;
...
}
controller层直接用注解@RequestBody接收即可
@RequestMapping(value = "/report/list")
@ResponseBody
public Object reportList(@RequestBody RequestParam param) {
...
}二、第二种方式
定义一个实体
public class Report{
private Integer reportId;
private String reportName;
private Date completeDate;
...
}
先用map接收,再利用fastjson转化json字符串为对象。因为list中包含着对象,所以需要先将json字符串转化为List,再遍历List将其每一个都转化为Report对象。
@RequestMapping(value = "/report/list")
@ResponseBody
public Object reportList(@RequestBody Map<String,Object> map) {
// 直接拿到外层id
String id= map.get("id").toString();
// 利用fastjson将json串转化为对象
List list = JSONObject.parseObject(map.get("list").toString(),List.class);
List<Report> reportList = new ArrayList<>();
for (int i = 0; i < list.size(); i++){
reportList.add(JSONObject.parseObject(list.get(i).toString(),Report.class));
}
...
}
Tips:在前端ajax传递时记得contentType属性设置为:"application/json"
第三种:目前我的项目中用到过的
var url = "${ctx}/billAutoSwitchLibrary/addBillAutoSwitchLibrary";
$.post(
url,
{
libraryName: libraryName,
cardType: cardType,
reusing: reusing,
channelIds: channelIds
},
resetEmp
);
@RequestMapping(value = "/addBillAutoSwitchLibrary", method = RequestMethod.POST)
@ResponseBody
public synchronized Map<String, String> addBillAutoSwitchLibrary(BillAutoSwitchLibrary billAutoSwitchLibrary,@RequestParam(value = "channelIds[]",required = false)String[] channelIds, HttpSession session) {
Map<String, String> result = new HashMap<>();
result.put("result", "SUCC");
System.out.println(channelIds);
try {
} catch (Exception e) {
}
return result;
}
-----------页面提交json数组,mvc用List接收----------------
页面:
function conditionSave(){
var fightLaunderings = [];
$('#conditionDiv input[type="checkbox"]').each(function() {
var status = $(this).is(':checked')==true?1:2;
var id=$(this).attr("id");
var num=$(this).parent().next().val();
fightLaunderings.push({"id":id,"num":num,"status":status})
});
var url = "${ctx}/fightLaundering/updateFightLaundering";
$.ajax({
url : url,
async : false,
type : "POST",
contentType : 'application/json',
dataType : 'json',
data :JSON.stringify(fightLaunderings),
success : function(data) {
if ('SUCC' == data.result) {
msgAlert('提示', '保存成功!', 'success');
setTimeout(function () {
$('#addChargebackFineSetting').modal('hide');
queryChargebackFineSettingList();
}, 1000);
} else {
msgAlert('提示', data.result, 'error');
}
}
});
}
服务器端:
@RequestMapping(value = "/updateFightLaundering", method=RequestMethod.POST)
@ResponseBody
public Map<String, String> updateFightLaundering(@RequestBody List<FightLaundering> fightLaunderings, HttpSession session,HttpServletRequest request) {
System.out.println("fightLaunderings:"+fightLaunderings);
}
@Data
public class FightLaundering {
/** 主键 */
private Long id;
/** 数量*/
private Integer num;
/** 状态:1生效 2失效*/
private Integer status;
}