在SpringMVC相关的前面的文章中,采用@RequestMapping对处理函数进行注解,默认情况下,这些方法都是对GET方法进行处理,那如何改变这些处理函数支持的HTTP方法?
1 修改IndexController类如下:
package com.gm.springmvc_test.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@RequestMapping(value = "/index/{name}", method = RequestMethod.POST)
public String indexController(@PathVariable("name") String name) {
return "欢迎您: " + name;
}
}
此时在@RequestMapping参数中加入了一个method参数用来设置HTTP方法。
注意:SpringMVC最新的版本中提供了一种更加简洁的配置HTTP方法的方式,增加了四个标注:
@PutMapping
@GetMapping
@PostMapping
@DeleteMapping
如上例中,我们可以改成@PostMapping("index/{name}")
2 在浏览器中输入http://localhost:8080/index/gongmin,发现浏览器中出现如下提示:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Jan 02 10:55:23 CST 2018
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
提示不支持GET方法,这是因为浏览器默认使用GET方法来进行HTTP的请求。我们可以通过Postman这个插件来模拟请求。
3 使用Postman进行POST请求: