springmvc-2

RESTful風格 將請求信息與狀態關聯

  • /order/1 HTTP GET :得到id = 1 的 order
  • /order/1 HTTP DELETE: 刪除 id=1 的order
  • /order/1 HTTP PUT : 更新id = 1的 order
  • /order/1 HTTP POST : 新增 order
    通過修改http的狀態值來標記請求的目的
    Spring中實現RESTful風格

HiddenHttpMethodFilter:瀏覽器form表單只支持GET和POST,不支持DELETE和PUT請求,
Spring添加了一個過濾器,可以將這些請求轉換爲標準的http方法,支持GET,POST,DELETE,PUT請求!

web.xml添加HiddenHttpMethodFilter配置

HiddenHttpMethodFilter org.springframework.web.filter.HiddenHttpMethodFilter HiddenHttpMethodFilter /*

需要注意: 由於doFilterInternal方法只對method爲post的表單進行過濾,所以在頁面中必須如下設置:

  <form action="..." method="post">  
         <input type="hidden" name="_method" value="put" />  
  </form>  

代表post請求,但是HiddenHttpMethodFilter將把本次請求轉化成標準的put請求方式! name="_method"固定寫法!

<html>

<body>
<h2>Hello World!</h2>

<script type="text/javascript">
        function a(){
            //設置表單的action值
            document.forms[0].action="test";
            // document.getElementById("txt").value("post");
            document.forms[0].submit();
        }
        function b() {
            //設置表單的action值
            document.forms[0].action = "test/1";
            document.getElementById("txt").value="put";
            document.forms[0].submit();
        }

            function c(){
//設置表單的action值
                document.forms[0].action="test/1";
                document.getElementById("txt").value="delete";
                document.forms[0].submit();
            }
            function d(){
//設置表單的action值
                location.href="test/1";
              //  document.forms[0].action="test/1";
               // document.getElementById("txt").value("get");
               // document.forms[0].submit;
            }
</script>


    <span onclick="a()">insert</span><br>       <%--test--%>
    <span onclick="b()">update</span><br>       <%--test/1--%>
    <span onclick="c()">delete</span>
    <span onclick="d()">select</span>

    <form method="post">
    <input type="hidden" id= "txt" name="_method" value="POST"/>

    </form>

    </body>
</html>

Test

@Controller
public class TestRestful {

    @RequestMapping(value = "test", method = RequestMethod.POST)
    public String  test1(){
        System.out.println("insert   --");
        return "insert";
    }

    @RequestMapping( value = "test/{id}", method = RequestMethod.PUT)
    public String  test2(@PathVariable("id") int uid ){
        System.out.println("update   --");
        return "update";
    }

    @RequestMapping(value = "test/{id}", method = RequestMethod.DELETE)
    public String  test3(@PathVariable("id") int uid ){
        System.out.println("delete   --");
        return "delete";
    }
    @RequestMapping(value = "test/{id}",method = RequestMethod.GET)
    public String  test4(@PathVariable("id") int uid ){
        System.out.println("select");
        return "select";
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章