RESTFul:RESTful简介、RESTful的实现、RESTFul案例

一、RESTful简介

REST:Representational State Transfer,表现层资源状态转移。

1.资源

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

2.资源的表述

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

3.状态转移

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

二、RESTful的实现

具体说,就是HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。

它们分别对应四种基本操作:GET用来获取资源,POST用来新建资源,PUT用来更新资源,DELETE用来删除资
源。

REST风格提倡URL地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求
参数,而是将要发送给服务器的数据作为URL地址的一部分,以保证整体风格的一致性。

操作传统方式REST风格
查询操作getUserById?id=1user/1–>get请求方式
保存操作saveUseruser–>post请求方式
删除操作deleteUser?id=1user/1–>delete请求方式
更新操作updateUseruser–>put请求方式

1.post与get

前端:

<a th:href="@{/user}">查询所有用户</a><br/>

<a th:href="@{/user/1}">根据id查询用户</a><br/>

<form th:action="@{/user}" method="post">
    <input name="username" type="text" value="admin">
    <input name="password" type="password" value="123456">
    <input type="submit" value="添加用户"/>
</form><br/>

后端:

    /*
    /user/1-->get 根据id查找user
    /users-->get  查询所有用户信息
    /user/1-->DELETE 根据id删除用户信息
    /user-->PUT  修改用户信息
    /user-->POST  新增用户信息
     */
    @PostMapping("/user")
    public String addUser(String username,String password) {
        System.out.println("username:"+username+",password:"+password);
        System.out.println("添加用户");
        return "success";
    }

    @GetMapping("/user")
    public String queryUserList() {
        System.out.println("查询所有用户");
        return "success";
    }

    @GetMapping("/user/{id}")
    public String queryUserById(@PathVariable("id") String id) {
        System.out.println("查询id为"+id+"的用户");
        return "success";
    }

2.put与delete

需要在web.xml中添加一个过滤器HiddenHttpMethodFilter,其核心代码如下:

使用时必须满足两个条件:

1、必须为post请求

2、必须包含隐藏域_methed,其value对应PUT、DELETE、PATCH

@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		HttpServletRequest requestToUse = request;

		if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
			String paramValue = request.getParameter(this.methodParam);
			if (StringUtils.hasLength(paramValue)) {
				String method = paramValue.toUpperCase(Locale.ENGLISH);
				if (ALLOWED_METHODS.contains(method)) {
					requestToUse = new HttpMethodRequestWrapper(request, method);
				}
			}
		}

		filterChain.doFilter(requestToUse, response);
	}

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <!--解决post乱码问题-->
    <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请求的问题,处理编码的过滤器一定要在最前面,否则会失效-->
    <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的前端控制器,对浏览器所发送的请求统一进行处理
        在此配置下,springMVC的配置文件具有默认的位置和名称
        默认的位置:WEB-INF
        默认的名称:<servlet-name>-servlet.xml
        若要为springMVC的配置文件设置自定义的位置和名称
        需要在servlet标签中添加init-param
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        load-on-startup:将前端控制器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>

前端:

<form th:action="@{/user}" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="text" name="username" value="abc">
    <input type="text" name="password" value="123456">
    <input type="submit" value="修改用户"/>
</form>
<br/>

<form th:action="@{/user/1}" method="post">
    <input type="hidden" name="_method" value="delete">
    <input type="submit" value="删除用户"/>
</form>
<br/>

后端:

@PutMapping("/user")
    public String alterUser(String username,String password) {
        System.out.println("username:"+username+",password:"+password);
        System.out.println("修改用户");
        return "success";
    }

    @DeleteMapping("/user/{id}")
    public String deleteUser(@PathVariable("id") String id) {
        System.out.println("删除id为"+id+"的用户");
        return "success";
    }

三、RESTFul案例

1.thymelaf遍历集合与拼接id

<table id="employeeTable">
    <tr th:colspan="5">
        <th>员工信息表</th>
    </tr>
    <tr>
        <th>id</th>
        <th>lastName</th>
        <th>email</th>
        <th>gender</th>
        <th><a th:href="@{/toAddEmp}">addEmp</a></th>
    </tr>
    <!--遍历集合-->
    <tr th:each="emp:${empList}">
        <td th:text="${emp.id}"></td>
        <td th:text="${emp.lastName}"></td>
        <td th:text="${emp.email}"></td>
        <td th:text="${emp.gender}"></td>
        <!--拼接id-->
        <td><a th:href="@{'/employee/'+${emp.id}}">update</a></td>
        <td><a @click="deleteEmployee" th:href="@{'/employee/'+${emp.id}}">delete</a></td>
    </tr>
</table>

2.超链接get请求变post请求

    <tr th:each="emp:${empList}">
        <td th:text="${emp.id}"></td>
        <td th:text="${emp.lastName}"></td>
        <td th:text="${emp.email}"></td>
        <td th:text="${emp.gender}"></td>
        <td><a th:href="@{'/employee/'+${emp.id}}">update</a></td>
        <td><a @click="deleteEmployee" th:href="@{'/employee/'+${emp.id}}">delete</a></td>
    </tr>
</table>

<form method="post" id="deleteEmployeeForm">
    <input type="hidden" name="_method" value="delete">
</form>

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript">
    var vue = new vue({
        el: "#employeeTable",
        methods: {
            deleteEmployee: function (event) {
                //获取form表单
                var deleteEmployeeForm = document.getElementById("deleteEmployeeForm");
                //将delete表单的href内容给form表单的action赋值
                deleteEmployeeForm.action = event.target.href;
                //提交表单
                deleteEmployeeForm.submit();
                //取消默认行为
                event.preventDefault();
            }
        }
    });
</script>

2.后端代码

package com.atguigu.controller;

import com.atguigu.bean.Employee;
import com.atguigu.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;

    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public ModelAndView queryEmployeeList() {
        ModelAndView modelAndView = new ModelAndView();
        Collection<Employee> empList = employeeDao.getAll();
        modelAndView.addObject("empList", empList);
        modelAndView.setViewName("emp_list");
        return modelAndView;
    }

    @RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
    public ModelAndView getEmployeeById(@PathVariable("id") int id) {
        Employee employee = employeeDao.get(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("update_emp");
        modelAndView.addObject("employee", employee);
        return modelAndView;
    }

    @RequestMapping(value = "/employee/{id}", method = RequestMethod.POST)
    public String deleteEmployee(@PathVariable("id") int id) {
        employeeDao.delete(id);
        return "redirect:/employee";
    }

    @RequestMapping("/toAddEmp")
    public String toAddEmp() {
        return "add_emp";
    }

    @RequestMapping("/addEmp")
    public String addEmp(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/employee";
    }

    @PutMapping("/updateEmp")
    public String updateEmp(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/employee";
    }
}

3.配置文件

<?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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--打开组件扫描-->
    <context:component-scan base-package="com"></context:component-scan>
    <!-- 配置Thymeleaf视图解析器 -->
    <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>


    <!--视图控制器view-controller实现页面跳转
    path:请求地址
    view-name:请求地址所对应的视图名称-->
    <mvc:view-controller path="/" view-name="index"/>
    <!--开启mvc注解驱动,不开启超链接会失效-->
    <mvc:annotation-driven/>

    <!--开放对静态资源的访问,先由sprngmvc进行处理,如果找不到再由默认handler处理,如果还是找不到,则报404-->
    <mvc:default-servlet-handler/>
</beans>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值