restuful风格:

百度百科:

RESTFUL是一种网络应用程序的设计风格和开发方式,基于HTTP,可以使用XML格式定义或JSON格式定义。RESTFUL适用于移动互联网厂商作为业务使能接口的场景,实现第三方OTT调用移动网络资源的功能,动作类型为新增、变更、删除所调用资源。

RESTFUL特点:
1、每一个URI代表1种资源;
2、客户端使用GET、POST、PUT、DELETE4个表示操作方式的动词对服务端资源进行操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源;
3、通过操作资源的表现形式来操作资源;
4、资源的表现形式是XML或者HTML;
5、客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都必须包含理解请求所必需的信息。
 
规范列表:
 

由于采用的是thymeleaf+bootstarp(springBoot)的结构实现

所以对于一些公共片段的抽取必须得满足thymeleaf的语法规则:

抽取:

引入:

三种引入的效果:

详见:https://www.thymeleaf.org/

工程结构:

登录拦截器:LoginHanderInterceptor

  1. package com.zyb.webdemo.handlerInterceptor;
  2.  
  3. import org.springframework.web.servlet.HandlerInterceptor;
  4. import org.springframework.web.servlet.ModelAndView;
  5.  
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8.  
  9. /**
  10. * 登陆拦截器
  11. */
  12. public class LoginHanderInterceptor implements HandlerInterceptor {
  13. @Override
  14. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  15. Object isLogin=request.getSession().getAttribute("isLogin");
  16. //没有登陆直接进主页
  17. if(isLogin==null){
  18. request.setAttribute("msg","没有权限请登录");
  19. request.getRequestDispatcher("/login").forward(request,response);
  20. return false;
  21. }else{
  22. return true;
  23. }
  24.  
  25. }
  26.  
  27. @Override
  28. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  29.  
  30. }
  31.  
  32. @Override
  33. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  34.  
  35. }
  36. }

员工操作控制器代码:EmployeeController

  1. package com.zyb.webdemo.controller;
  2.  
  3. import com.zyb.webdemo.dao.DepartmentDao;
  4. import com.zyb.webdemo.dao.EmployeeDao;
  5. import com.zyb.webdemo.entities.Department;
  6. import com.zyb.webdemo.entities.Employee;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.ui.Model;
  10. import org.springframework.web.bind.annotation.*;
  11.  
  12. import java.util.Collection;
  13. import java.util.Collections;
  14.  
  15. @Controller
  16. public class EmployeeController {
  17.  
  18. @Autowired
  19. EmployeeDao employeeDao;
  20. @Autowired
  21. DepartmentDao departmentDao;
  22. //返回员工列表页面
  23. @GetMapping("/emps")
  24. public String list(Model model){
  25. //thymeleaf默认就会拼串
  26. //前缀:classpath:/templates/
  27. //后缀:.html
  28. Collection<Employee> all= employeeDao.getAll();
  29. //放在请求域中
  30. model.addAttribute("emps",all);
  31. return "emp/list";
  32. }
  33.  
  34. //来到员工添加页面
  35. @GetMapping("/emp")
  36. public String toAddPage(Model model){
  37. //查出所有部门
  38. Collection<Department> departments = departmentDao.getDepartments();
  39. model.addAttribute("depts",departments);
  40. //返回员工添加页面的映射
  41. return "emp/add";
  42. }
  43.  
  44. //员工添加
  45. //SpringMvc自动将请求和入参对象的属性一一绑定;要求请求参数的名字和javaBean入参对想想的属性名一致
  46. @PostMapping("/emp")
  47. public String addEmp(Employee employee){
  48. //redirect:重定向
  49. //forword:转发
  50. //System.out.println("员工信息:"+employee);
  51. //保存员工
  52. employeeDao.save(employee);
  53. return "redirect:/emps";
  54. }
  55.  
  56. @GetMapping("/emp/{id}")
  57. public String toEditPage(@PathVariable("id") Integer id,
  58. Model model){
  59. Employee employee = employeeDao.get(id);
  60. model.addAttribute("emp",employee);
  61.  
  62. Collection<Department> departments = departmentDao.getDepartments();
  63. model.addAttribute("depts",departments);
  64. //回到修改界面
  65. return "emp/edit";
  66. }
  67.  
  68. //员工修改
  69. @PutMapping("/emp")
  70. public String updateEmployee(Employee employee){
  71. employeeDao.save(employee);
  72. return "redirect:/emps";
  73. }
  74. @DeleteMapping("/emp/{id}")
  75. public String deleteEmployee(@PathVariable("id") Integer id){
  76. employeeDao.delete(id);
  77. return "redirect:/emps";
  78. }
  79. }

