一、@RequestParam
/** * 测试: RequestParam * * SpringMVC取参数有三种形式: * @RequestParam注解到参数上 : * 请求没有参数param1,会报错;可以通过required设置会false来解决这个报错问题(这个第二种没啥区别) * 不写注解直接名字 : * 请求没有参数param2不会报错,但会赋值为空 * 通过request.getParameter("")来获取 * @return */ @RequestMapping(value = "/requestParam" ,method = RequestMethod.POST) public String testRequestParam(@RequestParam(required = false) String param1, String param2, HttpServletRequest request){ System.out.println(param1); System.out.println(param2); String param3 = request.getParameter("param3"); System.out.println(param3); return "success"; }
二、@RequestBody
1.说明
@RequestBody只接收json数据,并且封装到实体类中
只接收post请求,不接受get请求
controller中不能写多个@RequestBody
要引入相应的依赖(jackson),不然前端会返回 415
2.实验
1)引入相应的依赖
<!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0 </version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> </dependencies>
2)前端
写异步post请求,传入json参数
3)后台
/** * 测试: RequestBody * 说明:1.接收json数据,并封装到实体类中 * 2.只接收post的请求参数,不接受get请求 * 3.controller中不能有多个RequestBody * * */ @RequestMapping(value = "/requestbody",method = RequestMethod.POST) public String testRequestBody(@RequestBody User user){ //如果不加@RequestBody :user并没有获取前端给的属性 System.out.println(user); return "success"; }