基于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;
    }        

实现效果:

原文地址:https://www.cnblogs.com/xiaoliangup/p/10420973.html

时间: 2024-07-29 08:19:05

基于thymeleaf实现简单登录的相关文章

SpringBoot整合LayUI和Thymeleaf制作简单登录页面

前面已经学习过SpringBoot整合Thymeleaf,这次主要把上次提到的简单登录界面用博文形式写出来 记录一个小Demo的学习,如果没看过SpringBoot整合Thymeleaf可以看一下SpringBoot整合Thymeleaf(三) 先上页面效果图: Demo所涉及的知识点 1.SpringBoot请求映射 2.static和templates静态资源映射 只要简单了解这两个知识点,就可以做出简单的登录的页面 Demo所涉及的目录结构图 Demo所涉及的Pom文件的主要依赖 <dep

Spring Boot + MyBatis + Thymeleaf实现简单留言板应用

Spring Boot + MyBatis + Thymeleaf实现简单留言板应用 本项目主要介绍使用Spring Boot + MyBatis + Thymeleaf + Bootstrap来实现一个简单的增删改查(CRUD)留言板应用.高阶人士可以直接跳过. 源代码:https://github.com/qingwenwei/spring-boot-crud-example 功能介绍 发表帖子.帖子列表 编辑帖子 使用Spring Initializr构建项目 Spring Initial

【SSH进阶之路】Struts基本原理 + 实现简单登录(二)

上面博文,主要简单的介绍了一下SSH的基本概念,比較宏观.作为刚開始学习的人可以有一个总体上的认识,个人觉得对学习有非常好的辅助功能,它不不过一个"瞭望塔".更是检验是否真正掌握全部内容的一个前提. Struts是基于MVC的框架,它进一步的对MVC进行了封装,它是怎么封装的,我们从先回想一下MVC再到Struts.再用Struts给大家实现一个简单登录的实例.我们開始吧. MVC 概念 MVC全名是Model View Controller,是模型(model)-视图(view)-控

纯JSP实现简单登录跳转

1.JSP介绍 JSP即Java Server Pages,JSP技术使用Java编程语言编写类XML的tags和scriptlets,来封装产生动态网页的处理逻辑.网页还能通过tags和scriptlets访问存在于服务端的资源的应用逻辑.JSP将网页逻辑与网页设计的显示分离,支持可重用的基于组件的设计,使基于Web的应用程序的开发变得迅速和容易. 它是一种动态页面技术,它的主要目的是将表示逻辑从Servlet中分离出来. 1)原理 2)内置对象(参考自百科) request request 

【web开发】★☆之基于Map实现(用户登录三次失败后)24小时之内限制登录!

[web开发]★☆之基于Map实现(用户登录三次失败后)24小时之内限制登录! 近期在改一个老项目(struts1做的),客户现在想实现如下效果,用户在登录失败三次之后,锁定用户,需要信息部管理人员进行解锁!我第一想法,是在其数据库User表中加一个字段,记录登录失败的次数,但是数据库添加字段需要远程操作数据库,而对方的数据库又被各种加密软件包围!不是很方便,所以想了一下解决方案,利用Map来进行处理! 首先说一个思路,新建实体类,只有两个属性,登录失败次数,登录时间,实现get,set方法!

Java 简单登录MVC

构建一个简单的基于MVC模式的JavaWeb 零晨三点半了,刚刚几个兄弟一起出去吼歌,才回来,这应该是我大学第二次去K歌,第一次是大一吧,之后每次兄弟喊我,我都不想去,因为我还是很害怕去KTV,或许是因为那里是我伤心的地方,也或许是因为我在那里失败过,所以内心一直都有点抵触,昨天是一室友的生日,也快过年,也是想和他们一起好好的玩一回,就放下一切去了,很久都没去吼歌了,嗓子现在都感觉哑哑的,今天一天仿佛没有干什么,有些不安,于是回来后把以前学习MVC时笔记写下来!MVC设计模式是目前使用得比较多的

基于SAML的单点登录介绍

http://blog.csdn.net/csethcrm/article/details/20694993 一.背景知识: SAML即安全断言标记语言,英文全称是Security Assertion Markup Language.它是一个基于XML的标准,用于在不同的安全域(security domain)之间交换认证和授权数据.在SAML标准定义了身份提供者(identity provider)和服务提供者(service provider),这两者构成了前面所说的不同的安全域. SAML

基于长连接简单聊天

一.由来 最近,公司需要一个即时聊天功能.为此,曾尝试SignalR,Tencent Mars,重点研究了下mars项目,该项目支持Android,iOS端通信,并能对网络进行优化处理,是微信内部运行架构.服务端是基于Netty框架通信,数据通过protobuf封装,并自定义了一套通信协议.客户端通信,通过封装好的类库进行调用.因此,对于项目较急的,上线快速,此方案研究耗时较长,不满足现状.因此,在此先试用简单长连接,并设置好接口,以备后续直接切换成成熟框架. 作为研究学习记录,对简单长连接做一

(5)基于hadoop的简单网盘应用实现1

hadoop网盘的最终效果见下面,可以实现简单的文件上传.删除.下载功能,不同用户可以登录到自己的页面进行管理. 一.准备的安装包资源 (1)hadoop1.1.2安装包 (2)bootmetro一个CSS开元框架,用来提高web前端的开发效率 (3)mysql的Jdbc驱动包 (4)上传组件 (5)mysql安装包(我的电脑是x64,x86系统的请下载对应版本即可) 二.搭建hadoop集群环境 教程见(2)虚拟机下hadoop1.1.2集群环境搭建 三.mysql5.6安装和eclipse上