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

打印 上一主题 下一主题

主题 994|帖子 994|积分 2984

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
目录  
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 恰恰有一个获取请求方式的操作:
  1. 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"?><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>encode</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>        <!--逼迫request使用字符集encoding-->        <init-param>            <param-name>forceRequestEncoding</param-name>            <param-value>true</param-value>        </init-param>        <!--逼迫response使用字符集encoding-->        <init-param>            <param-name>forceResponseEncoding</param-name>            <param-value>true</param-value>        </init-param>    </filter>    <!--全部请求-->    <filter-mapping>        <filter-name>encode</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <!--发送put、delete请求方式的过滤器-->    <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框架-->    <servlet>        <servlet-name>springmvc</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <!--配置springMVC位置文件的位置和名称-->        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:springmvc.xml</param-value>        </init-param>        <!--将前端控制器DispatcherServlet的初始化时间提前到服务器启动时-->        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>springmvc</servlet-name>        <!--指定拦截什么样的请求            例如:http://localhost:8080/demo.action        -->        <url-pattern>/</url-pattern>    </servlet-mapping></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必要动态获取,不能写死!
  1. <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即可
  1. <script>Vue.config.productionTip= false </script>
复制代码
此时就可以正常的进行删除操作 


添加数据 

编写超链接,跳转到添加页面
  1. <th>options(<a th:href="@{/toAdd}">add</a>)</th>
复制代码
此时不必要任何的业务逻辑,使用视图控制器
  1. <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代码,从而解决具体题目。
  

京东购买链接:点击购买

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

tsx81428

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表