MySpringMvcConfig的配置:

  1. package com.zyb.webdemo.config;
  2.  
  3. import com.zyb.webdemo.component.MyLocaleResolver;
  4. import com.zyb.webdemo.handlerInterceptor.LoginHanderInterceptor;
  5. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.web.servlet.LocaleResolver;
  9. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  10. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
  11. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  12.  
  13. @Configuration
  14. //2.0之后直接实现 WebMvcConfigurer就行
  15. public class MySpringmvcConfig implements WebMvcConfigurer {
  16. @Override
  17. public void addViewControllers(ViewControllerRegistry registry) {
  18. registry.addViewController("/").setViewName("login");
  19. registry.addViewController("/login").setViewName("login");
  20. registry.addViewController("/main").setViewName("dashboard");//后面自动加html
  21. }
  22.  
  23. //注册拦截器
  24. @Override
  25. public void addInterceptors(InterceptorRegistry registry) {
  26. registry.addInterceptor(new LoginHanderInterceptor()).addPathPatterns("/**")
  27. .excludePathPatterns("/login","/user/login","/","/assert/**","/webjars/**");
  28. }
  29.  
  30. @Bean//将组件注册在容器中
  31. public LocaleResolver localeResolver(){
  32.  
  33. return new MyLocaleResolver();
  34. }
  35.  
  36. }

因为浏览器不直接支持put、delete的请求,所以需要post请求作为中间请求进行变换

