浏览器form只支持GET和POST请求,尔DELETE和PUT请求并不支持,Spring3.0开始添加了HiddenHttpMethodFilter过滤器,可以将这些请求转换为标准的http方法,使得支持GET、POST、PUT和DELETE请求。
SpringMVC发送rest风格的PUT和DELETE请求
1、配置HiddenHttpMethodFilter:在web.xml中配置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>
2、发送Post请求,并携带name=“_method”,value值为PUT或DELETE的隐藏请求域:
<form action="helloworld/1" method="post">
<input name="_method" type="hidden" value="DELETE" />
<input type="submit" value="delete请求测试" />
</form>
<form action="helloworld/2" method="post">
<input name="_method" type="hidden" value="PUT" />
<input type="submit" value="put请求测试" />
</form>
3、控制器中使用@PathVariable注解解析请求携带的参数
package com.gisxx.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;
@Controller
public class HelloWorld {
@RequestMapping(value="/helloworld/{id}",method=RequestMethod.PUT)
public String testPut(@PathVariable Integer i){
System.out.println("发送PUT请求:"+i);
return "success";
}
@RequestMapping(value="/helloworld/{id}",method=RequestMethod.DELETE)
public String testDelete(@PathVariable Integer i){
System.out.println("发送DELETE请求:"+i);
return "success";
}
}
@PathVariable可以将请求url中的占位符转化为方法可用的参数,这对SpringMVC向REST目标挺进发展具有里程碑意义
关注微信公众号GISXXCOM,GET更多技能