@RequestParam和@RequestBody使用详解
目录
1、FormData提交数据的几种方式【该博客只针对POST提交】
2、Json字符串提交数据的几种方式(需要设置contentType)
2.1、原生ajax提交json格式数据,需要设置contentType
2.2、jquery的ajax提交Json串数据,需要设置contentType
@RequestParam:用于获取FormData类型提交的数据【该注解一般可省略】
@RequestBody:用于获取json字符串类型提交的数据
1、FormData提交数据的几种方式【该博客只针对POST提交】
前端通过FormData提交的数据,后端可以通过 request.getParameter获取到。
通过FormData提交数据的几种方法:
1.1、Form表单提交
js监听按钮,点击按钮提交表单
<form method="post" action="export" id="form1_excel" style="display: none;" target="iframe">
<input type="hidden" name="startDate" id="startDate" ></input>
<input type="hidden" name="dDate" id="dDate" ></input>
<input type="hidden" name="queryType" id="queryType" value="all"></input>
<input type="hidden" name="inputManagerTrade" id="inputManagerTrade" ></input>
<input type="hidden" name="fundGroup1" id="fundGroup1" ></input>
<input type="hidden" name="tradeType1" id="tradeType1" ></input>
<input type="hidden" name="tradeType2" id="tradeType2" ></input>
</form>
<iframe name="iframe" style="display: none"></iframe>
<button type="button" class="btn formExport" id="analysisExprot">
<i class="fa fa-download"></i> 导出
</button>
<script>
$("#analysisExprot").click(function(){//调用导出表格的接口
var startDate =$('#datetimepicker_start').val();
var date = $('#datetimepicker_start2').val();
var inputManagerTrade=$("#firstname").val();
var fundGroup1 = $("#plantype").val();
var tradeType1 = $("#type1").val();
var tradeType2 = $("#type2").val();
$('#startDate').val(startDate);
$('#dDate').val(date);
$('#inputManagerTrade').val(inputManagerTrade);
$('#fundGroup1').val(fundGroup1);
$('#tradeType1').val(tradeType1);
$('#tradeType2').val(tradeType2);
$('#form1_excel').submit();// 提交Form
});
</script>
Controller接收代码:@RequestParam可省略,可同时包装Object和普通参数
@PostMapping(value = "export")
@ResponseBody
public void exportInvestmentAnalysis(
InvestmentAnalysisDto dto,
@RequestParam(value = "queryType") String queryType,
HttpServletRequest request,
HttpServletResponse response) {
}
请求头信息:
1.2、原生ajax提交FormData对象
JS代码:这里需要包装成FormData对象,jquery不需要包装成FormData对象,猜测是jquery对ajax的传输数据data进行了包装
var excelName = '配置分析' + $('#datetimepicker_start').val() + '.xlsx';
//var url = URL.createObjectURL(workbook2blob(wb));
var blobWB = workbook2blob(wb); // blob对象
var fd = new FormData(); // FormDate对象包装blob
fd.append('fname', excelName);
fd.append('data', blobWB);
fd.append('gsCells', gsNum*3+7);
fd.append('qyCells', qyNum*3+7);
var xhr = new XMLHttpRequest();
xhr.open('post', 'exportCfgAna', true);
xhr.responseType = 'blob';
//xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.onload = function () {
if (this.status == 200) {
var blob = this.response;
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
a.href = url;
//设置文件名称
a.download = excelName;
a.click();
}
}
xhr.send(fd);
Controller接收代码:可以同时包装Object和普通参数
@PostMapping(value = "exportCfgAna")
@ResponseBody
public void exportCfgAna(@RequestParam(value = "fname", required = false)String fname,
@RequestParam(value = "data", required = false)MultipartFile file,
@RequestParam(value = "gsCells", required = false)Integer gsCells,
@RequestParam(value = "qyCells", required = false)Integer qyCells,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
GeneralResult result = new GeneralResult();
ExcelUtils utils = new ExcelUtils();
try {
utils.exportExcelAggInvAna(fname, file.getInputStream(), gsCells, qyCells, request, response);
} catch (Exception e) {
result.fail(CodeUtils.CREATE_MODEL_ERROR, e.getMessage());
e.printStackTrace();
}
}
请求头信息:
1.3、jquery的ajax提交
直接传对象,这里跟原生js的ajax不同,原生js需要包装成FormData对象,这里直接传对象Controller层就可以接收到
// 账户明细-二级组合类型
$("#type1").change(function(){
var fundGroup1=$("#plantype").val();
var tradeType1=$(this).val();
var data = {
fundGroup1:fundGroup1,
tradeType1:tradeType1,
queryType : 'tradeType2'
};
$.ajax({
type: "post",
url: "/tpreport/investmentAnalysis/list",
data:data,
dataType : 'json',
success: function (data) {
if(data.code=='1000'){
var typyHtmlStr = "<option value=''>请选择</option>";
var typyList= data.data.tradeType2;
for (var i = 0; i < typyList.length; i++){
var tradeType2 = typyList[i].tradeType2;
if(!isEmpty(tradeType2)){
typyHtmlStr += "<option>"+tradeType2+"</option>";
}
}
$("#type2").html(typyHtmlStr);
}else{
var typyHtmlStr = "<option value=''>请选择</option>";
$("#type2").html(typyHtmlStr);
}
}
});
});
Controller接收参数:对象和普通参数可以同时包装
@RequestMapping(value = "list", method = RequestMethod.POST)
@ResponseBody
public GeneralResult queryInvestmentAnalysis(InvestmentAnalysisDto dto, @RequestParam(value = "queryType") String queryType) {
GeneralResult result = new GeneralResult();
return result;
}
2、Json字符串提交数据的几种方式(需要设置contentType)
2.1、原生ajax提交json格式数据,需要设置contentType
用JSON.stringfy包装数据
//导出
exportFun = function () {
var exportJson = {
"selectFund":selectFund,
"selectMngs":selectMngs,
"mngs_info_data":mngs_info_chart_data,
"mng_info_data":mng_info_chart_data2,
"dateList":normal_date,
"selectMng":selectMng,
"selectFund":selectFund};
var jsonObj = JSON.stringify(exportJson) // 转成json字符串格式
var xhr = new XMLHttpRequest();
xhr.open('post', '/tpreport/aggInvAna/exportInvMng', true);
xhr.responseType = 'blob';
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8'); // 这里设置数据类型和编码,否则中文乱码
xhr.onload = function () {
if (this.status == 200) {
var blob = this.response;
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
a.href = url;
//设置文件名称
a.download = "投资经理"+date1+'-'+date2+".xlsx";
a.click();
}
}
xhr.send(jsonObj);
}
Controller接收:接口参数对象@RequestBody注解,可以自动包装成对象,未验证是否可以包装多个参数。
该例子是使用一个String参数接收Json字符串,然后通过解析拿到数据
@PostMapping(value = "exportInvMng")
@ResponseBody
public void exportInvMng(@RequestBody String str,
HttpServletRequest request,
HttpServletResponse response) {
GeneralResult result = new GeneralResult();
try {
service.exportInvMng("投资经理.xlsx", str, request, response);
} catch (Exception e) {
result.fail(CodeUtils.CREATE_MODEL_ERROR, e.getMessage());
e.printStackTrace();
}
}
解析json传的代码:
String tJson = "{'selectMngs':'[12,13,14,15]','mngs_info_data':'{\"陆坚\":\"[11.23,22.43,33.56,44.77]\"}','selectMng':'陆坚'}";
public void exportInvMng(String fileName, String jsonStr, HttpServletRequest request, HttpServletResponse response) throws Exception {
ExcelUtils excelUtils = new ExcelUtils();
// 数据集合
Map map=new HashMap<>();
List<Object> tempList = new ArrayList<>();
List<Object> chartList = new ArrayList<>();
// 处理json格式数据
JSONObject jsonObject = JSON.parseObject(jsonStr);
// 选择的经理【不是所有经理有数据】
List<String> selectMngs = JSON.parseArray(jsonObject.get("selectMngs").toString(), String.class);
// 所有经理的数据
JSONObject mngsInfoJson = JSON.parseObject(jsonObject.get("mngs_info_data").toString());
// 时间
List<String> dates = JSON.parseArray(jsonObject.get("dateList").toString(), String.class);
// 当前选择经理数据
JSONObject mngInfoJson = JSON.parseObject(jsonObject.get("mng_info_data").toString());
// 组合经理净值选择的经理
Object selectMng = jsonObject.get("selectMng");
// 组合经理净值选择的组合
Object mngFund = jsonObject.get("selectFund");
}
请求头信息:
2.2、jquery的ajax提交Json串数据,需要设置contentType
JSON.stringfy(data)
var jsonData = {"startDate":date1,"dDate":date2,"queryType":"managers","managerType":mngType,}
$.ajax({
url:"/tpreport/investmentAnalysis/manager",
method:"post",
data:JSON.stringify(jsonData),
dataType:"json",
contentType:"application/json;charset=UTF-8",
success:function (data) {
}
});
Controller接收参数:dto自动包装
@RequestMapping(value = "manager", method = RequestMethod.POST)
@ResponseBody
public GeneralResult managers(@RequestBody InvestmentAnalysisDto dto) {
}
请求头:
2.3、也可以手动拼接json字符串
上一篇: 全部二货得瑟爆笑吹牛B