美文网首页
5.Spring MVC HiddenHttpMethodFil

5.Spring MVC HiddenHttpMethodFil

作者: 765197250c12 | 来源:发表于2017-05-25 19:52 被阅读337次

    HiddernHttpMethodFilter

    HiddernHttpMethodFilter:浏览器表单只支持GET与POST请求,而DELETE、PUT等method并不支持,Spring3.0添加了一个过滤器,可以将这些请求转发为标砖的http方法,支持GET、POST、PUT、DELETE请求
    1.在web.xml中配置

      <!--配置org.springframework.web.filter.HiddenHttpMethodFilter 可以把POST请求转换为DELETE或POST请求-->
      <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>
    

    2index.jsp中加入下面

    <%--HiddenHttpMethodFilter--%>
    
    <form action="controller/testRest/1" method="post">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="TestRest DELETE">
    </form>
    <br><br>
    
    <form action="controller/testRest/1" method="post">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="TestRest PUT">
    </form>
    <br><br>
    
    <form action="controller/testRest" method="post">
        <input type="submit" value="TestRest POST">
    </form>
    
    <a href="controller/testRest/1">Test Rest Get</a>
    

    3.在HelloContoller

      @RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
      public String testRestGet(@PathVariable("id") Integer id) {
        System.out.printf("testRest GET:------>" + id);
        return "Hello";
      }
    
      @RequestMapping(value = "/testRest", method = RequestMethod.POST)
      public String testRestPost() {
        System.out.println("testRest POST");
        return "Hello";
      }
    
     //出现HTTP Status 405 - JSPs only permit GET POST or HEAD.  tomcat8  bug
      @RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
      public String testRestDelete(@PathVariable("id") Integer id) {
        System.out.printf("testRest delete");
        return "Hello";
      }
      //出现HTTP Status 405 - JSPs only permit GET POST or HEAD.  tomcat8  bug
      @RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
      public String testRestPut(@PathVariable("id") Integer id) {
        System.out.printf("testRest put");
        return "Hello";
      }
    

    Rest风格的URL

    已CURD为例:
    新增: /order POST
    修改:/order/1 PUIT update?id =1
    获取:/order/1 GET get?id = 1
    删除:/order/1 DELETE delete?id = 1
    如何发送PUT请求和DELETE请求
    1.配置HiddenHttpMethodFilter
    2.需要发送POST请求
    3.需要在发送POST请求时携带一个name="_method"的隐藏域, 值为DELETE或PUT
    在SPringMVC的目标方法中如何得到id呢:使用@PathVariable注解


    源码:https://github.com/gurongkang/TestSpringMVC.git tag:4

    相关文章

      网友评论

          本文标题:5.Spring MVC HiddenHttpMethodFil

          本文链接:https://www.haomeiwen.com/subject/ikfnxxtx.html