其实在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")

相关文章:

  • 2021-08-20
  • 2021-12-24
  • 2021-11-22
  • 2021-10-24
  • 2022-12-23
  • 2021-09-15
  • 2021-04-19
  • 2021-11-14
猜你喜欢
  • 2021-09-21
  • 2021-06-16
  • 2019-10-27
  • 2021-12-30
  • 2021-11-08
  • 2022-01-21
  • 2022-01-16
相关资源
相似解决方案