springmvc实现REST中的GET、POST、PUT和DELETE

spring mvc 支持REST风格的请求方法,GET、POST、PUT和DELETE四种请求方法分别代表了数据库CRUD中的select、insert、update、delete,下面演示一个简单的REST实现过程。

package me.elin.rect;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/rest")
public class RESTMethod {
    private static final String SUCCESS = "success";

    // 该方法接受POST传值,请求url为/rest/restPost
    @RequestMapping(value = "restPost", method = RequestMethod.POST)
    public String restPost(@RequestParam(value = "id") Integer id) {
        System.out.println("POST ID:" + id);
        return SUCCESS;
    }

    // 该方法接受GET传值,请求url为/rest/restGet
    @RequestMapping(value = "/restGet", method = RequestMethod.GET)
    public String restGet(@RequestParam(value = "id") Integer id) {
        System.out.println("GET ID:" + id);
        return SUCCESS;
    }

    // 该方法接受PUT传值,请求url为/rest/restPut
    @RequestMapping(value = "/restPut", method = RequestMethod.PUT)
    public String restPut(@RequestParam(value = "id") Integer id) {
        System.out.println("PUT ID:" + id);
        return SUCCESS;
    }

    // 该方法接受DELETE传值,请求url为/rest/restDelete
    @RequestMapping(value="/restDelete",method=RequestMethod.DELETE)
    public String restDelete(@RequestParam(value = "id") Integer id) {
        System.out.println("DELETE ID:" + id);
        return SUCCESS;
    }
}
  • 在web.xml中添加一个filter,用来过滤rest中的方法。代码如下
    <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>
  • 在WebContent下创建index.jsp文件,添加如下内容
<a href="rest/restGet?id=1">发送GET请求</a>

<form action="rest/restPost" method="post">
    <input type="text" name="id" value="2"/>
    <input type="submit" value="发送POST请求"/>
</form>

<form action="rest/restPut" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="text" name="id" value="3">
    <input type="submit" value="发送PUT请求">
</form>


<form action="rest/restDelete" method="post">
    <input type="hidden" name="_method" value="DELETE">
    <input type="text" name="id" value="4">
    <input type="submit" value="发送DELETE请求">
</form>

其中get和post方法是html中自带的,但是不支持PUT和DELETE方法,所以需要通过POST方法模拟这两种方法,只需要在表单中添加一个隐藏域,名为_method,值为PUT或DELETE。

  • 运行程序,index.jsp中一个超链接和三个表单分别表示了四种请求方法。
  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值