@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";
}
}
重启服务器,会发现,被拦住了!!!
知识点:
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 删除