@RequestMapping

@RequestMapping 和 @GetMapping 是Spring MVC中用于处理HTTP请求的注解。@RequestMapping用于映射URL到处理程序方法,并可用于指定请求方法(如GET,POST等)。@GetMapping是@RequestMapping的简写,表示只处理GET请求。

 @RequestMapping的各个属性

1. value属性

前面,我们使用@RequestMapping注解都是直接在他的括号中加servlet的名称。
这里解释一下,默认只写一个参数的话,就是给value赋值。
也就是

@RequestMapping(“/hello”)
等价于
@RequestMapping(value = “/hello”)

注意:value属性是一个字符串类型的数组,表示请求映射能够匹配多个请求地址所对应的请求。
假如现在有代码:

    @RequestMapping(value = {"/other", "/other2", "/other3"})
    public String toOther(){
        return "other";

那么访问other、other2、other3这三个servlet都可以导向other页面。

2. method属性

method属性通过请求的请求方式(get或post)匹配请求映射。他也是一个数组,但是是RequestMethod类的数组,表示请求映射能够匹配多种请求方式的请求。

注意:直接打开网页的请求方式是GET。

当你设置了method属性之后,如果当前请求的请求地址满足请求映射的value属性,但是请求方式不满足method属性,则浏览器会报错405(Request method ‘POST’ not support)
如果不设置method属性,那么无论是GET还是POST都可以打开我们的servlet。

所以,我们现在给我们的HelloController.java代码改为:

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {

    /*添加请求方式必须为POST请求*/
    @RequestMapping(value = "/",method = RequestMethod.POST)
    public String toIndex(){
        /*返回视图名称,刚才配置文件会自己给他加前缀/WEB-INF/templates/和后缀.html*/
        return "index";
    }
    
    @RequestMapping(value = {"/other", "other2", "other3"})
    public String toOther(){
        return "other";
    }
}

重启服务器,会发现,被拦住了!!!

 

7bb6111c057d45e4aea7c905263d20dc.png

知识点:
1、对于处理指定请求方式的控制器方法,SpringMVC中提供了@RequestMapping的派生注解:
处理get请求的映射 —> @GetMapping
处理post请求的映射 —> @PostMapping
处理put请求的映射 —> @PutMapping
处理delete请求的映射 —> @DeleteMapping

2、常用的请求方式有get、post、put、delete
但是目前浏览器只支持get和post,若在form表单提交的时候,为method设置了其他请求方式(put或delete),则默认按照get的请求方式处理。
若要发送put和delete请求,则需要通过spring提供的过滤器HiddenHttpMethodFilter

 

REST风格就是根据不同的请求类型,做出不同的响应,GET 查询  POST 添加   PUT 修改  DELETE 删除

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值