springMVC restful风格

我的未来我决定 提交于 2019-12-09 01:42:03

RESTful简介

1.REST架构是一个抽象的概念,目前主要是基于HTTP协议实现,其目的是为了提高系统的可伸缩性,降低应用之间的耦合度,便于框架分布式处理程序。

2.REST主要对以下两方面进行了规范

-定位资源的URL风格,例如

 http://baidu.com/admin/1234

 http://baidu.com/admin/1234/10/11

-如何对资源操作

 采用HTTP协议规定的GET、POST、PUT、DELETE动作处理资源的增删该查操作

 

3.什么是RESTful?

 -符合REST约束风格和原则的应用程序或设计就是RESTful.

 eg:  /emp/1  HTTP GET      查询id=1的emp

       /emp/1  HTTP DELETE    删除id=1的emp,实验中直接删除会报405错误,但是采用$.ajax异步删除就没问题

       /emp/1  HTTP PUT    更新emp

       /emp/add  HTTP POST     新增emp

4.Spring对RESTful的支持

- Spring MVC 对 RESTful应用提供了以下支持

- 利用@RequestMapping 指定要处理请求的URI模板和HTTP请求的动作类型

- 利用@PathVariable讲URI请求模板中的变量映射到处理方法参数上

- 利用Ajax,在客户端发出PUT、DELETE动作的请求

具体例子

浏览器 form 表单只支持 GET 与 POST 请求,(官网:www.fhadmin.org) 而DELETE、PUT 等 method 并不支 持,Spring3.0  添加了一个过滤器----HiddenHttpMethodFilter,

可以将这些请求转换 为标准的 http 方法,使得支持 GET、POST、PUT 与 DELETE 请求。

在web.xml中配置

 <!-- configure the HiddenHttpMethodFilter,convert the post method to put or delete -->
  <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>

 

查询

先在index.jsp上放上两个超链接, 用于获取所有员工数据, 访问emps是通过get请求

  <body>
    <a href="emps">list all employees</a> <br>
  </body>

应控制器的方法如下,@RequestMapping 默认的请求方式是get, 所以method参数可以不用写

    @RequestMapping("/emps", method=RequestMethod.GET)
    public String list(Map<String, Object> map){
        map.put("employees", employeeDao.getAll());
        return "list";
    }

用map数据模型存储员工信息 然后带入到list.jsp页面上,在WEB-INF/view目录下创建list.jsp

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<head>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
</script>
<title></title>
</head>
<body>
    <div>
        <c:if test="${empty requestScope.employees }">
            没有员工信息
        </c:if>
        <c:if test="${!empty requestScope.employees }">
            <table border="1" >
                <tr>
                    <th>ID</th>
                    <th>lastName</th>
                    <th>email</th>
                    <th>gender</th>
                    <th>department</th>
                    <th>edit</th>
                    <th>delete</th>
                </tr>

                <c:forEach items="${requestScope.employees }" var="emp">
                    <tr>
                        <td>${emp.id }</td>
                        <td>${emp.lastName }</td>
                        <td>${emp.email }</td>
                        <td>${emp.gender == 0 ? 'Female' : 'Male' }</td>
                        <td>${emp.department.departmentName }</td>
                        <td><a href="">Edit</a></td>
                        <!-- 因为a标签是get请求, 要转成Delete请求, 可以使用jquery -->
                        <td><a class="delete" href="">Delete</a></td>
                    </tr>
                </c:forEach>
            </table>
        </c:if>
    </div>
</body>
</html>

显示如下: 
这里写图片描述

删除

接着做删除,给list.jsp添加删除请求的地址: 
<a class="delete" href="emp/${emp.id }">Delete</a>

开始的时候说了restful风格 用来删除资源的请求是DELETE,DELETE请求是由POST改造成的, 而现在是GET请求,现在要做的是把这get请求改成post请求 ,然后在改造成delete请求, 操作方法是当点击删除链接时, 通过jquery提交一个我们从新生成的form表单,在这个form表单上添加隐藏域标识这个表单是由post改成delete请求,给web.xml中配置的HiddenHttpMethodFilter类处理。

在list.jsp中创建一个新的表单, action先不写, 等会通过jquery进行修改, 添加隐藏域, name和value的值必须正确填写(固定的)

        <form action="" method="post">
            <input type="hidden" name="_method" value="DELETE"/>
        </form>

js如下: 获取请求地址并提交

    $(function(){
        $(".delete").click(function(){
            var href = $(this).attr("href");
            $("form").attr("action", href).submit();
            return false;
        })
    })

对应控制器的方法如下, 指定method为DELETE, 这样删除的请求才会找到这个方法

    @RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

新增

完成了删除在来写新增, 在index.jsp 添加进入新增界面的入口

  <body>
    <a href="emps">list all employees</a> <br>
    <a href="emp">add new employees</a> <br>
  </body>

请求emp对应的控制器方法;

    @RequestMapping(value="/emp", method=RequestMethod.GET)
    public String input(Map<String, Object> map){
        map.put("departments", departmentDao.getDepartments());
        map.put("employee", new Employee()); 
        return "input";
    }

接着在views目录下创建input.jsp, 这个界面作为新增和修改同时使用, 当id存在时, 表示是修改操作,添加隐藏域将表单标记为PUT。 当id不存时, 是新增操作,保持post提交

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<head>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
    <div>
        <form:form action="${pageContext.request.contextPath }/emp" method="post" modelAttribute="employee" >
            <c:if test="${employee.id == null }">
                <!-- 新增 -->
                lastName: <form:input path="lastName" /><br/>
            </c:if>
            <c:if test="${employee.id != null }">
                <!--修改-->
                <form:hidden path="id" />
                <input type="hidden" name="_method" value="PUT" />
            </c:if>

            email: <form:input path="email" /><br/>
            <%
                Map<String , String> genders = new HashMap<String , String>();
                genders.put("1", "male");
                genders.put("0", "female");
                request.setAttribute("genders",genders); //必须放在域对象中,才可以被${}访问到
            %>
            gender:<form:radiobuttons path="gender" items="${genders }" /><br/>
            department:<form:select path="department.id" items="${departments }" itemLabel="departmentName" itemValue="id"></form:select><br/>
            <input type="submit" />
        </form:form>
    </div>
</body>
</html>

emp对应的新增方法,post请求, 新增完成后重定向到员工列表

    @RequestMapping(value="/emp", method=RequestMethod.POST)
    public String save(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

修改

完成了新增操作, 再到list.jsp中, 将编辑链接添加请求地址 

修改请求的方法, 如下, 将值带到input.jsp界面

    @RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
    public String input(@PathVariable("id") Integer id ,Map<String, Object> map){
        map.put("departments", departmentDao.getDepartments());
        map.put("employee", employeeDao.get(id));
        return "input";
    }

此时进入了input.jsp页面, 其中的

            <c:if test="${employee.id != null }">
                <form:hidden path="id" />
                <input type="hidden" name="_method" value="PUT" />
            </c:if>

条件成立, 当提交表单时, 将以PUT的方式请求 , 对应控制器方法如下

    @RequestMapping(value="/emp", method=RequestMethod.PUT)
    public String update(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!