最近在为一个SpringMVC架构的web系统添加功能,既要写后台接口和业务逻辑,也要写前端页面通过http请求调用后台接口,在参数的传递和获取方面遇到的问题最多,于是自己总结了一下,方便和我一样学艺不精的同学参考,也让自己加深理解和记忆,欢迎批评指正。
方法一:请求参数放入body
后台controller:
@RequestMapping("/queryone")
@ResponseBody
public Map<String, Object> queryone( @RequestBody Map<String, String> map) {
Map<String, Object> cityCollectionMap = new HashMap<String, Object>();
List<CityCollection> cityCollectionList = new ArrayList<CityCollection>();
cityCollectionList = cityCollectionService.queryone(map);;
cityCollectionMap.put("data", cityCollectionList);
// 获取总记录条数
int total = PageUtil.getTotalCount();
cityCollectionMap.put("total", total != -1 ? total : cityCollectionList.size());
return cityCollectionMap;
}
此处注意参数注解@RequestBody,用于将前台发送过来固定格式的数据【xml 格式或者 json等】封装为对应的 JavaBean 对象,封装时使用到的一个对象是系统默认配置的 HttpMessageConverter进行解析,然后封装到形参上,因此前端调用接口传参时,要注意数据的格式:
前端调用示例:
var url = context + "/service/icity/operation/cityCollection/queryone";
$.ajax({
url: url,
type: "POST",
data: "{\"userId\":\"" + getUserId() + "\",\"cityCode\":\"" + thisCode + "\"}",
async: false,
contentType: "application/json",
success: function (data) {
if(data.total >=1){
collectBtn = "<a class=\"delCollect\" style='color:darkgrey'>取消收藏</a>";
}
else collectBtn = "<a class=\"collect\" >收藏城市</a>";
},
error: function (msg) {
alert(msg.responseText);
}
});
js代码请求时注意参数data:以json字符串形式传递参数;重中之重: contentType: "application/json" 这句不能落下,不然无法将json字符串解析为正确的参数形式,后台接口将无法正确获取参数。
方法二:参数写在请求的URL末尾
后台controller:
@RequestMapping(value = "/get")
public ModelAndView getUserOperationLog(@RequestParam(value = "logId", required = false)Long logId) {
Map<String, Object> model = new HashMap<String, Object>();
IcityUserOperationLog icityUserOperationLog = null;
if (logId != null && !"".equals(logId)) {
icityUserOperationLog = icityUserOperationLogService.get(logId);
}
model.put("data", icityUserOperationLog);
return new ModelAndView("icity/operation/basecenter/icityuserlog/useroperationlogdetail", model);
}
此处注意参数注解@RequestParam,该注解将拼接在URL末尾的参数加息出来,并赋给参数列表中相应的参数,只有参数列表中有名为"logId"的参数,才可以将其值赋给后面的logId。
前端调用示例:
var url = context + "/service/icity/operation/basecenter/icityuserlog/get";
if(data.logId!=undefined&&data.logId!=""){
url += "?"+"logId="+data.logId;
//参数拼接在URL末尾
}
window.location.href = url;
此处调用涉及到页面重定向,相信不需要页面重定向也是一个道理。
以上为我关于参数请求及获取的心得。
如有不足,欢迎指正。