一、 在HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。
·它们分别对应四种基本操作:
1、GET ====== 获 取资源
2、POST ======新建资源
3、PUT======= 更新资源
4、DELETE==== 删除资源
二、REST:即 Representational State Transfer。(资源)表现层状态转化。是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便, 所以正得到越来越多网站的采用。
我们可以通过rest风格占位符方式,利用@PathVariable注解将占位符的值赋给调用方法参数,实现结果:
/某路径/1 HTTP GET : 得到 id = 1 的 一条数据
/某路径/1 HTTP DELETE: 删除 id = 1的 一条数据
/某路径/1 HTTP PUT: 更新id = 1的 一条数据
/某路径 HTTP POST: 新增一条数据
实现方式(REST风格四种请求方式的调用):
我们通过@RequestMapping映射请求中的method参数实现四种请求方式的调用,以下为示例代码。
GET请求:
1 @RequestMapping(value="/student",method=RequestMethod.GET)
2 public ModelAndView toAddPage(){
3 ModelAndView mView=new ModelAndView();
4 mView.addObject("employee",new Employee());
5 mView.setViewName("add-stu");
6 mView.addObject("departments", departmentDao.getDepartments());
7 return mView;
8 }
POST请求:
1 @RequestMapping(value="/student",method=RequestMethod.POST)
2 public String addStu(Employee employee){
3 employeeDao.save(employee);
4 return "redirect:/show" ;
5 }
DELETE请求:
1 @RequestMapping(value="/student/{id}",method=RequestMethod.DELETE)
2 public String deleteStu(@PathVariable(value="id") Integer id){
3 employeeDao.delete(id);
4 return "redirect:/show" ;
5 }
PUT请求:
1 @RequestMapping(value="/student",method=RequestMethod.PUT)
2 public String Update(@RequestParam(value="id")Integer id,Employee employee){
3 employeeDao.save(employee);
4 return "redirect:/show" ;
5 }
三、将POST请求转化为put请求和delele请求
1.在web.xml文件中配置HiddenHttpMethodFilter过滤器:
1 <!-- HiddenHttpMethodFilter过滤器可以将POST请求转化为put请求和delete请求! -->
2 <filter>
3 <filter-name>hiddenHttpMethodFilter</filter-name>
4 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
5 </filter>
6 <filter-mapping>
7 <filter-name>hiddenHttpMethodFilter</filter-name>
8 <url-pattern>/*</url-pattern>
9 </filter-mapping>
2.在表单域中需要携带一个name值为_method,value值为put或者delete的参数,如下所示:
1 <form action="" method="post">
2 <input type="hidden" name="_method" value="delete">
3 </form>
1 <form:form action="${pageContext.request.contextPath}/student" method="post" modelAttribute="employee">
2 <c:if test="${empty employee.id }">
3 姓名:<form:input path="lastName"/><br>
4 </c:if>
5 <c:if test="${!empty employee.id }">
6 姓名:<form:input path="lastName" readonly="true"/><br>
7 <form:hidden path="id"/>
8 <input type="hidden" name="_method" value="put">
9 </c:if>
10 邮箱:<form:input path="email"/><br>
11 <%
12 Map<String,Object>map=new HashMap<String,Object>();
13 map.put("1","Male");
14 map.put("0", "Female");
15 request.setAttribute("genders", map);
16 %>
17 性别:<form:radiobuttons path="gender" items="${genders}"/><br>
18 部门:<form:select path="department.id" items="${departments}" itemValue="id" itemLabel="departmentName"></form:select><br>
19 <input type="submit" value="提交">
20 </form:form>
最后在Controller层调用即可。根据@RequestMapping的value值以及携带的参数、请求方式查找匹配函数。
SpringMVC的REST风格的四种请求方式
最新推荐文章于 2025-03-16 23:28:58 发布