12.13 REST思想
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package com.runsstudio.springmvc.servlet;
public class RESTControlTest {
@RequestMapping(value = "/{id}",method = RequestMethod.GET) public String queryEmp(@PathVariable("id")String id, Model model){ System.out.println("GET:queryEmp,id="+id); return "success"; }
@RequestMapping(value = "/{id}",method = RequestMethod.POST) public String addEmp(@PathVariable("id")String id, Model model){ System.out.println("POST:addEmp,id="+id); return "success"; }
}
|
/book/1 GET – 获取1号图书
/book/1 PUT – 更新1号图书
/book/1 DELETE – 删除1号图书
/book POST 添加图书
不幸的是 页面上只能发起GET和POST两种请求,其他的请求方式,没办法使用
那我们怎么办呢?
SPRING配置了一个hidden http method FILTER 可以弥补jsp页面不能发这两种请求的缺陷
- web.xml 拦截所有请求 首先配置hidden http method filter
1 2 3 4 5 6 7 8
| <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>
|
- 然后模拟增删改查操作 对于put和delete的 增加一个_method表单项 value 就是put method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <%-- 模拟增删改查操作--%> <form action="${pageContext.request.contextPath}/emp/1" method="get"> <input type="submit" value="提交GET"> </form> <form action="${pageContext.request.contextPath}/emp/1" method="post"> <input type="submit" value="添加1号员工(POST)"> </form><br> <%-- 要一个_method的项--%> <form action="${pageContext.request.contextPath}/emp/1" method="post"> <input name="_method" value="put" > <input type="submit" value="修改1号员工(PUT)"> </form><br> <form action="${pageContext.request.contextPath}/emp/1" method="post"> <input name="_method" value="delete"> <input type="submit" value="删除1号员工(DELETE)"> </form>
|
然后正常写PUT 和delete的控制层代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
@RequestMapping(value = "/{id}",method = RequestMethod.PUT) public String updateEmp(@PathVariable("id")String id, Model model){ System.out.println("PUT:updateEmp,id="+id); return "success"; } @RequestMapping(value = "/{id}",method = RequestMethod.DELETE) public String delEmp(@PathVariable("id")String id, Model model){ System.out.println("DELETE:delEmp,id="+id); return "success"; }
|
最后,对于TOMCAT 8以上的服务器 会限制只能发出GET和POST 请求 发出其他请求会报错,修改的方法:在success.jsp头上加isErrorPage=”true”
1
| <%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
|