【知识整理】SpringMVC-REST风格CRUD

来源:互联网 发布:淘宝宝贝搜索排名 编辑:程序博客网 时间:2024/05/26 07:28
一.POST、PUT、DELETE,他们分别对应四种基本操作,GET用来获取资源,POST用来新建资源,PUT用来更新资源,DELETE用来删除资源。
1.HiddenHttpMethodFiter:浏览器表单只支持GET与POST请求,而DELETE\PUT等method不支持,Spring3.0添加一个过滤器,可以将这些请求转为标准的http方法,使得支持GET\POST\PUT\DELETE请求。
2.REST风格URL
①新增: 例: /order/ POST请求URL
②获取: 例:/order/1 GET请求URL
③更新: 例:/order/1 PUT请求URL
④删除: 例:/order/1 DELETE请求URL
2.如何发送PUT和DELETE请求
(1)配置HiddenHttpMethodFilter
(2)需要发送POST请求
(3)在发送POST请求时,携带一个隐藏域name="_method" value="DELETE/PUT"
3.在SpringMVC中如何得到id?

(1)在目标方法中使用@PahtVariable注解

二.发送PUT、DELETE请求

1.(1)web.xml中加入如下配置:

//配置HiddenHttpMethodFilter,可以把POST请求转为DELETE或PUT请求

<filter><filter-name>HiddenHttpMethodFiter</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)SpringMVC配置文件中:配置视图解析器,如何把handler方法返回值解析为实际的物理视图

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/"></property><property name="suffix" value=".jsp"></property></bean>

2.发送GET请求:

(1)控制器类中:

@RequestMapping(value="/testRest/{id}", method=RequestMethod.PUT)public String testRestPut(@PathVariable("id") Integer id){System.out.println("test REST PUT");return "hello";}
(3)jsp文件中:

<form action="/springMVC/springmvc/testRest/1" method="post"><input type="hidden" name="_method" value="PUT"/><input type="submit" value="test REST PUT"/></form>

3.发送DELETE请求:
(1)控制器类中:

@RequestMapping(value="/testRest/{id}", method=RequestMethod.DELETE)public String testRestDelete(@PathVariable("id") Integer id){System.out.println("test REST DELETE");return "hello";}
(2)jsp文件中:

<form action="/springMVC/springmvc/testRest/1" method="post"><input type="hidden" name="_method" value="DELETE"/><input type="submit" value="test REST DELETE"/></form>





1 0