Spring MVC REST风格

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";
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gary jie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值