@GetMapping和@PostMapping详解

x33g5p2x  于2021-11-21 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(211)

首先要了解一下@RequestMapping注解。

@RequestMapping用于映射url到控制器类的一个特定处理程序方法。可用于方法或者类上面。也就是可以通过url找到对应的方法。

@RequestMapping有8个属性。

  • value:指定请求的实际地址。
  • method:指定请求的method类型(GET,POST,PUT,DELETE)等。
  • consumes:指定处理请求的提交内容类型(Context-Type)。
  • produces:指定返回的内容类型,还可以设置返回值的字符编码。
  • params:指定request中必须包含某些参数值,才让该方法处理。
  • headers:指定request中必须包含某些指定的header值,才让该方法处理请求。

@getMapping与@postMapping是组合注解。
@getMapping = @requestMapping(method = RequestMethod.GET)。

@postMapping = @requestMapping(method = RequestMethod.POST)。

@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。该注解将HTTP Get 映射到 特定的处理方法上。

Difference between @GetMapping & @RequestMapping:

@GetMapping does not support the consumes attribute of @RequestMapping.

SpringBoot 中@GetMapping和@PostMapping测试同一方法,为什么用@Get类型的注解可以访问成功,而@PostMapping用浏览器访问失败

@Controller
public class JspController {
    @PostMapping("/index")
    public String index(Model model){
        model.addAttribute("msg","springboot访问JSP页面");
        return "index";
    }
 
}

用@PostMapping注解,在浏览器输入访问地址时,会出现

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Feb 20 09:50:06 CST 2019

There was an unexpected error (type=Method Not Allowed, status=405).

Request method ‘GET’ not supported

而用@GetMapping注解,可以访问成功

通过浏览器的地址栏输入地址,所访问的URL都是get请求,因此如果以post定义方法,那么由于请求与实现的不一致,会返回405错误。

浏览器发送Get请求有

1.直接在地址栏中输入地址

2.点击链接

3.表单默认提交方式

浏览器发送post请求有:

1.将表单的method设置为post

相关文章

微信公众号

最新文章

更多