四、spring Boot项目中Controller的使用

其实在spring Boot项目中的Controller和普通spring项目基本没有区别

1、类和方法上的常用注解

@Controller 处理http请求

   该注解不能单独使用必须配合模板使用

@RestController  在类上声明该注解才能返回json数据

 spring4之后加的新注解,原来返回json需要@ResponseBody加@Controller

@RequestMapping(value="/hello",method = RequestMethod.GET)
           配置url映射

  1.多个mapping映射一个方法,将value 写成集合的方式。

@RequestMapping(value={"/hello","/hi"},method = RequestMethod.GET)
  2.过在类上声明 @RequestMapping("/hello") 和方法上的映射名称拼接进行方法访问
  3.过更改method属性的值来控制http的访问方式,当method没有赋值的时候get、post访问都可以访问(不建议)

2、获取参数值的常用注解

  1.@PathVariable获取url中的数据

@RequestMapping(value="/say/{id}",method = RequestMethod.GET)
public String say(@PathVariable("id")Integer id){
  return "id:" + id;
}

  2.@RequestParam获取请求参数的值

@RequestMapping(value="/say",method = RequestMethod.GET)
public String say(@RequestParam("id") Integer myId){
  return "id:" + myId;
}

3.@RequestPara设置默认值

           required:是否必填

           defaultValue :默认值(必须为字符串)

@RequestMapping(value="/say",method = RequestMethod.GET)
public String say(@RequestParam(value = "id",required = false,defaultValue = "0") Integer myId){
  return "id:" + myId;
}

4. 组合注解

简化@RequestMapping(value="/say",method = RequestMethod.GET)的方法
   使用 @GetMapping(value = "/say")
   或者@PostMapping(value = "/say")

猜你喜欢

转载自www.cnblogs.com/404code/p/10569132.html