SpringMVC(四):RequestMapping

打印 上一主题 下一主题

主题 1722|帖子 1722|积分 5166

现在我们来学习一下RequestMapping注解。
RequestMapping注解用来将url映射到一个控制类(Controller类)或一个特定处理的方法上。
一、RequestMapping使用的位置
1.方法上
直接上实例:
  1. package com.jms.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.ui.Model;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. @Controller
  6. public class MainController {
  7.     @RequestMapping("/t1")
  8.     public String test1(Model model) {
  9.         model.addAttribute("message", "test1");
  10.         return "main";
  11.     }
  12. }
复制代码

 
 此时直接访问类上注解的地址即可发起请求。
2.类上
使用在类上时不能仅仅使用在类上,还需要同时使用在方法上。
使用在类上相当于给使用RequestMapping注解的方法添加了一个父关系,也就说在实际请求时需要将类注解的url和方法注解的地址拼接起来,看下面的例子:
  1. package com.jms.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.ui.Model;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. @Controller
  6. @RequestMapping("/m1")
  7. public class MainController {
  8.     @RequestMapping("/t1")
  9.     public String test1(Model model) {
  10.         model.addAttribute("message", "test1");
  11.         return "main";
  12.     }
  13. }
复制代码
此时在类和方法上都有注解,我们访问一下:

 
 此时我们需要访问类注解和方法注解拼接起来的路径才能够发起请求。
一般来说直接在方法上写死即可,无需在类上进行RequestMapping注解的使用。
二、RequestMapping注解的属性
我们来看一下RequestMapping注解的源码:
  1. @Target({ElementType.TYPE, ElementType.METHOD})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Mapping
  5. public @interface RequestMapping {
  6.     String name() default "";
  7.     @AliasFor("path")
  8.     String[] value() default {};
  9.     @AliasFor("value")
  10.     String[] path() default {};
  11.     RequestMethod[] method() default {};
  12.     String[] params() default {};
  13.     String[] headers() default {};
  14.     String[] consumes() default {};
  15.     String[] produces() default {};
  16. }
  17.    
复制代码
1.name属性:这个属性相当于方法的注释,使方法更容易理解。
2.value属性:指定请求的实际地址,指定的地址可以是URI 模板模式(Template Pattern),这里用的是数组,说明可以有多个值;value属性是RequestMapping注解的默认属性,我们所写的@RequestMapping("/t1")实际上就是@RequestMapping(value = "/t1")。
3.path属性:有源码中可见,path与value互为别名,也就是说它和value属性的作用是相同的。
4.method属性:指定请求的类型,我们看一下RequestMethod的源码如下:

 
 由此我们衍生出来了一些新的注解,如
    @GetMapping
    @PostMapping
    @PutMapping
    @PatchMapping
    @DeleteMapping
@GetMapping("/t1")就等价于@RequestMapping(value="/t1", method=RequestMethod.GET)。
 
(本文仅作个人学习记录用,如有纰漏敬请指正)

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

伤心客

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表