Controller层接收参数方式
一、请求路径(url)中的参数
方式一:原始方式获取请求参数
方式一:原始方式获取请求参数@RequestMapping(value = "/depts", method = RequestMethod.DELETE)@DeleteMapping("/depts")public Result delete(HttpServletRequest request){String id = request.getParameter("id");int idInt = Integer.parseInt(id);System.out.println("id="+idInt);return Result.success();}
方式二:通过spring提供的@RequestParam注解获取请求参数
方式二:通过spring提供的@RequestParam注解获取请求参数@RequestParam加上之后,required默认值为true代表前端就必须要传递该参数,否则报错400,Bad Request, 如果不需要限制,可以将其设置为required=falsepublic Result delete(@RequestParam(value = "id", required = false) Integer deptId){System.out.println("deptId = " + deptId);//调用service的删除方法deptService.delete(deptId);return Result.success();}
方式三:形参变量名与请求参数名一致,可以自动封装简单参数值【推荐】
// 方式三:形参变量名与请求参数名一致,可以自动封装简单参数值【推荐】@DeleteMappingpublic Result delete(Integer id){log.info("id = {}", id);//调用service的删除方法deptService.delete(id);return Result.success();}
方式四:@PathVariable接受路径参数
接受路径中的参数 如/depts/{id} 中的id
@GetMapping("/{id}")public Result getById(@PathVariable Integer id){log.info("id = {}", id);//调用service的方法Dept dept = deptService.getById(id);return Result.success(dept);}
二、请求体中的参数(Json格式数据)
方式一:直接封装成Java对象
请求体中的key值与类的属性名对应一致,可以进行自动封装
@PutMappingpublic Result update(@RequestBody Dept dept){log.info("dept = {}", dept);deptService.update(dept);return Result.success();}
方式二:转换为Map<String,String> map对象
@PutMapping("/depts")public Result updateById(@RequestBody Map<String, String> map) {Integer id = Integer.parseInt(map.get("id"));String name = map.get("name");String createTime = map.get("createTime");return deptService.updateById(new Dept(id,name,createTime,null));}