springmvc之HiddenHttpMethodFilter配置使用REST风格的URL

REST:即资源表现层状态转化。

资源:网络上的一个实体。每种资源对应一个特定的URL。

表现层:把资源具体展现出来的形式,例如文本以txt、html、xml、json或二进制的形式表示。

状态转化:每发出一个请求,就代表了客户端和服务端的一种交互过程,而HTTP请求是无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器端,必须通过某种手段。而这种转化是建立在表现层之上的,所以就是表现层状态转化。具体说,就是HTTP协议里,四个表示操作方式的动词:GET、POST、PUT、DELETE。

以CURD为例,REST风格的URL:

新增:/order Post  

修改:/order/1 Put  以前:update?id=1

删除:/order/1 Delete 以前:selete?id=1

获取:/order/1 Get  以前:get?id=1

如何发送PUT和DELETE请求呢?

(1)需要在web.xml中配置HiddenHttpMethodFilter。

(2)需要发送POST请求。

(3)在发送POST请求时需要发送name="_method"的隐藏域,值为DELETE或PUT。

在springmvc中的目标方法中如何得到发过去的参数,比如id呢?

使用@PathVariable注解。

在web.xml中:

    <!-- 
    配置 org.springframework.web.filter.HiddenHttpMethodFilter 
    -->
    <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>

SpringmvcTest.java

package com.gong.springmvc.handlers;

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

@RequestMapping("/springmvc")
@Controller
public class SpringmvcTest {
    private static final String SUCCESS = "success";
    
    @RequestMapping(value="/testRest/{id}",method=RequestMethod.GET)
    public String testGet(@PathVariable("id") Integer id) {
        System.out.println("get-->"+id);
        return SUCCESS;
    }
    @RequestMapping(value="/testRest",method=RequestMethod.POST)
    public String testPost() {
        System.out.println("post-->");
        return SUCCESS;
    }
    @RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
    public String testPut(@PathVariable("id") Integer id) {
        System.out.println("put-->"+id);
        return SUCCESS;
    }
    @RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
    public String testDelete(@PathVariable("id") Integer id) {
        System.out.println("delete-->"+id);
        return SUCCESS;
    }
}

index.jsp

    <a href="springmvc/testRest/1">Get</a>
    <br><br>
    <form action="springmvc/testRest" method="POST">
        <input type="submit" value="submit">
    </form>
    <br><br>
        <form action="springmvc/testRest/1" method="POST">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="delete">
    </form>
    <br><br>
    <form action="springmvc/testRest/1" method="POST">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="put">
    </form>
    <br><br>

启动ttomcat服务器之后:

点击相应的提交方式:

在控制台会输出:

说明是调用了不同的请求方式 。

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/12177670.html