org.springframework.web.bind.annotation这个包中注解如下图,该包中的注解的作用是绑定参数和方法,比如@CookieValue是将前端的Cookie值和目标方法的参数绑定. @RequestParam 和 @ PathVariable 也是绑定 请求的参数 和 url 路径中的值!
1、@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,将URL和目标方法绑定起来. 可用于类或方法上。用于类上,表示类中的所有响应请求的方法 都是以该地址作为父路径,类和方法共同组成的字符串才是一个完整的url.
@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Mapping public @interface RequestMapping{ String[] value() default {}; RequestMethod[] method() default {}; String[] params() default {}; String[] headers() default {}; String[] consumes() default {}; String[] produces() default {}; }
RequestMapping注解有六个属性,下面我们把她分成三类进行说明(下面有相应示例)。
1、 value, method;
value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
method: 指定请求的method类型, GET(查)、POST(改)、PUT(增)、DELETE(删)等;
2、consumes,produces
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
3、params,headers
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
2、@PathVariable
这个注解用来修饰handler类 方法参数的,被修饰的参数会将url 中的参数赋值给参数,方法内部就可以使用了.
//只能修饰参数 @Target({java.lang.annotation.ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface PathVariable { String value() default ""; }
用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数。如:
public class TestController { @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET) public String getLogin(@PathVariable("userId") String userId, @PathVariable("roleId") String roleId){ System.out.println("User Id : " + userId); System.out.println("Role Id : " + roleId); return "hello"; } @RequestMapping(value="/product/{productId}",method = RequestMethod.GET) public String getProduct(@PathVariable("productId") String productId){ System.out.println("Product Id : " + productId); return "hello"; } //还可以用正则表达式 @RequestMapping(value="/javabeat/{regexp1:[a-z-]+}", method = RequestMethod.GET) public String getRegExp(@PathVariable("regexp1") String regexp1){ System.out.println("URI Part 1 : " + regexp1); return "hello"; } }