백엔드/Java

스프링 RestuFul API 에서 PUT / DELETE 메소드 가능하게 하는방법

david100gom 2024. 3. 20. 13:40

첫번째,  web.xml 에 아래의 설정을 추가한다.

<!-- HTML에서 PUT, DELETE 사용가능하게 해주는 필터  _method  파라미터를 -->
<filter>
   <filter-name>httpMethodFilter</filter-name>
   <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
 
<filter-mapping>
   <filter-name>httpMethodFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

두번째, Html 코드상에서  아래와 같이 설정한다. (ajax, 일반 html 2가지 방법)

<html xmlns="http://www.w3.org/1999/html">
<script src="http://static.instarwaz.com/shop/assets/js/core/jquery.min.js"></script>
<script>
    function putTest() {
        $.ajax({
                   cache: false,
                   url: "/sandbox/put",
                   type: "PUT",
                   dataType: "json",
                   success: function (data) {
 
                   },
                   error: function (xhr, status, error) {
 
                   }
               });
    }
 
    function deleteTest() {
        $.ajax({
           cache: false,
           url: "/sandbox/delete",
           type: "DELETE",
           dataType: "json",
           success: function (data) {
 
           },
           error: function (xhr, status, error) {
 
           }
       });
    }
 
 
</script>
PUT : <form action="/sandbox/put" method="post">
    <input type="text" name = "_method" value="put">
    <input type="submit"/>
</form>
DELETE : <form action="/sandbox/delete" method="post">
    <input type="text" name = "_method" value="delete">
    <input type="submit"/>
</form>
 
AJAX PUT Test
<a href="javascript:putTest();">AJAX PUT TEST</a>
 
AJAX DELETE Test
<a href="javascript:deleteTest();">AJAX DELETE TEST</a>
</html>