Day03 SpringBoot中Controller中各种注解的使用

xiaoxiao2021-02-28  48

RestController注解的使用

@RestController 等同于 @Controller和@ResponseBody

在某个方法上写@RestController ,则此方法的return返回的是json

@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(){ return "hello"; } } //上面代码等价于下面代码 @Controller @ResponseBody public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(){ return "hello"; } }

@RequestMapping 配置url映射

@RequestMapping此注解即可以作用在控制器的某个方法上,也可以作用在此控制器类上。

几种参数绑定

1.无参类型 @RequestMapping(value="/helloparam2",method= RequestMethod.GET) public String helloParam(){ return "hello"; } 2.PathVariable参数绑定 用来获得请求url中的动态参数的 是从一个URI模板里面来填充 通过http://localhost:8080/helloparam/3 来访问 @RequestMapping(value="/helloparam/{id}",method= RequestMethod.GET) public String helloParam(@PathVariable("id") Integer id){ return "id:"+id; } 3.RequestParam参数绑定 @RequestParam 是从request里面拿取值 通过http://localhost:8080/helloparam?id=3 来访问 @RequestMapping(value="/helloparam3",method= RequestMethod.GET) //第一个id是与url地址参数相对应,第二个myid随意起名字 //设置默认值,若不传id,则使用默认值 public String helloParam3(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myid){ return "id:"+myid; } //若没有required = false, defaultValue = "0",则代表未设置默认值

@GetMapping 简化@RequestMapping书写

@GetMapping则代表get方式请求 @PostMapping则代表post方式请求 后续会说到以下几种 @PutMapping @DeleteMapping

//简化@RequestMapping书写 @GetMapping(value = "/helloparam4") public String helloParam4(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myid){ return "id:"+myid; }
转载请注明原文地址: https://www.6miu.com/read-2631682.html

最新回复(0)