edit.html:(修改页面)

  1. <!DOCTYPE html>
  2. <!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
  3. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  4.  
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  8. <meta name="description" content="">
  9. <meta name="author" content="">
  10.  
  11. <title>Dashboard Template for Bootstrap</title>
  12. <!-- Bootstrap core CSS -->
  13. <link href="../../static/asserts/css/bootstrap.min.css" th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">
  14.  
  15. <!-- Custom styles for this template -->
  16. <link href="../../static/asserts/css/dashboard.css" th:href="@{/asserts/css/dashboard.css}" rel="stylesheet">
  17. <style type="text/css">
  18. /* Chart.js */
  19.  
  20. @-webkit-keyframes chartjs-render-animation {
  21. from {
  22. opacity: 0.99
  23. }
  24. to {
  25. opacity: 1
  26. }
  27. }
  28.  
  29. @keyframes chartjs-render-animation {
  30. from {
  31. opacity: 0.99
  32. }
  33. to {
  34. opacity: 1
  35. }
  36. }
  37.  
  38. .chartjs-render-monitor {
  39. -webkit-animation: chartjs-render-animation 0.001s;
  40. animation: chartjs-render-animation 0.001s;
  41. }
  42. </style>
  43. </head>
  44.  
  45. <body>
  46. <!-- 引入头部搜索栏-->
  47. <div th:replace="~{commons/common::topbar}"></div>
  48.  
  49. <div class="container-fluid">
  50. <div class="row">
  51. <div th:replace="~{commons/common::#menu(activeUri='emplist')}"></div>
  52.  
  53. <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
  54. <form th:action="@{/emp}" method="post">
  55. <!--发送put请求修改员工数据-->
  56. <!--
  57. 1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)
  58. 2、页面创建一个post表单
  59. 3、创建一个input项,name="_method";值就是我们指定的请求方式
  60. -->
  61. <input type="hidden" name="_method" value="put" />
  62. <input type="hidden" name="id" th:value="${emp.id}">
  63. <div class="form-group">
  64. <label>LastName</label>
  65. <input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${emp.lastName}">
  66. </div>
  67. <div class="form-group">
  68. <label>Email</label>
  69. <input name="email" type="email" class="form-control" placeholder="zhangsan@atguigu.com" th:value="${emp.email}">
  70. </div>
  71. <div class="form-group">
  72. <label>Gender</label><br/>
  73. <div class="form-check form-check-inline">
  74. <input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp.gender==1}">
  75. <label class="form-check-label"></label>
  76. </div>
  77. <div class="form-check form-check-inline">
  78. <input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp.gender==0}">
  79. <label class="form-check-label"></label>
  80. </div>
  81. </div>
  82. <div class="form-group">
  83. <label>department</label>
  84. <!--提交的是部门的id-->
  85. <select class="form-control" name="department.id">
  86. <option th:selected="${dept.id == emp.department.id}" th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option>
  87. </select>
  88. </div>
  89. <div class="form-group">
  90. <label>Birth</label>
  91. <input name="birth" type="text" class="form-control" placeholder="zhangsan" th:value="${#dates.format(emp.birth, 'yyyy-MM-dd')}">
  92. </div>
  93. <button type="submit" class="btn btn-primary" >修改</button>
  94. </form>
  95.  
  96. </main>
  97. </div>
  98. </div>
  99.  
  100. <!-- Bootstrap core JavaScript
  101. ================================================== -->
  102. <!-- Placed at the end of the document so the pages load faster -->
  103. <script type="text/javascript" src="../../static/asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/asserts/js/jquery-3.2.1.slim.min.js}"></script>
  104. <script type="text/javascript" src="../../static/asserts/js/popper.min.js" th:src="@{/asserts/js/popper.min.js}"></script>
  105. <script type="text/javascript" src="../../static/asserts/js/bootstrap.min.js" th:src="@{/asserts/js/bootstrap.min.js}"></script>
  106.  
  107. <!-- Icons -->
  108. <script type="text/javascript" src="../../static/asserts/js/feather.min.js" th:href="@{/asserts/js/feather.min.js}"></script>
  109. <script>
  110. feather.replace()
  111. </script>
  112.  
  113. <!-- Graphs -->
  114. <script type="text/javascript" src="../../static/asserts/js/Chart.min.js" th:src="@{/asserts/js/Chart.min.js}"></script>
  115. <script>
  116. var ctx = document.getElementById("myChart");
  117. var myChart = new Chart(ctx, {
  118. type: 'line',
  119. data: {
  120. labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  121. datasets: [{
  122. data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
  123. lineTension: 0,
  124. backgroundColor: 'transparent',
  125. borderColor: '#007bff',
  126. borderWidth: 4,
  127. pointBackgroundColor: '#007bff'
  128. }]
  129. },
  130. options: {
  131. scales: {
  132. yAxes: [{
  133. ticks: {
  134. beginAtZero: false
  135. }
  136. }]
  137. },
  138. legend: {
  139. display: false,
  140. }
  141. }
  142. });
  143. </script>
  144.  
  145. </body>
  146.  
  147. </html>
  1. 相关实体类:

删除的实现技巧:

不能将delete按钮直接包含在form表单中:

通过js进行进行调用一个表单,不用为删除而创建多个表单

效果图:

修改页面:

