@RequestMapping和@GetMapping @PostMapping的区别
@GetMapping
:将HTTP get
请求映射到特定处理程序的方法注解,是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写,
- 源码如下:
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping( method = {RequestMethod.GET} ) public @interface GetMapping { @AliasFor( annotation = RequestMapping.class ) String name() default ""; .... }
@RequestMapping(method = RequestMethod.GET)
:这行代码即说明@GetMapping就是@RequestMapping附加了请求方法
@PostMapping
:将HTTP post
请求映射到特定处理程序的方法注解,是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写,
- 源码如下:
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping( method = {RequestMethod.POST} ) public @interface PostMapping { @AliasFor( annotation = RequestMapping.class ) String name() default ""; ....... }
- 如上类似
总结:除了上面二者的引入,还有@PostMapping、@PutMapping、@DeleteMapping和@PatchMapping,一共5个注解,所以,一般情况下用下面的注解也可
@RequestMapping(method = RequestMethod.XXXX)
@PathVaribale/@RequestParam介绍
@PathVaribale:获取url中的数据
需要获取localhost:8080/abc/id中的id值,实现代码如下
- 前提:通过@PathVariable注解来获取URL中的时参数的前提条件是我们知道url的格式时怎么样的。
只有知道url的格式,我们才能在指定的方法上通过相同的格式获取相应位置的参数值
@RestController
public class AbcController {
@RequestMapping(value="/abc/{id}",method= RequestMethod.GET)
public String test(@PathVariable("id") Integer id){
return "id:"+id;
}
}
在url有多个参数需要获取
@RestController
public class AbcController {
@RequestMapping(value="/abc/{id}/{name}",method= RequestMethod.GET)
public String test(@PathVariable("id") Integer id,@PathVariable("name") String name){
return "id:"+id+" name:"+name;
}
}
@RequestParam:获取请求参数的值
url的格式为:localhost:8080/abc?id=98,获取id值,get请求和post请求都是这样
@RestController
public class AbcController {
@RequestMapping(value="/abc",method= RequestMethod.GET)
//或
//@GetMapping("/abc")
public String test(@RequestParam("id") Integer id){
return "id:"+id;
}
}
url格式:localhost:8080/abc?id=98&&name=abc1,获取id和name值,get请求和post请求都是这样
@RestController
public class AbcController {
@RequestMapping(value="/abc",method= RequestMethod.GET)
//或
//@GetMapping("/abc")
public String test(@RequestParam("id") Integer id,@RequestParam("name") String name){
return "id:"+id+ " name:"+name;
}
}