@RequestMapping实现RESTful风格的增删改查

1 Http协议定义的操作

Http协议定义了4这种操作方式(CRUD),分别为GET,POST,PUT,DELETE
GET请求用于获取资源
POST请求用于新建资源
PUT请求用于更新资源
DELETE请求用于删除资源
但是超链接用于实现GET请求,表单用于实现POST请求,PUT和DELETE请求如何实现呢?

2 先看看原生javaWeb的执行流程

在这里插入图片描述
在请求时确定了请求方式是GET或者POST;然后请求经过过滤器过滤,最终才能被Servlet接受
所以对所有请求的统一处理过程可以利用过滤器类来实现。

SpringMVC实现了将POST请求转为PUT或者DELETE请求过程的类叫HiddenHttpMethodFilter

3 HiddenHttpMethodFilter的使用

向原生的javaWEB的filter一样配置在web.xml文件中

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

前端页面

<a href="helloworld">GET</a>
    <br/><br/>
    <form action="helloworld" method="post">
        <input type="submit" value="POST">
    </form>
     <br/>
    <form action="helloworld" method="post">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="PUT">
    </form>
     <br/>
    <form action="helloworld" method="post">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="DELETE">
    </form>

在这里插入图片描述
@RequestMapping代码

@Controller
public class Distributor {
    @RequestMapping(value = "/helloworld", method = RequestMethod.GET)
    public String distribute2Success1() {
        System.out.println("GET");
        return "success";
    }
    @RequestMapping(value = "/helloworld", method = RequestMethod.POST)
    public String distribute2Success2() {
        System.out.println("POST");
        return "success";
    }
    @RequestMapping(value = "/helloworld", method = RequestMethod.PUT)
    public String distribute2Success3() {
        System.out.println("PUT");
        return "success";
    }
    @RequestMapping(value = "/helloworld", method = RequestMethod.DELETE)
    public String distribute2Success4() {
        System.out.println("DELETE");
        return "success";
    }
}

这时候点击不同的连接,就会进入不同是我函数体,试想一下结合之前的@PathVariable注解。@RequestParam注解,就可以实现删除,更新等操作,参照https://blog.csdn.net/qq_23937341/article/details/95970359
https://blog.csdn.net/qq_23937341/article/details/95999217

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