当前位置:   article > 正文

【SpringMVC】| RESTful架构风格、RESTful案例(CRUD)_restful框架

restful框架

目录  

RESTful架构风格

1. RESTful简介

2. RESTful的实现

3. HiddenHttpMethodFilter

RESTful案例(CRUD)

1. 准备工作

2. 功能清单

列表功能(显示数据) 

删除数据(难点)

添加数据 

更新数据

图书推荐:用ChatGPT与VBA一键搞定Excel


RESTful架构风格

1. RESTful简介

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

a>资源

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

b>资源的表述

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

c>状态转移

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

2. RESTful的实现

(1)具体说,就是 HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET 用来获取资源POST 用来新建资源PUT 用来更新资源DELETE 用来删除资源

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

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

3. HiddenHttpMethodFilter

(1)由于浏览器只支持发送get和post方式的请求,那么该如何发送put和delete请求呢SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们将 POST 请求转换为 DELETE 或 PUT 请求!

(2)HiddenHttpMethodFilter 处理put和delete请求的条件

①当前请求的请求方式必须为:post

②当前请求必须传输请求参数:_method(这个参数有三个值:put、delete、patch

(3)满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求的请求方式转换为请求参数_method的值,因此请求参数_method的值才是最终的请求方式。

 在web.xml中注册HiddenHttpMethodFilter

  1. <filter>
  2. <filter-name>HiddenHttpMethodFilter</filter-name>
  3. <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>HiddenHttpMethodFilter</filter-name>
  7. <url-pattern>/*</url-pattern>
  8. </filter-mapping>

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

原因:在 CharacterEncodingFilter 中通过 request.setCharacterEncoding(encoding) 方法设置字符集的;request.setCharacterEncoding(encoding) 方法要求前面不能有任何获取请求参数的操作; 而 HiddenHttpMethodFilter 恰恰有一个获取请求方式的操作:

String paramValue = request.getParameter(this.methodParam);

发送Get、Post、Put、Delete请求实操

前端发送请求:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <!--发送Get请求-->
  9. <a th:href="@{/user}">查询所有用户信息</a><br>
  10. <a th:href="@{/user/1}">根据id查询用户信息</a><br>
  11. <!--发送Post请求-->
  12. <form th:action="@{/user}" method="post">
  13. 用户:<input type="text" name="username"><br>
  14. 密码:<input type="password" name="password"><br>
  15. <input type="submit" name="Post提交"><br>
  16. </form>
  17. <!--发送put请求-->
  18. <form th:action="@{/user}" method="post">
  19. <!--设置隐藏域的请求类型-->
  20. <input type="hidden" name="_method" value="put"><br>
  21. 用户:<input type="text" name="username"><br>
  22. 密码:<input type="password" name="password"><br>
  23. <input type="submit" name="Put提交"><br>
  24. </form>
  25. <!--发送delete请求-->
  26. <form th:action="@{/user/2}" method="post">
  27. <input type="hidden" name="_method" value="delete"><br>
  28. <input type="submit" name="Delete提交"><br>
  29. </form>
  30. </body>
  31. </html>

后端接收请求:

注:执行删除操作时一般都是使用超链接,但是一般都是和Vue或者ajax相关联;这里就是用form表单的形式,但是使用form表单执行删除操作时,不能使用@RequestMappping注解,然后method属性去指定请求的方式(会报错)。直接使用派生注解@DeleteMapping就没事

  1. package com.zl.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.DeleteMapping;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. /**
  8. * 使用Restful模拟用户资源的增删改查
  9. * /user Get 查询所有用户信息
  10. * /user/1 Get 根据用户id查询用户信息
  11. * /user Post 添加用户信息
  12. * /user/1 Delete 根据用户id删除用户信息
  13. * /user Put 修改用户信息
  14. */
  15. @Controller
  16. public class UserController {
  17. @RequestMapping("/")
  18. public String forwardIndex(){
  19. return "index";
  20. }
  21. // 发送Get查询所有
  22. @RequestMapping(value = "/user",method = RequestMethod.GET)
  23. public String getAllUser(){
  24. System.out.println("查询所有用户信息");
  25. return "success";
  26. }
  27. // 发送Get查询一个
  28. @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
  29. public String getUserById(@PathVariable String id){
  30. System.out.println("根据用户id查询用户信息"+id);
  31. return "success";
  32. }
  33. // 发送Post增加
  34. @RequestMapping(value = "/user",method = RequestMethod.POST)
  35. public String insertUser(String username,String password){
  36. System.out.println("成功添加用户:"+username+"密码是:"+password);
  37. return "success";
  38. }
  39. // 发送put修改
  40. @RequestMapping(value = "/user",method = RequestMethod.PUT)
  41. public String putUser(){
  42. System.out.println("修改用户信息");
  43. return "success";
  44. }
  45. // 发送Delete删除
  46. // @RequestMapping(value = "/user/{id}}",method = RequestMethod.DELETE)
  47. @DeleteMapping(value = "/user/{id}")
  48. public String deleteUserById(@PathVariable String id){
  49. System.out.println("根据用户id删除用户信息:"+id);
  50. return "success";
  51. }
  52. }

RESTful案例(CRUD)

1. 准备工作

搭建环境

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>org.example</groupId>
  6. <artifactId>springmvc-thymeleaf-restful</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <packaging>war</packaging>
  9. <name>springmvc-thymeleaf-restful Maven Webapp</name>
  10. <!-- FIXME change it to the project's website -->
  11. <url>http://www.example.com</url>
  12. <properties>
  13. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  14. <maven.compiler.source>1.8</maven.compiler.source>
  15. <maven.compiler.target>1.8</maven.compiler.target>
  16. </properties>
  17. <dependencies>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-webmvc</artifactId>
  21. <version>5.2.5.RELEASE</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>javax.servlet</groupId>
  25. <artifactId>javax.servlet-api</artifactId>
  26. <version>3.1.0</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.thymeleaf</groupId>
  30. <artifactId>thymeleaf-spring5</artifactId>
  31. <version>3.0.10.RELEASE</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>ch.qos.logback</groupId>
  35. <artifactId>logback-classic</artifactId>
  36. <version>1.2.3</version>
  37. </dependency>
  38. </dependencies>
  39. <!--指定资源文件的位置-->
  40. <build>
  41. <resources>
  42. <resource>
  43. <directory>src/main/java</directory>
  44. <includes>
  45. <include>**/*.xml</include>
  46. <include>**/*.properties</include>
  47. </includes>
  48. </resource>
  49. <resource>
  50. <directory>src/main/resources</directory>
  51. <includes>
  52. <include>**/*.xml</include>
  53. <include>**/*.properties</include>
  54. </includes>
  55. </resource>
  56. </resources>
  57. </build>
  58. </project>

web.xml 

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <!--注册过滤器:解决post请求乱码问题-->
  7. <filter>
  8. <filter-name>encode</filter-name>
  9. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  10. <!--指定字符集-->
  11. <init-param>
  12. <param-name>encoding</param-name>
  13. <param-value>utf-8</param-value>
  14. </init-param>
  15. <!--强制request使用字符集encoding-->
  16. <init-param>
  17. <param-name>forceRequestEncoding</param-name>
  18. <param-value>true</param-value>
  19. </init-param>
  20. <!--强制response使用字符集encoding-->
  21. <init-param>
  22. <param-name>forceResponseEncoding</param-name>
  23. <param-value>true</param-value>
  24. </init-param>
  25. </filter>
  26. <!--所有请求-->
  27. <filter-mapping>
  28. <filter-name>encode</filter-name>
  29. <url-pattern>/*</url-pattern>
  30. </filter-mapping>
  31. <!--发送put、delete请求方式的过滤器-->
  32. <filter>
  33. <filter-name>HiddenHttpMethodFilter</filter-name>
  34. <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  35. </filter>
  36. <filter-mapping>
  37. <filter-name>HiddenHttpMethodFilter</filter-name>
  38. <url-pattern>/*</url-pattern>
  39. </filter-mapping>
  40. <!--注册SpringMVC框架-->
  41. <servlet>
  42. <servlet-name>springmvc</servlet-name>
  43. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  44. <!--配置springMVC位置文件的位置和名称-->
  45. <init-param>
  46. <param-name>contextConfigLocation</param-name>
  47. <param-value>classpath:springmvc.xml</param-value>
  48. </init-param>
  49. <!--将前端控制器DispatcherServlet的初始化时间提前到服务器启动时-->
  50. <load-on-startup>1</load-on-startup>
  51. </servlet>
  52. <servlet-mapping>
  53. <servlet-name>springmvc</servlet-name>
  54. <!--指定拦截什么样的请求
  55. 例如:http://localhost:8080/demo.action
  56. -->
  57. <url-pattern>/</url-pattern>
  58. </servlet-mapping>
  59. </web-app>

springmvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. 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 http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
  7. <!--配置包扫描-->
  8. <context:component-scan base-package="com.zl"/>
  9. <!--视图控制器,用来访问首页;需要搭配注解驱动使用-->
  10. <mvc:view-controller path="/" view-name="index"/>
  11. <!--专门处理ajax请求,ajax请求不需要视图解析器InternalResourceViewResolver-->
  12. <!--但是需要添加注解驱动,专门用来解析@ResponseBody注解的-->
  13. <!--注入date类型时,需要使用@DateTimeFormat注解,也要搭配这个使用-->
  14. <mvc:annotation-driven/>
  15. <!-- 配置Thymeleaf视图解析器 -->
  16. <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
  17. <property name="order" value="1"/>
  18. <property name="characterEncoding" value="UTF-8"/>
  19. <property name="templateEngine">
  20. <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
  21. <property name="templateResolver">
  22. <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
  23. <!-- 视图前缀 -->
  24. <property name="prefix" value="/WEB-INF/templates/"/>
  25. <!-- 视图后缀 -->
  26. <property name="suffix" value=".html"/>
  27. <property name="templateMode" value="HTML5"/>
  28. <property name="characterEncoding" value="UTF-8"/>
  29. </bean>
  30. </property>
  31. </bean>
  32. </property>
  33. </bean>
  34. </beans>

准备实体类

  1. package com.zl.bean;
  2. public class Employee {
  3. private Integer id;
  4. private String lastName;
  5. private String email;
  6. private Integer gender;
  7. @Override
  8. public String toString() {
  9. return "Employee{" +
  10. "id=" + id +
  11. ", lastName='" + lastName + '\'' +
  12. ", email='" + email + '\'' +
  13. ", gender=" + gender +
  14. '}';
  15. }
  16. public Integer getId() {
  17. return id;
  18. }
  19. public void setId(Integer id) {
  20. this.id = id;
  21. }
  22. public String getLastName() {
  23. return lastName;
  24. }
  25. public void setLastName(String lastName) {
  26. this.lastName = lastName;
  27. }
  28. public String getEmail() {
  29. return email;
  30. }
  31. public void setEmail(String email) {
  32. this.email = email;
  33. }
  34. public Integer getGender() {
  35. return gender;
  36. }
  37. public void setGender(Integer gender) {
  38. this.gender = gender;
  39. }
  40. public Employee(Integer id, String lastName, String email, Integer gender) {
  41. super();
  42. this.id = id;
  43. this.lastName = lastName;
  44. this.email = email;
  45. this.gender = gender;
  46. }
  47. public Employee() {
  48. }
  49. }

准备dao模拟数据:使用Map集合的操作模拟连接数据库

  1. package com.zl.dao;
  2. import com.zl.bean.Employee;
  3. import org.springframework.stereotype.Repository;
  4. import java.util.Collection;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. @Repository
  8. public class EmployeeDao {
  9. private static Map<Integer, Employee> employees = null;
  10. static{
  11. employees = new HashMap<Integer, Employee>();
  12. employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1));
  13. employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
  14. employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
  15. employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
  16. employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1));
  17. }
  18. private static Integer initId = 1006;
  19. public void save(Employee employee){
  20. if(employee.getId() == null){
  21. employee.setId(initId++);
  22. }
  23. employees.put(employee.getId(), employee);
  24. }
  25. public Collection<Employee> getAll(){
  26. return employees.values();
  27. }
  28. public Employee get(Integer id){
  29. return employees.get(id);
  30. }
  31. public void delete(Integer id){
  32. employees.remove(id);
  33. }
  34. }

2. 功能清单

功能URL 地址请求方式
访问首页√/GET
查询全部数据√/employeeGET
删除√/employee/2DELETE
跳转到添加数据页面√/toAddGET
执行保存√/employeePOST
跳转到更新数据页面√/employee/2GET
执行更新√/employeePUT

列表功能(显示数据) 

index.html:发送请求,查询所有员工

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <h1>首页</h1>
  9. <a th:href="@{/employee}">查看员工信息</a>
  10. </body>
  11. </html>

EmployeeController:接收请求,拿到数据放到域对象当中去;并跳转页面展示数据

  1. package com.zl.controller;
  2. import com.zl.bean.Employee;
  3. import com.zl.dao.EmployeeDao;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.ResponseBody;
  11. import java.util.Collection;
  12. import java.util.Iterator;
  13. @Controller
  14. public class EmployeeController {
  15. @Autowired
  16. private EmployeeDao employeeDao;
  17. // 查看员工信息
  18. @GetMapping("/employee")
  19. public String getEmployees(Model model){
  20. Collection<Employee> employees = employeeDao.getAll();
  21. System.out.println(employees);
  22. // 放到域对象当中
  23. model.addAttribute("employees",employees);
  24. // 跳转页面进行数据的展示
  25. return "employee_list";
  26. }
  27. }

employee_list.html:展示数据

①前端中两个重要的标签from和table:from是用来发送请求的,table是用来展示数据的。border属性表示设置边框、cellpadding和cellspacing表示设置边框的边距和间距为0、style是用来设置居中操作的(也可以直接用align="center")。

②使用thymeleaf便利数据,很类似以与JSTL标签库的使用,格式不同罢了;这是使用的是thymeleaf的each标签,格式为:"自定义变量名:放入域对象数据的key"

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Employee Info</title>
  6. </head>
  7. <body>
  8. <!--表格展示数据:居中、边框的边距和间距设为0-->
  9. <table border="1" style="text-align: center" cellpadding="0" cellspacing="0" >
  10. <tr>
  11. <!--colspan合并单元格,表示当前字段占用5个单元格-->
  12. <th colspan="5">Employee Info</th>
  13. </tr>
  14. <tr>
  15. <th>id</th>
  16. <th>lastName</th>
  17. <th>email</th>
  18. <th>gender</th>
  19. <th>options</th>
  20. </tr>
  21. <!--使用thymeleaf遍历数据,类似于JSTL标签库-->
  22. <tr th:each="employee : ${employees}">
  23. <td th:text="${employee.id}"></td>
  24. <td th:text="${employee.lastName}"></td>
  25. <td th:text="${employee.email}"></td>
  26. <td th:text="${employee.gender}"></td>
  27. <td>
  28. <a href="">delete</a>
  29. <a href="">update</a>
  30. </td>
  31. </tr>
  32. </table>
  33. </body>
  34. </html>

效果展示:

删除数据(难点)

问题:删除操作处理超链接地址?

通过id进行删除操作,但是此时的id需要动态获取,不能写死!

<a th:href="@{/employee/${employee.id}}">delete</a>

如果直接使用${employee.id}的方式添加在路径后面,此时大括号{}会被thymeleaf解析!

解决方案一: 使用+号拼接,拼接在@{}外面,这样就不会被thymeleaf解析

  1. <!--放到@{}外面,此时的 加号+ 会报错,但不影响使用-->
  2. <a th:href="@{/employee/}+${employee.id}">delete</a>

解决方案二: 也可以就拼接在@{}里面,此时的路径/employee/需要加上单引号

  1. <!--加上单引号的表示会被当做路径解析,后面的则会被当做数据解析-->
  2. <a th:href="@{'/employee/'+${employee.id}}">delete</a>

问题:通过超链接控制表单的提交?

通过Vue实现超链接控制form表单的提交!

注:在webapp/static/js下导入vue.js库!

①首先需要创建Vue,在Vue中绑定容器;我们需要操作超链接,所以绑定的元素必须包括我们要操作的元素。所以可以在tr或者table标签中定义一个id进行绑定。

②设置超链接的点击事件,在删除的超链接中使用@click绑定一个点击事件;然后在Vue的methods种处理绑定事件。

③获取form表单,所以要给from表单设置id,进行获取,获取到表单以后将触发事件的超连接的href属性赋值给表单的action、提交表单、取消超连接的默认行为。

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Employee Info</title>
  6. </head>
  7. <body>
  8. <!--表格展示数据:居中、边框的边距和间距设为0-->
  9. <table id="dataTable" border="1" style="text-align: center" cellpadding="0" cellspacing="0" >
  10. <tr>
  11. <!--colspan合并单元格,表示当前字段占用5个单元格-->
  12. <th colspan="5">Employee Info</th>
  13. </tr>
  14. <tr>
  15. <th>id</th>
  16. <th>lastName</th>
  17. <th>email</th>
  18. <th>gender</th>
  19. <th>options</th>
  20. </tr>
  21. <!--使用thymeleaf遍历数据,类似于JSTL标签库-->
  22. <tr th:each="employee : ${employees}">
  23. <td th:text="${employee.id}"></td>
  24. <td th:text="${employee.lastName}"></td>
  25. <td th:text="${employee.email}"></td>
  26. <td th:text="${employee.gender}"></td>
  27. <td>
  28. <!--删除操作,超链接控制form表单-->
  29. <a @click="deleteEmployee" th:href="@{'/employee/'+${employee.id}}">delete</a>
  30. <a href="">update</a>
  31. </td>
  32. </tr>
  33. </table>
  34. <!--表单-->
  35. <form id="deleteForm" method="post">
  36. <input type="hidden" name="_method" value="delete" />
  37. </form>
  38. <!--引入Vue-->
  39. <script type="text/javascript" th:src="@{/static/js/vue.js}" />
  40. <!--使用js代码-->
  41. <script type="text/javascript">
  42. // 创建Vue
  43. var vue = new Vue({
  44. // 绑定容器(使用el属性)
  45. el:"#dataTable",
  46. // 处理绑定事件(使用methods属性)
  47. methods:{
  48. // 函数的名称和对应的函数
  49. deleteEmployee:function(event){ // event代表当前的点击事件
  50. // 根据id获取form表单元素
  51. var deleteForm = document.getElementById("deleteForm");
  52. // 将触发事件的超连接的href属性赋值给表单的action
  53. deleteForm.action = event.target.href;
  54. // 提交表单
  55. deleteForm.submit();
  56. // 取消超连接的默认行为
  57. event.preventDefault();
  58. }
  59. }
  60. });
  61. </script>
  62. </body>
  63. </html>

根据id删除

注:此时会遇到使用转发还是重定向的问题;删除过后就和当前页面没关系,是要跳转到另一个页面,并且地址栏的地址肯定也要变,所以使用重定向!

  1. // 根据id删除员工
  2. @DeleteMapping("/employee/{id}")
  3. public String deleteEmployee(@PathVariable Integer id){
  4. employeeDao.delete(id);
  5. // 重定向到列表页面
  6. return "redirect:/employee";
  7. }

问题1:此时重新部署进行访问,此时浏览器会报错误(发送的还是get请求,绑定的事件没起作用)

F12代开调试窗口,发现是找不到vue.js

 此时打开当前工程打的war包发现没有static的目录

 解决方案:重新进行打包

问题2: 上面是解决了当前项目没有,所以找不到;重新打包以后当前服务器已经有了,发现还是找不到!

解释:此时是因为前端控制器DispatcherServlet引起的,因为我们设置的处理路径是"/",表示除了jsp的所有路径,此时的静态资源vue.js被SpringMVC处理了,但是静态资源又不能被SpringMVC处理。此时需要一个default-servlet-handler开放对静态资源的访问!

  1. <!--开放对静态资源的访问-->
  2. <mvc:default-servlet-handler />

<mvc:default-servlet-handler />工作的原理:

首先静态资源会被SpringMVC的前端控制器DispatcherServlet处理,如果在前端的控制器中找不到相对应的请求映射,此时就会交给默认的Servlet处理,如果默认的Servlet能找到资源就访问资源,如果找不到就报404!

问题3:此时浏览器还可能报错

解释:您正在开发模式下运行Vue。部署生产时,请确保打开生产模式。

根据提示来做 , 将生产模式的提示关闭即可 ,即设置成 false即可

<script>Vue.config.productionTip= false </script>

此时就可以正常的进行删除操作 

添加数据 

编写超链接,跳转到添加页面

<th>options(<a th:href="@{/toAdd}">add</a>)</th>

此时不需要任何的业务逻辑,使用视图控制器

<mvc:view-controller path="/toAdd" view-name="employee_add"/>

 添加数据的employee_add

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>add employee</title>
  6. </head>
  7. <body>
  8. <!--添加数据的表单-->
  9. <form th:action="@{/employee}" method="post">
  10. lastName:<input type="text" name="lastName"><br>
  11. email:<input type="text" name="email"><br>
  12. gender:<input type="radio" name="gender" value="1">male
  13. <input type="radio" name="gender" value="0">female<br>
  14. <input type="submit" value="add"><br>
  15. </form>
  16. </body>
  17. </html>

获取form表单提交的数据,进行添加

  1. // 添加数据
  2. @PostMapping("/employee")
  3. public String addEmployee(Employee employee){
  4. employeeDao.save(employee);
  5. // 重定向到列表页面
  6. return "redirect:/employee";
  7. }

添加成功

更新数据

根据id进行修改

  1. <!--修改操作-->
  2. <a th:href="@{'/employee/'+${employee.id}}">update</a>

注:这里涉及一个回显数据的功能,所以需要先跳转到一个Controller去查询数据,把数据放到域对象当中后跳转到一个新的页面employee_update页面显示,通过这个页面进行显示的数据进行修改,修改后并提交在经过一个Controller处理冲转到页面展示功能页面进行数据的展示!

根据id先查询数据

  1. // 用户回显数据的controller
  2. @RequestMapping("/employee/{id}")
  3. public String getEmployeeById(@PathVariable Integer id,Model model){
  4. // 根据id查
  5. Employee employee = employeeDao.get(id);
  6. // 存到域对象当中
  7. model.addAttribute("employee",employee);
  8. // 跳转到回显数据的页面
  9. return "employee_update";
  10. }

回显数据并可以更新数据的employee_update

对于单显框的回显使用的是field属性!

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>update employee</title>
  6. </head>
  7. <body>
  8. <!--回显数据的表单-->
  9. <form th:action="@{/employee}" method="post">
  10. <!--发送put请求-->
  11. <input type="hidden" name="_method" value="put">
  12. <!--id也回显,设置为隐藏域,或者设置为只读-->
  13. <input type="hidden" name="id" th:value="${employee.id}">
  14. lastName:<input type="text" name="lastName" th:value="${employee.lastName}"><br>
  15. email:<input type="text" name="email" th:value="${employee.email}"><br>
  16. gender:<input type="radio" name="gender" value="1" th:field="${employee.gender}">male
  17. <input type="radio" name="gender" value="0" th:field="${employee.gender}">female<br>
  18. <input type="submit" value="update"><br>
  19. </form>
  20. </body>
  21. </html>

效果展示:默认回显数据的效果

在上面回显数据的页面进行更新,根据更新提交的数据进行存储,然后重定向到列表页面展示

  1. // 更新数据的Controller
  2. @PutMapping("/employee")
  3. public String updateEmployee(Employee employee){
  4. // 更新数据
  5. employeeDao.save(employee);
  6. // 重定向到列表页面
  7. return "redirect:/employee";
  8. }

图书推荐:用ChatGPT与VBA一键搞定Excel

参与方式:

本次送书 1 本! 
活动时间:截止到 2023-06-12 00:00:00。

抽奖方式:利用程序进行抽奖。

参与方式:关注博主(只限粉丝福利哦)、点赞、收藏,评论区随机抽取,最多三条评论!

本期图书:《用ChatGPT与VBA一键搞定Excel》

        在以 ChatGPT 为代表的 AIGC(AI Generated Content,利用人工智能技术来生成内容)工具大量涌现的今天,学习编程的门槛大幅降低。对于大部分没有编程基础的职场人士来说,VBA 这样的办公自动化编程语言比以前任何时候都更容易掌握,能够极大提高工作效率。本书通过 3 个部分:VBA 基础知识、ChatGPT基础知识、ChatGPT实战办公自动化,帮助Excel用户从零开始迅速掌握VBA,以“授人以渔”的方式灵活应对任何需要自动化办公的场景。

        简而言之,本书的目标是:普通用户只需要掌握一些VBA的基本概念,然后借助 ChatGPT 就可以得到相应的VBA代码,从而解决具体问题。

京东购买链接:点击购买

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/193843
推荐阅读
相关标签
  

闽ICP备14008679号