• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

认识RESTFul

武飞扬头像
菜鸟小小晨
帮助1

认识RESTful

REST全称:Representational State Transfer(表现层资源状态转移)

资源

资源是一种看待服务器的方式,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个
可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、
数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端
应用开发者能够理解。与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词。一个
资源可以由一个或多个URI来标识。URI既是资源的名称,也是资源在Web上的地址。对某个资源感兴
趣的客户端应用,可以通过资源的URI与其进行交互。

资源的表述

资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交
换)。资源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等。资源的表述格
式可以通过协商机制来确定。请求-响应方向的表述通常使用不同的格式。

状态转移

状态转移说的是:在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资
源的表述,来间接实现操作资源的目的。

如何实现RESTFul

学新通

GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE
用来删除资源。

HiddenHttpMethodFilter

SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们将 POST 请求转换为 DELETE 或 PUT 请求
HiddenHttpMethodFilter 处理put和delete请求的条件:
1、当前请求的请求方式必须为post
2、当前请求必须传输请求参数_method
满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求的请求方式转换为请求参数
_method的值,因此请求参数_method的值才是最终的请求方式

<!--在web.xml中注册HiddenHttpMethodFilter-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filterclass>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

目前为止,SpringMVC中提供了两个过滤器:CharacterEncodingFilter和
HiddenHttpMethodFilter
在web.xml中注册时,必须先注册CharacterEncodingFilter,再注册HiddenHttpMethodFilter

RESTful案例

结构

学新通

构建Maven

学新通
学新通
学新通
学新通
学新通

导入Jar包

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.18</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
      <version>3.0.12.RELEASE</version>
    </dependency>
  </dependencies>
学新通

配置web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--请求处理put和delete的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>

    <!--springMVC前端控制器DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
学新通

配置springMVC.xml

学新通

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启组件扫描-->
    <context:component-scan base-package="com.zsc.rest"/>
    <!--配置视图解析器-->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                     </bean>
                </property>
            </bean>
        </property>
    </bean>
    <!--视图控制器-->
    <mvc:view-controller path="/" view-name="index"/>
    <mvc:view-controller path="/toAdd" view-name="emp_add"/>
    <!--开放对静态资源的访问-->
    <mvc:default-servlet-handler/>
    <!--开启mvc注解驱动-->
    <mvc:annotation-driven/>
</beans>
学新通

创建实体类

public class Emp {
    private Integer id;
    private String name;
    private String email;
    private String gender;

    public Emp() {
    }

    public Emp(Integer id, String name, String email, String gender) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.gender = gender;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}


学新通

创建测试数据

@Repository
public class EmpDao {

    private static Map<Integer, Emp> employees = null;
    static{
        employees = new HashMap<Integer, Emp>();
        employees.put(1, new Emp(1, "test1", "1@qq.com", "男"));
        employees.put(2, new Emp(2, "test2", "2@qq.com", "男"));
        employees.put(3, new Emp(3, "test3", "3@qq.com", "女"));
        employees.put(4, new Emp(4, "test4", "4@qq.com", "女"));
        employees.put(5, new Emp(5, "test5", "5@qq.com", "女"));
    }
    private static Integer initId = 6;
    public void save(Emp employee){
        if(employee.getId() == null){
            employee.setId(initId  );
        }
        employees.put(employee.getId(), employee);
    }
    public Collection<Emp> getAll(){
        return employees.values();
    }
    public Emp get(Integer id){
        return employees.get(id);
    }
    public void delete(Integer id){
        employees.remove(id);
    }
}
学新通

创建控制器

@Controller
public class EmpController {

    @Autowired
    private EmpDao empDao;

    @RequestMapping(value = "/emp",method = RequestMethod.GET)
    public String getAllEmp(Model model) {
        Collection<Emp> empList = empDao.getAll();
        model.addAttribute("empList", empList);
        return "emp_list";
    }
    
	@RequestMapping(value = "/emp/{id}",method = RequestMethod.DELETE)
    public String deleteEmp(@PathVariable("id") Integer id) {
        empDao.delete(id);
        return "redirect:/emp";
    }

    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    public String addEmp(Emp emp) {
        empDao.save(emp);
        return "redirect:/emp";
    }
    
	@RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    public String getEmpById(@PathVariable("id") Integer id,Model model) {
        Emp emp = empDao.get(id);
        model.addAttribute("emp",emp);
        return "emp_update";
    }
    
    @RequestMapping(value = "/emp",method = RequestMethod.PUT)
    public String updateEmp(Emp emp) {
        empDao.save(emp);
        return "redirect:/emp";
    }
}
学新通

编写数据显示页面emp_list

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <table id="dataTable" border="1" cellspacing="0" cellpadding="0" style="text-align: center">
        <tr>
            <th colspan="6">员工信息</th>
        </tr>
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>性别</th>
            <th colspan="3">操作</th>
        </tr>
        <!--报错不用管照样能出来数据-->
        <tr th:each="emp : ${empList}">
            <td th:text="${emp.id}"></td>
            <td th:text="${emp.name}"></td>
            <td th:text="${emp.email}"></td>
            <td th:text="${emp.gender}"></td>
            <td>
                <a th:href="@{/toAdd}">添加</a>
                <a @click="deleteEmp" th:href="@{|/emp/${emp.id}|}">删除</a>
                <a th:href="@{|/emp/${emp.id}|}">修改</a>
            </td>
        </tr>
    </table>
    <form id="deleteForm" method="post">
        <input type="hidden" name="_method" value="delete">
    </form>
<script th:src="@{/static/js/vue.js}"></script>
<script>
    var vue = new Vue({
        el:"#dataTable",
        methods:{
            deleteEmp:function (event) {
                //根据id获取表单元素
                var deleteForm = document.getElementById("deleteForm");
                //将触发点击事件的超链接的href属性赋值给表单的action
                deleteForm.action = event.target.href;
                //提交表单
                deleteForm.submit();
                //取消超链接的默认行为
                event.preventDefault();
            }
        }
    });
</script>
</body>
</html>
学新通

如果上面报错看着不舒服可以设置一下
学新通

编写添加页面emp_add

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>emp_add</title>
</head>
<body>

<form th:action="@{/emp}" method="post">
    姓名:<input type="text" name="name"><br>
    邮箱:<input type="text" name="email"><br>
    性别:<input type="radio" name="gender" value="男">男
        <input type="radio" name="gender" value="女">女<br>
    <input type="submit" value="添加"><br>

</form>

</body>
</html>
学新通

编写修改页面emp_update

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>emp_update</title>
</head>
<body>

<form th:action="@{/emp}" method="post">
    <input type="hidden" name="_method" value="put">
    <input type="hidden" name="id" th:value="${emp.id}">
    姓名:<input type="text" name="name" th:value="${emp.name}"><br>
    邮箱:<input type="text" name="email" th:value="${emp.email}"><br>
    性别:<input type="radio" name="gender" value="男" th:field="${emp.gender}">男
        <input type="radio" name="gender" value="女" th:field="${emp.gender}">女<br>
    <input type="submit" value="修改"><br>

</form>

</body>
</html>
学新通

完结

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgeihec
系列文章
更多 icon
同类精品
更多 icon
继续加载