赞
踩
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
xmlns:th="http://www.thymeleaf.org"
# 关闭模板引擎的缓存
spring.thymeleaf.cache=false
首页配置:需注意 == > 所有静态资源都需要使用thymeleaf来接管 :url ==> @{}
使用之前需要确保IDEA的所有编码都是UTF-8
目录:
右键添加步骤:
# 配置文件的真实位置
spring.messages.basename=i18n.login
国际化使用的标签:#{}
MyLocaleResolver
public class MyLocaleResolver implements LocaleResolver { // 解析请求 @Override public Locale resolveLocale(HttpServletRequest request) { // 获取请求中的语言参数 String language = request.getParameter("l"); Locale locale = Locale.getDefault(); // 如果没有则使用默认的 if (!StringUtils.isEmpty(language)){ // zh_CN String[] split = language.split("_"); // 国家,地区 locale = new Locale(split[0], split[1]); } return locale; } @Override public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { } }
index.html
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
// 自定义的国际化组件注入到Bean中
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
效果:
页面国际化
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model){
if ( "jack".equals(username) && "123".equals(password) ){
return "dashboard";
}else {
// 返回错误信息
model.addAttribute("msg","用户名或密码错误");
return "index";
}
}
}
th:if="${not #strings.isEmpty(msg)}" 为thymeleaf语法
registry.addViewController("/main.html").setViewName("dashboard");
这里无论登不登录,都可以进入main页面,所以需要加入拦截器进行拦截
public class LoginHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 登录成功之后,应该有用户的session Object loginUser = request.getSession().getAttribute("loginUser"); if (loginUser == null){ request.setAttribute("msg","您未登录,请先登录"); request.getRequestDispatcher("/index.html").forward(request,response); return false; } else { return true; } } }
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/*","/js/*","/img/*");
}
公共页面:
<!-- 顶部导航栏 -->
th:fragment="topbar"
<!-- 侧边栏-->
th:fragment="sidebar"
子页面:
<!-- 顶部导航栏 -->
<div th:replace="~{commons/commons::topbar}"></div>
<!-- 侧边栏-->
<!-- 传递参数给组件-->
<div th:replace="~{commons/commons::sidebar(active='list.html')}"></div>
如果要传递参数,可以直接使用()传参,接收判断即可!
增加编辑,删除按钮
<td>
<!-- 按钮,小按钮,按钮颜色 -->
<button class="btn btn-sm btn-primary">编辑</button>
<button class="btn btn-sm btn-danger">删除</button>
</td>
<table class="table table-striped table-sm"> <thead> <tr> <th>id</th> <th>lastName</th> <th>email</th> <th>gender</th> <th>department</th> <th>birth</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="emp:${emps}"> <td th:text="${emp.getId()}"></td> <td th:text="${emp.getLastName()}"></td> <td th:text="${emp.getEmail()}"></td> <td th:text="${emp.getGender()==0?'女':'男'}"></td> <td th:text="${emp.getDepartment().getDepartmentName()}"></td> <td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}"></td> <td> <button class="btn btn-sm btn-primary">编辑</button> <button class="btn btn-sm btn-danger">删除</button> </td> </tr> </tbody> </table>
需要对性别和日期做判断,使用三目表达式
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
@RequestMapping("/emp")
public String employee(Model model){
Collection<Employee> employees = employeeDao.getAll();
model.addAttribute("emps",employees);
return "emp/list";
}
}
点击高亮
需对active做出判断
效果展示
学习视频:https://www.bilibili.com/video/BV1PE411i7CV?p=25
<h2><a class="btn btn-sm btn-success" th:href="@{/emps}">添加员工</a></h2>
效果:
<!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 th:href="@{/css/bootstrap.min.css}" rel="stylesheet"> <!-- Custom styles for this template --> <link th:href="@{/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="~{commons/commons::topbar}"></div> <div class="container-fluid"> <div class="row"> <div th:replace="~{commons/commons::sidebar(active='list.html')}"></div> <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"> <form th:action="@{/emps}" method="post"> <div class="form-group"> <label>LastName</label> <input type="text" name="lastName" class="form-control" placeholder="海绵宝宝"> </div> <div class="form-group"> <label>Email</label> <input type="email" name="email" class="form-control" placeholder="1176244270@qq.com"> </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:each="dept:${department}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option> </select> </div> <div class="form-group"> <label>Birth</label> <input type="text" name="birth" class="form-control" placeholder="嘤嘤嘤"> </div> <button type="submit" class="btn btn-primary">添加</button> </form> </main> </div> </div> </body> </html>
效果:
// 点击增加员工,跳转页面
@GetMapping("/emps")
public String toAddPage(Model model){
// 查出所有的部门信息
Collection<Department> department = departmentDao.getAllDepartment();
model.addAttribute("department",department);
return "emp/add";
}
加入name属性,否则后台无法获取数据
对部门进行遍历,根据部门id遍历,然后显示部门名称
@PostMapping("/emps")
public String addEmp(Employee employee){
System.out.println(employee);
// 保存员工信息
employeeDao.add(employee);
return "redirect:/emp";
}
效果
注意
这里输入时间时,系统默认为dd/MM/yyyy,如果需要"-"格式的,则需要在配置中修改
spring.mvc.format.date=yyyy-MM-dd
默认格式为:
修改之后格式为:
学习视频:https://www.bilibili.com/video/BV1PE411i7CV?p=26
<!--${emp.getId()} 获取当前的id值-->
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.getId()}">编辑</a>
// 去员工的修改页面
@GetMapping("/emp/{id}")
public String toUpdateEmployee(@PathVariable("id") Integer id,Model model){
// 根据id获取信息
Employee employeeById = employeeDao.getEmployeeById(id);
model.addAttribute("emp",employeeById);
// 查出所有的部门信息
Collection<Department> department = departmentDao.getAllDepartment();
model.addAttribute("department",department);
return "emp/update";
}
注意
th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm')}"
@PostMapping("/updateEmp")
public String updateEmp(Employee employee){
employeeDao.add(employee);
return "redirect:/emp";
}
这里点击修改会发现,并不是修改已有用户的信息,而是在增加员工信息,所以这里我们需要获取用户的id,根据id去修改用户的信息
<input type="hidden" name="id" th:value="${emp.getId()}">
<a class="btn btn-sm btn-danger" th:href="@{/delete/}+${emp.getId()}">删除</a>
// 删除员工
@GetMapping("/delete/{id}")
public String deleteEmp(@PathVariable("id") int id){
employeeDao.deleteEmployeeById(id);
return "redirect:/emp";
}
学习视频:https://www.bilibili.com/video/BV1PE411i7CV?p=27
在templates下面新建error目录,将404.html导入
访问一个不存在的网页时效果
// 注销
@RequestMapping("/user/logout")
public String logout(HttpSession session){
// 清除session
session.invalidate();
return "redirect:/index.html";
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。