资源定位及资源操作的一种风格,不是协议,可以遵循,也可以不遵循
REST 即 Representational State Transfer
(资源)表现层状态转化,用 URL 定位资源,用 HTTP 描述操作,是目前最流行的一种互联网软件架构,它的结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用,使用POST,DELETE,PUT,GET 分别对应 CRUD,Spring3.0 开始支持 REST 风格的请求。
URL | 概述 |
---|---|
http://localhost:8080/get.action?id=10 | 查询 GET |
http://localhost:8080/add.action | 新增 POST |
http://localhost:8080/update.action | 修改 POST |
http://localhost:8080/delete.action?id=10 | 删除 POST |
URL | 概述 |
---|---|
http://localhost:8080/goods/1 | 查询 GET |
http://localhost:8080/goods | 新增 POST |
http://localhost:8080/goods | 更新 PUT |
http://localhost:8080/goods/1 | 删除 DELETE |
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>@RequestMapping相关属性</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/restful/1.action">测试rest路径</a>
</body>
</html>
/**
* @author: BNTang
*/
@Controller
public class MyFirstController {
@RequestMapping("/restful/{id}")
public String show(@PathVariable Integer id) {
System.out.println(id);
return "/first";
}
}
默认情况下 Form 表单是不支持 PUT 请求和 DELETE 请求的,Spring3.0添加了一个过滤器 HiddenHttpMethodFilter
,可以将 POST 请求转换为 PUT 或 DELETE 请求。
修改 web.xml
<!--
配置 HiddenHttpMethodFilter 过滤器
实现 RestFul 请求
-->
<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>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>@RequestMapping相关属性</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/restful/1.action" method="post">
<%--
定义一个隐藏的表单,name 值必须为 _method, value 为请求方式
--%>
<input type="hidden" name="_method" value="put"/>
<input type="submit" value="提交请求"/>
</form>
</body>
</html>
/**
* @author: BNTang
*/
@Controller
public class MyFirstController {
@RequestMapping(value = "/restful/{id}", method = {RequestMethod.PUT})
public String show(@PathVariable Integer id) {
System.out.println(id);
return "redirect:/result.action";
}
@RequestMapping("/result")
public String res() {
return "/first";
}
}
注意事项,从 Tomcat8 开始,如果直接返回 JSP 页面,会报 405 的错误 JSPs only permit GET POST or HEAD
,使用重定向的形式跳转到对应的 JSP,或者是直接把对应 JSP 的 isErrorPage="true"
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有