SpringBoot实现restuful风格的CRUD的更多相关文章

  1. java框架之SpringBoot(6)-Restful风格的CRUD示例

    准备 环境 IDE:Idea SpringBoot版本:1.5.19 UI:BootStrap 4 模板引擎:thymeleaf 3 效果:Restful 风格 CRUD 功能的 Demo 依赖 &l ...

  2. SpringBoot整合Redis使用Restful风格实现CRUD功能

    前言 本篇文章主要介绍的是SpringBoot整合Redis,使用Restful风格实现的CRUD功能. Redis 介绍 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-valu ...

  3. SpringBoot之RESTful风格

    SpringBoot之RESTful风格 1.RESTful介绍 RESTful是一种软件架构风格,一种时尚! RESTful架构风格规定,数据的元操作,即CRUD(create, read, upd ...

  4. 学习SpringMVC——你们要的REST风格的CRUD来了

    来来来,让一下,客官,您要的REST清蒸CRUD来了,火候刚刚好,不油不腻,请慢用~~~ 如果说前面是准备调料,洗菜,切菜,摆盘,那么今天就来完整的上道菜,主要说的是基于REST风格实现数据的增删改查 ...

  5. 使用SpringBoot编写Restful风格接口

    一.简介    Restful是一种对url进行规范的编码风格,通常一个网址对应一个资源,访问形式类似http://xxx.com/xx/{id}/{id}. 举个栗子,当我们在某购物网站上买手机时会 ...

  6. SpringBoot + Maven + Hibernate ( 简单实现CRUD功能 )

    工具:idea.mariadb数据库 创建一个项目 ( student ) ........(使用idea创建一个springboot项目,这里我就不多说了) Maven 中的依赖 <?xml ...

  7. Springboot中Rest风格请求映射如何开启并使用

    问题引入 因为前端页面只能请求两种方式:GET请求和POST请求,所以就需要后台对其进行处理 解决办法:通过springmvc中提供的HiddenHttpMethodFilter过滤器来实现 而由于我 ...

  8. SpringBoot 整合 MyBatis,实现 CRUD 示例

    目录 前言 创建项目/模块 SpringBoot Console Application CommandLineRunner SpringBoot 集成 MyBatis 创建数据库/表 配置数据源/连 ...

  9. 使用springBoot搭建REATFul风格的web demo

    1 Spring boot 核心特性 自动配置:针对常见 spring 应用程序的常见应用功能,Spring boot 自动提供相应配置 起步依赖:告诉springboot 需要什么功能,他就会自动引 ...

随机推荐

  1. NPOI 导出Excel表报错

    当导出2007格式的时候,打开文件总是报错“发现 xxx中的部分内容有问题.是否让我们尽量尝试恢复?”. 导出的程序: protected void btnValidateInternalData_C ...

  2. PyQt5遇到的一个坑 "ImportError: unable to find Qt5Core.dll on PATH" 及解决办法

    最近再实现一个功能,主要是将自动化测试界面化 环境组合为:Windows 64bit + PyCharm + Python + PyQt5 + Pyinstaller + Inno Setup PS ...

  3. Java+Selenium+Testng自动化测试学习(二)

    Java+Selenium+TestNG自动化测试框架整合 1.简化代码 封装一个定位元素的类,类型为ElementLocation package com.test; import org.open ...

  4. 8.7-Day1T1

    题目大意: T组测试数据,每组测试数据给出一个n,求[0,n-1]所有逆元的和.(n可能不为质数) 题解: 我的想法: 求出每一个数的逆元,再相加.由于有n为质数的时候,所以,我将它分为两种情况:(1 ...

  5. vue 实现todolist,包含添加,删除,统计,清空,隐藏功能

    vue 实现todolist,包含添加,删除,统计,清空,隐藏功能 添加:生成列表结构(v-for+数组).获取用户输入(v-model).通过回车新增数据(v-on+.enter) 删除:点击删除指 ...

  6. 搭建分布式hadoop环境的前期准备---需要检查的几个点

    前期准备: jdkhostnamehostsdate安全机制firewallwindows 域名映射 具体的操作见下面 1.看看自己是否已经配置了别名了(linux别名的配置可以参考博文:自己cent ...

  7. Linux中Oracle启动侦听报错TNS:permission denied的解决方法

    最近在开发环境 oracle 启动侦听的时候,出现了 TNS:permission denied 的问题,通过网上和咨询朋友,最终找到了解决方案,现在共享出来给有需要的朋友. [oracle@orac ...

  8. Docker配置阿里云镜像源

    Docker默认拉取镜像是从这里拉取(https://hub.docker.com/),拉取的速度让人...,所以是配置国内镜像源,拉取速度十分惊人 一.版本要求 Docker版本:1.10以上 二. ...

  9. 【强烈推荐,超详细,实操零失误】node.js安装 + npm安装教程 + Vue开发环境搭建

    node.js安装 + npm安装教程 + Vue开发环境搭建 [强烈推荐,超详细,实操零失误] 原博客园地址:https://www.cnblogs.com/goldlong/p/8027997.h ...

  10. Uva 11300 Spreading the Wealth(贪心)

    题目链接:https://vjudge.net/problem/UVA-11300 这道题的思路太神了,但很难想到是贪心. 用M表示每个人最终拥有的金币数. 首先假设有四个人.假设1号给2号3枚,2号 ...