视频讲解可以关注B站狂神说Java
SpringBoot-Thymeleaf
使用SpringBoot+Thymeleaf 完成员工及部门信息最简单的增删改查操作
项目目录
thymeleaf基本语法
thymeleaf和SpringBoot整合
导入依赖
<!--thymeleaf模板引擎-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
前端页面引入Thymeleaf
<html lang="en" xmlns:th="http://www.thymeleaf.org">
......
......
</html>
首页实现(扩展MVC)
因为在template下的静态资源无法直接访问,所以当我们访问localhost:8080 或者 localhost:8080/index.html时候希望能都访问到index.html页面,所以我们可以自己扩展一个SpringMvc,添加一个试题解析器实现,实现该功能
//扩展MVC
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
登录拦截器
在登录后会将登录信息存入session中,若session中没有值的则表示未登录,无法访问业务页面给与拦截,登录后即可访问
在confing包下自定义拦截器LoginHandlerInterceptor实现HandlerInterceptor接口,重写所需方法
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取登陆后存入session的登录信息
if (request.getSession().getAttribute("loginUser") == null){
request.setAttribute("msg","未登录,请先进行登录!");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return