SpringBoot-URL路由:@Controller和@RequestMapping

一、@Controller标注的类表示的是一个处理HTTP请求的控制器(即MVC中的C),该类中所有被@RequestMapping标注的方法都会用来处理对应URL的请求。该类也可以被@RequestMapping标注,此时该类中所有方法的url路径都在该目录下。

在SpringMVC框架中,使用@RequsetMapping标注可以将URL与处理方法绑定起来,例如:

@RestController//控制器
@RequestMapping("/index")//绑定接口url:localhost:8080/index
public class HelloController {
    private final Logger LOG = LoggerFactory.getLogger(HelloController.class);

    @RequestMapping("/")//绑定接口url:localhost:8080/index/
    public String HelloWorld(){
        return "hello world";
    }

    @RequestMapping("/test")//绑定接口url:localhost:8080/index/test
    public String HelloWorldTwo(){
        return "this is a test";
    }

}

在浏览器地址里输入:localhost:8080/index/、localhost:8080/index/test,请求会分别交给对应接口绑定的方法Helloworld()和HelloWorldTwo()处理。

结果:

二、@RequestMapping的解释

在web应用中常用的HTTP方法有四种:

  1. PUT方法用来添加资源
  2. GET方法用来获取已有的资源
  3. POST方法用来对资源进行状态转换
  4. DELETE方法用来删除已有的资源

每一个Web请求都是属于其中一种,在@RequestMapping中如果不指定method值的话,默认是GET请求。

因此@RequestMapping("/")是@RequestMapping("/",method = RequestMethod.GET)的默认,可以通过method属性,设置请求的HTTP方法。

@RequestMapping(value = "/",method = RequestMethod.GET)
//等价于@RequestMapping("/")

@RequestMapping(value = "/",method = RequestMethod.PUT)

@RequestMapping(value = "/",method = RequestMethod.POST)

@RequestMapping(value = "/",method = RequestMethod.DELETE)

比如PUT /hello请求,对应@RequestMapping("/hello",method = RequestMethod.PUT)

Spring MVC最新的版本中提供了一种更加简洁的配置HTTP方式,增加了四个简写注解:

  1. PutMapping
  2. GetMapping
  3. PostMapping
  4. DeleteMapping
@GetMapping("/")
//等价于@RequestMapping(value = "/",method = RequestMethod.GET)

@PutMapping("/")
//等价于@RequestMapping(value = "/",method = RequestMethod.PUT)

@PostMapping("/")
//等价于@RequestMapping(value = "/",method = RequestMethod.POST)

@DeleteMapping("/")
//等价于@RequestMapping(value = "/",method = RequestMethod.DELETE)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值