1)方式一:对于请求方式为?id=10&name=jery这种方式使用@RequestParam接收
http://localhost:8080/springmvc/user/findUser?id=100&name=tom
/**
* 通过@RequestParam获取请求参数
* 当方法中的形参名和提交的参数名不一致时用@RequestParam
* http://localhost:8080/springmvc/user/findUser?id=100&name=tom
* value="name" : 接收的参数名是 name
* required=false : 表示该参数可以有,也可以没有,如果 required=true,表示必须传递该参数
*/
@RequestMapping("/findUser")
public ModelAndView findUserParam(
@RequestParam(value = "id") int userId,
@RequestParam(value = "name", required = false, defaultValue = "jury") String userName) {
System.out.println("获取用户提交的数据:" + userId + ", " +userName);
return new ModelAndView("hello");
}
2)方式二:对于RestFul风格的请求使用@PathVariable
http://localhost:8080/springmvc_2/user/restFul/100/tom/36/男
/**
* RESTful风格
* href="user/restFul/100/tom/36/男"
*/
@GetMapping("/restFul/{id}/{userName}/{age}/{sex}")
public ModelAndView restFul(@PathVariable int id,
@PathVariable("userName") String name,
@PathVariable int age,
@PathVariable String sex) {
System.out.println("姓名: " + name + ", 年龄: " + age + ", 性别: " + sex);
return new ModelAndView("hello");
}
3)方式三:对于post/put请求{key:value,key:value,…}的json方式的参数使用@RequestBody接收
/**
* Ajax页面参数传递: JSON串 {"id":100,"name":"张三","age":18,"sex":"女"}
* 注解: @RequestBody 将用户传递的JSON串,转化为对象.
* 要求:key必须与对象的属性保持一致
*/
@RequestMapping(value = {"/postAjax","/putAjax"},method = {RequestMethod.POST,RequestMethod.PUT})
public User postAjax(@RequestBody User user){
user.setName("服务器数据");
return user;
}
@RequestBody说明
使用了axios发送ajax请求之后,浏览器发送到服务器的请求参数有两种格式:
(1)name=value&age=value…(这种方式适用于get/delete请求),此时的请求参数可以通过request.getParameter()获取,对应SpringMVC中,可以直接通过控制器方法的形参(@RequestParam)获取此类请求参数
(2){key:value,key:value,…}(这种方式适用于post/put请求),此时无法通过request.getParameter()获取,之前我们使用操作json的相关jar包gson或jackson处理此类请求参数,可以将其转换为指定的实体类对象或map集合。在SpringMVC中,直接使用@RequestBody注解标识控制器方法的形参即可将此类请求参数转换为java对象
补充:
前端传递过来的JSON字符串的转换
//将前端传来的JSON字符串转换成List
List<DamageListGoods> damageListGoodsList = JSONObject.parseArray(damageListGoodsStr, DamageListGoods.class);
System.out.println("damageListGoodsList = " + damageListGoodsList);