springMVC中controller的传参的几种案例
1、springmvc的controller方法不指定method时,默认get/post都支持
//@RequestMapping(value="test") //@RequestMapping(value = "test", method = RequestMethod.GET) //@ReqestMapping(value = "test", method = RequestMethod.POST) public void test(String test) { }
2、每个参数都列出来,用String类型申明(get/post都可以)
@RequestMapping(value = "getChinaCityData", produces = "application/json; charset=utf-8") @ResponseBody public String getChinaCityData(String startTime,String endTime,String timeType,String cityCode) { }
3、参数太多的时候,可以考虑直接传递对象(只支持post)
后端用@RequestBody注释,对象是一个javaBean。
@RequestMapping(value = "/forecastModel/selectProvinceAssessmentStatistics", produces = "application/json; charset=utf-8") @ResponseBody public String selectProvinceAssessmentStatistics(@RequestBody ProvAssessVo provAssessVo)
{ String time=provAssessVo.getStartTime();//ProvAssessVo是一个对象,是javaBean
}
前端ajax要加:contentType : 'application/json;charset=utf-8',
var param = {}; var statsType = thisObj.statsType; var startTime = thisObj.startTime.Format("yyyy-MM-01 00:00:00"); var endDate = new Date(); endDate.setTime(thisObj.endTime.getTime()); endDate = endDate.dateAdd("m", 1); var endTime = endDate.Format("yyyy-MM-01 00:00:00"); param.startTime = new Date(startTime); param.endTime = new Date(endTime); param.type = statsType; param.offsets = $('#hourTypeValue').text().match(/\d+/)[0]; CSJJ_RequestMethod(url,JSON.stringify(param),"json","post", true, function (data) { thisObj.renderProvAssessmentStatisticsBody(data); });
4、使用requestParam或者PathVariable。
@GetMapping("/get") public User getUserById(@RequestParam(name = "id", required = true,defaultvalue=0) Integer id)
{ if (id.intValue() == 0) { return null; } return list.get(id); }
@GetMapping("/get/{id}") public User getUserByPathValue(@PathVariable(name = "id", required = true) Integer id)
{ return list.get(id);//该方式用来获取路径中的参数 }
5、使用HttpServletRequest
(1)用来传参:String name = request.getParameter("name")
(2)用来获取http的相关信息,多用在登陆,用户日志,文件上传等。