SpringMVC-@PathVariable注解与REST风格请求
REST 风格
资源定位及资源操作的一种风格,不是协议,可以遵循,也可以不遵循
REST 风格请求
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 |
restful 操作资源
URL | 概述 |
---|---|
http://localhost:8080/goods/1 | 查询 GET |
http://localhost:8080/goods | 新增 POST |
http://localhost:8080/goods | 更新 PUT |
http://localhost:8080/goods/1 | 删除 DELETE |
使用 @PathVariable 接收 RESTFul 风格参数
<%@ 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";
}
}
发送 PUT 与 DELETE 请求
默认情况下 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"
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具