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"

posted @ 2020-11-08 15:47  BNTang  阅读(286)  评论(0编辑  收藏  举报