SpringMVC基础-SpringMVC的四种请求方式

SpringMVC注解@RequestMapping注解除了params,header属性,还有一个非常重要的属性——method,method的四种取值GET,POST,DELETE,PUT方式刚好对应了SpringMVC的四种请求方式。

SpringMVC的四种请求方式

通过rest风格占位符方式,利用@PathVariable注解将占位符的值赋给调用方法参数,GET请求方式

@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
    public String testRest(@PathVariable("id") Integer id) {
        System.out.println("testRest get " + id);
        return SUCCESS;
    }


POST请求方式

 @RequestMapping(value = "/testRest", method = RequestMethod.POST)
    public String testRest() {
        System.out.println("testRest post");
        return SUCCESS;
    }


DELETE请求方式

 @RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
    public String testRestDelete(@PathVariable Integer id) {
        System.out.println("testRestDelete " + id);
        return SUCCESS;
    }

PUT请求方式

 @RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
    public String testRestPut(@PathVariable Integer id) {
        System.out.println("testRestPut " + id);
        return SUCCESS;
    }
  1. 上面有些请求路径是一样的,比如delete请求和get请求,都为springmvc/testRest/1,但是RequestMapping的method属性限制了请求方式,对应的请求方式对应了相应的请求路径
  2. rest url方式试图消除传统的url传递参数的模式
  3. PUT与DELETE请求方式是基于POST请求方式的

  • GET:/xxx/{id} 表示通过id得到一条数据
  • POST:/xxx 表示新增一条数据
  • DELETE:/xxx/{id} 表示通过id删除一条数据
  • PUT:/xxx/{id} 表示通过id修改一条数据

GET,POST,DELETE,PUT 刚好对应数据库crud操作


如何使用DELETE,PUT请求方式
<!-- rest风格put 表示修改一条数据-->
<form action="springmvc/testRest/1" method="post">
    <input type="hidden" name="_method" value="PUT"/>
    <input type="submit" value="testRest PUT"/>
</form>

<!-- rest风格delete 表示删除一条数据-->
<form action="springmvc/testRest/1" method="post">
    <input type="hidden" name="_method" value="DELETE"/>
    <input type="submit" value="testRest DELETE"/>
</form>


基于上面的java代码,以及DELETE,PUT请求方式是基于POST请求方式,必须在表单提交中写上一个隐藏域,而且必须将name设置为_method,value属性值写上对应的请求方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值