基于thymeleaf实现简单登录

Posted xiaoliangup

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于thymeleaf实现简单登录相关的知识,希望对你有一定的参考价值。

1、引入thymeleaf、静态资源等依赖

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.1.3</version>
        </dependency>
    <!-- 模板引擎 Thymeleaf 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2、欢迎页面及静态资源配置解析:WebMvcAutoConfiguration

public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
                return;
            }
            Integer cachePeriod = this.resourceProperties.getCachePeriod();
            if (!registry.hasMappingForPattern("/webjars/**")) {
                customizeResourceHandlerRegistration(registry
                        .addResourceHandler("/webjars/**")
                        .addResourceLocations("classpath:/META-INF/resources/webjars/")
                        .setCachePeriod(cachePeriod));
            }
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
      //静态资源文件夹映射
if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations( this.resourceProperties.getStaticLocations()) .setCachePeriod(cachePeriod)); } }     
    
    //配置欢迎页 @Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping( ResourceProperties resourceProperties) { return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern()); }
public Resource getWelcomePage() {
        for (String location : getStaticWelcomePageLocations()) {
            Resource resource = this.resourceLoader.getResource(location);
            try {
                if (resource.exists()) {
                    resource.getURL();
                    return resource;
                }
            }
            catch (Exception ex) {
                // Ignore
            }
        }
        return null;
    }

    private String[] getStaticWelcomePageLocations() {
        String[] result = new String[this.staticLocations.length];
        for (int i = 0; i < result.length; i++) {
            String location = this.staticLocations[i];
            if (!location.endsWith("/")) {
                location = location + "/";
            }
            result[i] = location + "index.html";
        }

3、注册templates主页面访问路径/、/index

@Configuration
public class MyConfig {
    
    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter webMvcConfigurerAdapter =new WebMvcConfigurerAdapter(){
            
            public void addViewControllers(ViewControllerRegistry registry) {
                // TODO Auto-generated method stub
                registry.addViewController( "/").setViewName("index");
                registry.addViewController( "/index.html").setViewName("index");
            }
            
        return webMvcConfigurerAdapter;
    }

技术图片

4、index.html

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta 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="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Jekyll v3.8.5">
    <title>Signin Template · Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="/docs/4.2/dist/css/bootstrap.min.css" rel="stylesheet" th:href="@{/webjars/bootstrap/4.1.3/css/bootstrap.min.css}" crossorigin="anonymous">
    

    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }
    </style>
    <!-- Custom styles for this template -->
    <link th:href="@{assert/css/signin.css}" rel="stylesheet">
  </head>
  <body class="text-center">
    <form class="form-signin" th:action="@{/toLogin}">
  <img class="mb-4" th:src="@{/assert/img/bootstrap-solid.svg}" alt="" width="72" height="72">
  <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
  
  <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
  <label class="sr-only" th:text="#{login.username}">Username</label>
  <input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required autofocus>
  <label for="inputPassword" class="sr-only" th:text="#{login.password}">Password</label>
  <input type="password" name="password" id="inputPassword" class="form-control" th:placeholder="#{login.password}" required>
  <div class="checkbox mb-3">
    <label>
      <input type="checkbox" value="remember-me"> [[#{login.remember}]]
    </label>
  </div>
  <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
  <p class="mt-5 mb-3 text-muted">&copy; 2017-2018</p>
</form>
</body>
</html>

5、LoginController

@Controller
public class LoginController {

    @RequestMapping(value = "/toLogin")
    public String toLogin(@PathParam(value = "username") String username,
            @PathParam(value = "password") String password,
            Map<String, Object> map, HttpSession session) {
        
        if(!StringUtils.isEmpty(username)&&"123456".equals(password)){
            session.setAttribute("loginUser", username);
            return "redirect:/main";
        }else {
            map.put("msg", "用户或密码不正确");
            return "index";
        }
    }

6、用拦截器LoginInterceptor简单实现未登录返回主页面

public class LoginInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginUser");
        if(user == null){
            request.setAttribute("msg", "请先登录");
            request.getRequestDispatcher("/").forward(request, response);
            return false;
        }
        
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        
    }

}

注册拦截器

@Configuration
public class MyConfig {
    
    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter webMvcConfigurerAdapter =new WebMvcConfigurerAdapter(){
            
                        ......
            
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                // TODO Auto-generated method stub
                registry.addInterceptor(new LoginInterceptor()).excludePathPatterns("/","/index.html","/toLogin");
            }
            
        };
        
        return webMvcConfigurerAdapter;
    }        

实现效果:

技术图片

 





以上是关于基于thymeleaf实现简单登录的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot实现基于shiro安全框架的,配合thymeleaf模板引擎的用户认证和授权

一个简单的springboot+mybatis-plus+thymeleaf的学生管理系统

使用片段时 Intellij 无法正确识别 Thymeleaf 模型变量

Spring boot:thymeleaf 没有正确渲染片段

登录 Spring 安全重定向到错误 Thymeleaf 和基于 Java 的配置

登录成功后向片段或页面传递数据