我的理解:其实@RequestMapping、@GetMapping、 @PostMapping 三者就是父类和子类的区别,RequestMapping是父类,@GetMapping、 @PostMapping为子类集成了RequestMapping更明确了http请求的类型
分析三者的源码:
- RequestMapping .class:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
String name() default "";
@AliasFor("path")
String[] value() default {};
@AliasFor("value")
String[] path() default {};
RequestMethod[] method() default {};
String[] params() default {};
String[] headers() default {};
String[] consumes() default {};
String[] produces() default {};
}
RequestMapping 源码可知@RequestMapping 可以同时作用的地方有方法和类(@Target({ElementType.TYPE, ElementType.METHOD}))如(可以在方法上添加@RequestMapping(method = RequestMethod.POST)@RequestMapping(method = RequestMethod.GEt)表示是get还是post请求 ),除了name一个参数是字符串 , 其他的参数都是数组,说明其他参数都可以是多值。那么一个函数是不是可有多个接口地址请求呢?
举个例子同个方法是否支持两个不同url请求:
(1)http://localhost:8000/login/pww
(2)http://localhost:8000/login/pww1
/**
* 表单形式请求数据
* .
* @param id
* @return
*/
@ResponseBody
@PostMapping(value = {"pww","pww1"})
public Map<String,Object> loginById(@RequestParam(name = "id") Integer id){
Map map = new HashMap() ;
switch (id){
case 0:
map.put("msg","你是邱工么");
break;
case 1:
map.put("msg","你真的是邱工么");
break;
case 2:
map.put("msg","是的 我是邱工");
break;
case 3:
map.put("msg","hello! 邱工");
break;
case 4:
map.put("msg","邱工哈哈");
break;
case 5:
map.put("msg","邱工呵呵");
break;
default:{
map.put("msg","邱工是个女的!");
break;
}
}
return map ;
}
结果证明是可行的。
- GetMapping.class:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
method = {RequestMethod.GET}
)
public @interface GetMapping {
@AliasFor(
annotation = RequestMapping.class
)
String name() default "";
@AliasFor(
annotation = RequestMapping.class
)
String[] value() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] path() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] params() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] headers() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] consumes() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] produces() default {};
}
- PostMapping .class:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
method = {RequestMethod.POST}
)
public @interface PostMapping {
@AliasFor(
annotation = RequestMapping.class
)
String name() default "";
@AliasFor(
annotation = RequestMapping.class
)
String[] value() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] path() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] params() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] headers() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] consumes() default {};
@AliasFor(
annotation = RequestMapping.class
)
String[] produces() default {};
}
那么最后有源码分析得出GetMapping 和PostMapping就是 RequestMapping已经指定请求方式的简写版