欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring mvc rest风格的CRUD

程序员文章站 2022-04-23 15:57:07
...

DELETE:删除  PUT:更新POST:新增  GET:查询

Rest风格的URL 如何发送PUT请求和DELETE请求?

1.需要在web.xml中配置HidenHttpMethodFilter

<!--配置 org.springframework.web.filter.HiddenHttpMethodFilter :可以把post转换为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>

2.需要发送POST请求,需要在发送POST请求时携带一个name=“_method”的隐藏域,值为DELETE或者PUT

<!-- get请求 -->
       <a href="testRest/122">test Rest get</a>

 <!-- DELETE请求 -->

    <form action="testRest/1" method="post">
        <input type="hidden" value="DELETE" name="_method"> <input
            type="submit" value="Test Rest DELETE">
    </form>

<!-- post请求 -->

    <form action="testRest" method="post">
        <input type="submit" value="Test Rest post">
    </form>

<!-- PUT请求 -->

    <form action="testRest/1" method="post">
        <input type="hidden" value="PUT" name="_method"> <input
            type="submit" value="Test Rest put">
    </form>

通过相同的路径名springmvc/testRest  调用不同方法。


   //在springMVC中如何获取id呢? 使用@PathVariable注解
       @RequestMapping(value = "/testRest", method = RequestMethod.POST)
	public String testRest() {
		System.out.println("test Rest post");
		return "success";
	}

	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
	public String testRestDelete(@PathVariable("id") Integer id) {
		System.out.println("test Rest delete" + id);
		return "success";
	}

	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
	public String testRest(@PathVariable("id") Integer id) {
		System.out.println("test Rest GET" + id);
		return "success";
	}

	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
	public String testRestPut(@PathVariable("id") Integer id) {
		System.out.println("test Rest GET" + id);
		return "success";
	}