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

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM