Spring REST 风格可以简单理解为:使用 URL 表示资源时,每个资源都用一个独一无二的 URL 来表示,并使用 HTTP 方法表示操作,即准确描述服务器对资源的处理动作(GET、POST、PUT、DELETE),实现资源的增删改查。
示例
HTTP 不支持 PUT 和 DELETE 请求,所以需要将 DELETE 和 PUT 请求转换成 POST 请求。
在 web.xml 中配置过滤器 HiddenHttpMethodFilter。
<!-- HiddenHttpMethodFilter过滤器可以将POST请求转化为put请求和delete请求! -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
新建 rest.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>REST风格</title>
</head>
<body>
<h4>发送GET请求</h4>
<a href=" user/1">GET</a>
<h4>发送POST请求</h4>
<form action="user/1" method="post">
<input type="submit" value="POST" />
</form>
<!-- 发送PUT和DELETE请求时,需要添加一个隐藏域 -->
<h4>发送PUT请求</h4>
<form action=" user/1" method="post">
<input type="hidden" name="_method" value="PUT" /> <input
type="submit" value="PUT" />
</form>
<h4>发送DELETE请求</h4>
<input type="hidden" name="_method" value="DELETE" />
<form action=" user/1" method="post">
<input type="hidden" name="_method" value="DELETE" /> <input
type="submit" value="DELETE" />
</form>
</body>
</html>
下面通过@RequestMapping 映射请求中的 method 参数实现四种请求方式的调用,UserController⭐
@Controller
public class UserController {
@RequestMapping("/torest")
public String torest() {
return "rest";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public String hello(@PathVariable Integer id) {
System.out.println("test rest get:" + id);
return "success";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.POST)
public String hello() {
System.out.println("test POST:");
return "success";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public String helloDelete(@PathVariable Integer id) {
System.out.println("test rest delete:" + id);
return "success";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public String helloPUt(@PathVariable Integer id) {
System.out.println("test rest put:" + id);
return "success";
}
}