springmvc實現REST中的GET、POST、PUT和DELETE

spring mvc 支持REST風格的請求方法,GET、POST、PUT和DELETE四種請求方法分別表明了數據庫CRUD中的select、insert、update、delete,下面演示一個簡單的REST實現過程。html

package me.elin.rect;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/rest")
public class RESTMethod {
    private static final String SUCCESS = "success";

    // 該方法接受POST傳值,請求url爲/rest/restPost
    @RequestMapping(value = "restPost", method = RequestMethod.POST)
    public String restPost(@RequestParam(value = "id") Integer id) {
        System.out.println("POST ID:" + id);
        return SUCCESS;
    }

    // 該方法接受GET傳值,請求url爲/rest/restGet
    @RequestMapping(value = "/restGet", method = RequestMethod.GET)
    public String restGet(@RequestParam(value = "id") Integer id) {
        System.out.println("GET ID:" + id);
        return SUCCESS;
    }

    // 該方法接受PUT傳值,請求url爲/rest/restPut
    @RequestMapping(value = "/restPut", method = RequestMethod.PUT)
    public String restPut(@RequestParam(value = "id") Integer id) {
        System.out.println("PUT ID:" + id);
        return SUCCESS;
    }

    // 該方法接受DELETE傳值,請求url爲/rest/restDelete
    @RequestMapping(value="/restDelete",method=RequestMethod.DELETE)
    public String restDelete(@RequestParam(value = "id") Integer id) {
        System.out.println("DELETE ID:" + id);
        return SUCCESS;
    }
}
  • 在web.xml中添加一個filter,用來過濾rest中的方法。代碼以下
<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>
  • 在WebContent下建立index.jsp文件,添加以下內容
<a href="rest/restGet?id=1">發送GET請求</a>

<form action="rest/restPost" method="post">
    <input type="text" name="id" value="2"/>
    <input type="submit" value="發送POST請求"/>
</form>

<form action="rest/restPut" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="text" name="id" value="3">
    <input type="submit" value="發送PUT請求">
</form>


<form action="rest/restDelete" method="post">
    <input type="hidden" name="_method" value="DELETE">
    <input type="text" name="id" value="4">
    <input type="submit" value="發送DELETE請求">
</form>

其中get和post方法是html中自帶的,可是不支持PUT和DELETE方法,因此須要經過POST方法模擬這兩種方法,只須要在表單中添加一個隱藏域,名爲_method,值爲PUT或DELETE。數據庫

  • 運行程序,index.jsp中一個超連接和三個表單分別表示了四種請求方法。
相關文章
相關標籤/搜索