首页 > 代码库 > springmvc 对REST风格的支持

springmvc 对REST风格的支持

1、PathVariable注解

用于映射url的占位符到目标方法的参数中

例子:

 

@RequestMapping("/testPathVariable/{id}")

public String testPathVariable(@PathVariable("id") Integer id) {

syso (id);

}

 

请求:/testPathVariable/101 输出:101

 

2、REST请求示例:

/order  HTTP POST --新增

/order/1  HTTP DELETE --删除

/order/1  HTTP PUT --修改

/order/1  HTTP GET --查看

 

3、如何发送一个PUT和DELETE请求

1)在web.xml中配置一个filter HiddenHttpMethodFilter。

2)发送一个POST请求

3)在请求参数中放入_method = DELETE 或PUT

 

配置:

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

controller:

@RequestMapping(value="http://www.mamicode.com/order/{id}",method=RequestMethod.GET)
    public String testGet(@PathVariable Integer id) {
        System.out.println("testGet id=" + id);
        return SUCCESS;
    }
    
    
    @RequestMapping(value="/order",method=RequestMethod.POST)
    public String testPOST() {
        System.out.println("testPOST");
        return SUCCESS;
    }
    
    
    @RequestMapping(value="/order/{id}",method=RequestMethod.PUT)
    public String testPUT(@PathVariable Integer id) {
        System.out.println("testPUT id=" + id);
        return "redirect:/success.jsp";
    }
    
    @RequestMapping(value="/order/{id}",method=RequestMethod.DELETE)
    public String testDELETE(@PathVariable Integer id) {
        System.out.println("testDELETE id=" + id);
        return "redirect:/success.jsp";
    }

测试:

<br>
<br>
<a href="test/order/11">test testGET</a>
<br>
<br>
<form action="test/order" method="post">
    <input type="submit" value="testPost">
</form>


<br>
<br>
<form action="test/order/11" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="submit" value="testPUT">
</form>


<br>
<br>
<form action="test/order/11" method="post">
    <input type="hidden" name="_method" value="DELETE">
    <input type="submit" value="testDELETE">
</form>

 

注意tomcat8报错:

HTTP Status 405 - JSPs only permit GET POST or HEAD

1、使用低版本tomcat

2、在返回时使用重定向:return "redirect :/test.jsp"

3、写一个Filter来包装HttpRequest中的getMethod()方法

 

springmvc 对REST风格的支持