Allen_Zsj

导航

SpringMVC PathVariable和post、get、put、delete请求

1、PathVariable 可以映射URL中的占位符到目标方法的参数中。

2、Rest风格的URL

  以CRUD为例:

  新增:/order POST

  修改:/order/id PUT

  获取:/order/id GET

  删除:/order/id DELETE

3、如何发送PUT和DELETE请求?

  1.需要配置HiddenHttpMethodFilter

  2.需要发送POST请求: 

  <form action="springmvc/testRest/1" method="post">
  <input type="hidden" name="_method" value="PUT">
  <input type="submit" value="PUT">
  </form>
  <br/><br/>

  <form action="springmvc/testRest/1" method="post">
  <input type="hidden" name="_method" value="DELETE">
  <input type="submit" value="DELETE">
  </form>
  <br/><br/>

  3.需要发送POST请求时携带一个name="_method"的隐藏域,值为DELETE或PUT

   <input type="hidden" name="_method" value="PUT">

   <input type="hidden" name="_method" value="DELETE">

   4.在SpringMVC的目标方法中需要指定请求的方法,并使用@PathVariable注解获取参数值

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

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

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


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

  

posted on 2017-12-20 11:09  Allen_Zsj  阅读(4738)  评论(0编辑  收藏  举报