SpringBoot之CRUD实战
首先请先下载好我准备的初始的项目
链接:https://pan.baidu.com/s/13CPPHGnw-jkxJcMlleU9vw
提取码:twru
这里我们只是实现了一个功能那就是访问:localhost:8088可以访问到登陆页面
下面我们一步步的完善功能。
一.国际化配置
1.编写国际化配置文件
注意我们的登录页面,但是是英文,我们接下来需要做的就是根据浏览器的优先语言来自动变换语言以及在点击最下面的中英文链接的实现中英文转化功能也实现,一共是两个功能。
我们首先在resources
目录下建立文件:
现在我们还需要一个英文的配置文件,创建方式可以按照下面来,命名方式与中文的一样,都是语言名加上国家代号(也可以直接新建
)
接下来我们就在那个中文的配置文件中完成英文的转换:
红框的内容就是我们需要转换的内容
这里我举例翻译提示部分(下面注意选择了文件后在左下角选择Resource Bondle
)。
其他按照上面修改即可。
最后应该是这样:
index.properties
:
index.password=密码~
index.remember=记住我~
index.sign=登陆~
index.tip=请登录~
index.username=姓名~
index_zh_CN.properties:
index.password=密码
index.remember=记住我
index.sign=登陆
index.tip=请登录
index.username=姓名
index_en_US.properties
:
index.password=Password
index.remember=Remember me
index.sign=Sign in
index.tip=Please sign in
index.username=Username
2.将国际化配置文件交给SpringBoot来管理
这一部分我们只是了解,本文的目的在于应用,原理我们不深挖,想了解原理的同学请自行看下面的文件
接下来我们需要在主配置文件里面加上:
spring.messages.basename=i18n.index
至于为什么这么做想知道原理的同学可以看我上看给出的文件的源码去了解。
3.让页面可以获取到我们配置的内容完成转换
我们现在可以把index.html
的内容改为如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<link rel="shortcut icon" th:href="@{/favicon.ico}"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>登录</title>
<!-- Bootstrap core CSS -->
<link href="asserts/css/bootstrap.min.css" rel="stylesheet" th:href="@{/asserts/css/bootstrap.min.css}">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" rel="stylesheet" th:href="@{/asserts/css/signin.css}">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" src="asserts/img/bootstrap-solid.svg" th:src="@{/asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{index.tip}">Please sign in</h1>
<label class="sr-only" th:text="#{index.username}">Username</label>
<input type="text" class="form-control" placeholder="Username" name="username" required="" autofocus="" th:placeholder="#{index.username}">
<label class="sr-only">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password" required="" th:placeholder="#{index.password}">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" > [[#{index.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{index.sign}">Sign in</button>
<p class="mt-5 mb-3 text-muted">©2017-2018</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
</body>
</html>
注意上面的sr
c和href
一定要修改为我们的thymeleaf
表达式,不然后面页面跳转是会出问题。举个例子,现在发送一个请求localhost:8088/user/login
,于是来到登录的页面,密码输入错误重新转发回到登录页面,但是由于我们没有使用thymeleaf的表达式,最后导致了例如src="asserts/img/bootstrap-solid.svg"
就会解析为localhost:8088/user/asserts/img/bootstrap-solid.svg"
,相当于往前退一个,把login
少了,然后user
保留了,而正确的路径应该是:localhost:8088/asserts/img/bootstrap-solid.svg"
。
接下来再次访问发现得到这样的结果:
解决方案就是在MyConfig
类中加入:
@Bean
public ResourceBundleMessageSource messageSource(){
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setFallbackToSystemLocale(false);
messageSource.setBasenames("i18n.index");
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(2);
return messageSource;
}
再次访问:
当然也许有的同学会遇到乱码的现象,这里解决方案是在Setting
里面配置File Encoding
为UTF-8
即可(当然这个时候需要把我们的国际化配置文件的内容修正回来,因为这个时候已经乱码了
)
解决了上述问题后,我们再来回一下我们最开始说的要实现根据浏览器默认的语言优先级来显示对应的语言(注意这不是使用浏览器的翻译功能
),这里我们来详细的演示一边就明白了:
演示1:中文优先
访问如下:
演示2:英文优先
访问如下:
不过这里呢我们还是简单的来介绍一下我们的原理:
在英文优先的条件下的请求头信息如下:
现在我们来实现第二个功能,就是点击链接实现中英文的转化:
首先需要修改index.html
里面的链接标签,如下:
但是这样还是不能实现我们的功能,因为在容器里面的区域信息解析器还是更根据我们的请求头来的,我们需要在容器中加入我们自己的区域信息解析器才行。
我们兴建下面一个区域信息解析器:
package com.jack.demo.component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String lang = request.getParameter("l");
//操作系统自己的区域化对象
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(lang)){
String[] split = lang.split("_");
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
然后我们在MyConfig类
里面加上:
@Bean
//注意这个方法名应该为localeResolver,因为最后需要根据这个名字来获取组件
//或者在@Bean注解上来加名字也可
public LocaleResolver localeResolver(HttpServletRequest request){
return new MyLocaleResolver();
}
到这里我们的国际化配置的内容就讲解完毕。
二.登陆功能的实现
首先我们把index.html
的表单标签来修改一下属性:
<form class=“form-signin” action=“dashboard.html” th:action="@{/user/login}" method=“post”>
接下来我们编写Controller
:
package com.jack.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@PostMapping("/user/login")
//@RequestMapping(value = "/user/login",method = RequestMethod.POST)
public String login(){
return "dashboard";
}
}
插句题外话:这里说一个小技巧,在我们以后的开发中会反复的修改我们的页面,但是这样我们就要不断的重启我们的应用,这样带来的结果就是很浪费开销,我们可以这么做,在主配置文件中我们加上spring.thymeleaf.cache=false来禁用缓存,然后按住ctrl+f9即可完成自动重新编译(热部署)
为了让密码错误时显示msg
消息,我们加入下面标签:
上面我们解决了密码错误显示的问题。但是我们登录成功后还有一个问题如下:
由于登陆成功后得到的页面是转发来的,也就是说点刷新还是在刷新登陆页面,这就导致了会出现重复提交表单的问题。
很自然我们可以使用重定向来解决这一问题,方案如下(修改或者添加红框的内容
):
演示如下:
不过这样我们又有了一个新的问题就是如果直接访问:http://localhost:8088/main.html
也可得到上面的页面,这显然不对的,于是我们可以通过配置拦截器来解决。(后面会出教程使用Spring-Security
来实现),如果对拦截器的知识忘记了可以参考我的SpringMVC教程
:SSM项目整合——10SpringMVC拦截器
我们编写拦截器:
package com.jack.demo.component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object user = session.getAttribute("loginUser");
//如果没有user这一属性,说明没有登录成功过
if(user==null){
//无法通过那么我们需要的操作就是跳转到登陆界面
request.getRequestDispatcher("/index.html").forward(request,response);
request.setAttribute("msg","无权访问");
return false;//拦截
}else{
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
然后将拦截器注入到容器中:
(注意如果出现上面拦截失效的话,加上"/error"即可)
登录成功后我们要在session
中说明该用户已登录:
演示如下:
当我们直接访问main.html
时我们发现跳转到了登录页面,登录成功后我们再次开一个新的页面时再次直接访问main.html
就可以直接成功了。不过我们还要一个问题就是我们登录后Company Name
应该是jack
才对,很简单:
在dashboard.html显示Company Name的那一个标签内加上下面内容
th:text="${#session.getAttribute(‘loginUser’)}
三.RestFul——CRUD
RestFul风格的CRUD的URI是/资源名称/资源标识
,他通过请求方式来区分操作
操作类型 | 普通CRUD(以路径区分操作) | RestFul的CRUD(以请求方式来区分操作) |
---|---|---|
查询 | getEmp/… | emp–GET方式 |
添加 | addEmp/… | emp–POST方式 |
修改 | updateEmp/… | emp–PUT方式 |
删除 | deleteEmp/… | emp–DELETE方式 |
现在我们列举本实验的具体路径:
1.员工列表展示
I.初始展示
在这里我先将list.html
放到templates
下面的emp
包下面
添加控制器:
package com.jack.demo.controller;
import com.jack.demo.dao.EmployeeDao;
import com.jack.demo.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Collection;
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
//返回员工列表页面
@GetMapping("/emps")
public String list(Model model){
Collection<Employee> employees = employeeDao.getAll();
model.addAttribute("emps",employees);
return "/emp/list";
}
}
然后把dashboard.html
做如下修改:
把list.html
做如下修改:
接下来演示一下:
II.Thymeleaf抽取公共部分
接下来我们要解决一个冗余的问题,就是下面红框的部分每个页面是一样的因此我们应该把这一部分抽取出来。
这里给出一个我写的一个Thymeleaf抽取
的文章给大家参考即可。具体的操作留给读者。
这里我将公共部分抽取出来放在templates/emp/bar.html里面如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>bar</title>
</head>
<body>
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" id="topBar">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#" th:text="${#session.getAttribute('loginUser')}"">Company name</a>
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
</li>
</ul>
</nav>
<nav class="col-md-2 d-none d-md-block bg-light sidebar" id="leftBar">
<div class="sidebar-sticky">
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link active" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
<polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>
Dashboard <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file">
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
<polyline points="13 2 13 9 20 9"></polyline>
</svg>
Orders
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart">
<circle cx="9" cy="21" r="1"></circle>
<circle cx="20" cy="21" r="1"></circle>
<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
</svg>
Products
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#" th:href="@{/emps}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
员工列表
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-bar-chart-2">
<line x1="18" y1="20" x2="18" y2="10"></line>
<line x1="12" y1="20" x2="12" y2="4"></line>
<line x1="6" y1="20" x2="6" y2="14"></line>
</svg>
Reports
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-layers">
<polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
<polyline points="2 17 12 22 22 17"></polyline>
<polyline points="2 12 12 17 22 12"></polyline>
</svg>
Integrations
</a>
</li>
</ul>
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Saved reports</span>
<a class="d-flex align-items-center text-muted" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
</a>
</h6>
<ul class="nav flex-column mb-2">
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Current month
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Last quarter
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Social engagement
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Year-end sale
</a>
</li>
</ul>
</div>
</nav>
</body>
</html>
III.链接高亮处理
下面这样处理后在访问dashboard.html
时activeUri
的值就是main.html
,在访问
list.html
时activeUri
的值就是emps
在bar.html
里面就根据这些值来判断是否高亮显示。
IV.数据遍历显示
在list.html
修改显示内容如下:
<table class="table table-striped table-sm">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>邮箱</th>
<th>性别</th>
<th>部门</th>
<th>生日</th>
</tr>
</thead>
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td th:text="${emp.getLastName()}"></td>
<td th:text="${emp.getEmail()}"></td>
<td th:text="${emp.getGender()==0?'女':'男'}"></td>
<td>[[${emp.department.departmentName}]]</td>
<td th:text="${emp.getBirth().toString()}"></td>
</tr>
</tbody>
</table>
如果对时间显示有要求可以按照下面这么做:
效果如下:
为下面的CRUD
做准备我们作如下修改:
效果如下:
2.员工添加
对list.html
做如下修改:
在EmployeeController
里添加下面内容:
@Autowired
DepartmentDao departmentDao;
@GetMapping("/emp")
public String toAddPage(Model model){
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts",departments);
return "emp/add";
}
@PostMapping("/emp")
public String add(Employee employee){
employeeDao.save(employee);
return "redirect:/emps";
}
templates/emp/add.html
的内容如下:
<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Dashboard Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="asserts/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/dashboard.css" rel="stylesheet">
<style type="text/css">
/* Chart.js */
@-webkit-keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}
@keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}
.chartjs-render-monitor {
-webkit-animation: chartjs-render-animation 0.001s;
animation: chartjs-render-animation 0.001s;
}
</style>
</head>
<body>
<div th:replace="~{emp/bar::#topBar}"></div>
<div class="container-fluid">
<div class="row">
<div th:replace="emp/bar::#leftBar(activeUri='emps')"></div>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2><a class="btn btn-sm btn-success" th:href="@{/emp}">员工添加</a></h2>
<form th:action="@{/emp}" th:method="post">
<div class="form-group">
<label>LastName</label>
<input name="lastName" type="text" class="form-control" placeholder="zhangsan">
</div>
<div class="form-group">
<label>Email</label>
<input name="email" type="email" class="form-control" placeholder="[email protected]">
</div>
<div class="form-group">
<label>Gender</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<select class="form-control" name="department.id">
<option th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.id}"></option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input name="birth" type="text" class="form-control" placeholder="zhangsan">
</div>
<button type="submit" class="btn btn-primary">添加</button>
</form>
</main>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript" src="asserts/js/popper.min.js"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js"></script>
<!-- Icons -->
<script type="text/javascript" src="asserts/js/feather.min.js"></script>
<script>
feather.replace()
</script>
<!-- Graphs -->
<script type="text/javascript" src="asserts/js/Chart.min.js"></script>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
datasets: [{
data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
lineTension: 0,
backgroundColor: 'transparent',
borderColor: '#007bff',
borderWidth: 4,
pointBackgroundColor: '#007bff'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false,
}
}
});
</script>
</body>
</html>
上面演示正常了,但对于添加功能我们会存在下面问题:
提交的数据格式不对:生日:日期;
2017-12-12;2017/12/12;2017.12.12;
日期的格式化;SpringMVC将页面提交的值需要转换为指定的类型;
2017-12-12—Date; 类型转换,格式化;
默认日期是按照/的方式;
我们可以在主配置文件指定日期提交的格式:
spring.mvc.date-format=yyyy-MM-dd HH:mm
3.员工修改
在EmployeeController
里面加上:
@GetMapping("/emp/{id}")
public String toEditPage(@PathVariable("id") Integer id,Model model){
Employee employee = employeeDao.get(id);
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts",departments);
model.addAttribute("emp",employee);
return "emp/edit";
}
而我们的templates/emp/edit.html
为:
<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Dashboard Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="asserts/css/bootstrap.min.css" th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/dashboard.css" th:href="@{/asserts/css/dashboard.css}" rel="stylesheet">
<style type="text/css">
/* Chart.js */
@-webkit-keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}
@keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}
.chartjs-render-monitor {
-webkit-animation: chartjs-render-animation 0.001s;
animation: chartjs-render-animation 0.001s;
}
</style>
</head>
<body>
<div th:replace="~{emp/bar::#topBar}"></div>
<div class="container-fluid">
<div class="row">
<div th:replace="emp/bar::#leftBar(activeUri='emps')"></div>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2><a class="btn btn-sm btn-success" th:href="@{/emp}">员工添加</a></h2>
<form th:action="@{/emp}" th:method="post">
<input type="hidden" name="_method" value="put"/>
<input type="hidden" name="id" th:value="${emp.id}">
<div class="form-group">
<label>LastName</label>
<input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:placeholder="${emp.lastName}">
</div>
<div class="form-group">
<label>Email</label>
<input name="email" type="email" class="form-control" placeholder="[email protected]" th:placeholder="${emp.email}">
</div>
<div class="form-group">
<label>Gender</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp.gender==1?true:false}">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp.gender==0?true:false}">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<select class="form-control" name="department.id" th:selected="${emp.department.id}">
<option th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.id}"></option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input name="birth" type="text" class="form-control" placeholder="zhangsan" th:placeholder="${#dates.format(emp.birth,'yyyy-MM-dd')}">
</div>
<button type="submit" class="btn btn-primary">保存</button>
</form>
</main>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript" src="asserts/js/popper.min.js"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js"></script>
<!-- Icons -->
<script type="text/javascript" src="asserts/js/feather.min.js"></script>
<script>
feather.replace()
</script>
<!-- Graphs -->
<script type="text/javascript" src="asserts/js/Chart.min.js"></script>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
datasets: [{
data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
lineTension: 0,
backgroundColor: 'transparent',
borderColor: '#007bff',
borderWidth: 4,
pointBackgroundColor: '#007bff'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false,
}
}
});
</script>
</body>
</html>
这里表单实现了put
方式的提交。
1.SpringMvc配置了HiddenHttpMethodFilter(SpringBoot自动配置好了)
2.创建表单,提交方式为post
3.在表单里面加上input标签,name为_method;value为put
效果展示:
4.员工删除
对list.html
作如下修改
$(".btnDelete").click(function () {
$("#deleteEmpForm").attr("action",$(this).attr("deleteUri")).submit()
})
演示如下:
到此我们的整个教程就此结束了,如果您认为对您有用麻烦为我点个赞哈!