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.</version>
</dependency> <dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.1.</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 = ; 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: .125rem;
text-anchor: middle;
} @media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: .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="" height="">
<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; -</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)&&"".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实现简单登录的更多相关文章

  1. 纯JSP实现简单登录跳转

    1.JSP介绍 JSP即Java Server Pages,JSP技术使用Java编程语言编写类XML的tags和scriptlets,来封装产生动态网页的处理逻辑.网页还能通过tags和script ...

  2. Java 简单登录MVC

    构建一个简单的基于MVC模式的JavaWeb 零晨三点半了,刚刚几个兄弟一起出去吼歌,才回来,这应该是我大学第二次去K歌,第一次是大一吧,之后每次兄弟喊我,我都不想去,因为我还是很害怕去KTV,或许是 ...

  3. 基于SAML的单点登录介绍

    http://blog.csdn.net/csethcrm/article/details/20694993 一.背景知识: SAML即安全断言标记语言,英文全称是Security Assertion ...

  4. [置顶] 使用红孩儿工具箱完成基于Cocos2d-x的简单游戏动画界面

    [Cocos2d-x相关教程来源于红孩儿的游戏编程之路CSDN博客地址:http://blog.csdn.net/honghaier 红孩儿Cocos2d-X学习园地QQ3群:205100149,47 ...

  5. 玩转spring boot——简单登录认证

    前言 在一个web项目中,某些页面是可以匿名访问的,但有些页面则不能.spring mvc提供了HandlerInterceptor接口来应对,只需要重写preHandle方法便可以实现此功能.那么使 ...

  6. Spring Security 整合freemaker 实现简单登录和角色控制

    Spring Security 整合freemaker 实现简单登录和角色控制     写这篇文章是因为我做了一个电商网站项目,近期刚加上权限控制.整个过程很简单,在此给大家梳理一下,也算是自己对知识 ...

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

    上面博文,主要简单的介绍了一下SSH的基本概念,比較宏观,作为刚開始学习的人可以有一个总体上的认识,个人觉得对学习有非常好的辅助功能.它不不过一个"瞭望塔".更是检验是否真正掌握全 ...

  8. 基于RxJava2+Retrofit2简单易用的网络请求实现

    代码地址如下:http://www.demodashi.com/demo/13473.html 简介 基于RxJava2+Retrofit2实现简单易用的网络请求,结合android平台特性的网络封装 ...

  9. 基于CAS的单点登录实战(2)-- 搭建cas的php客户端

    在这之前已经搭好了CAS服务端 基于CAS的单点登录实战(1)-- 搭建cas服务器 PHP-Client php-Client是官方支持的,去官网下个最新版就好了.phpCAS 接入很简单,解压放到 ...

随机推荐

  1. SetThreadAffinityMask windows下绑定线程(进程)到指定的CPU核心

    原帖地址:https://www.cnblogs.com/lvdongjie/p/4476766.html 一个程序指定到单独一个CPU上运行会比不指定CPU运行时快.这中间主要有两个原因:1)CPU ...

  2. 1.0 Android基础入门教程

    1.0 Android基础入门教程 分类 Android 基础入门教程 本教程于2015年7月开始撰写,耗时半年,总共148节,涵盖了Android基础入门的大部分知识,由于当时能力局限,虽已竭尽全力 ...

  3. 解决“Jquery的each里面return失效的问题”

    参考文章:http://blog.csdn.net/coffeesmile/article/details/53349860 问题描述: 集中获取页面的一些元素,然后用each循环处理这些元素,如果其 ...

  4. layui日历控件设置选择日期不能超过当前日期

    layui.use('laydate', function() { var laydate = layui.laydate; laydate.render({ elem : '#begin', max ...

  5. phpstorm yii2框架的redis和mongodb提示

    随便找个目录创建一个 yii_helper.php 文件,内容如下: /** * Class Yii */ class Yii { /** * @var MyApplication */ public ...

  6. python脚本使用源码安装不同版本的python

    # coding=utf-8 import os import sys # 判断是否是root用户 if os.getuid() == 0: pass else: print('当前用户不是root用 ...

  7. 转 linux下ClamAV使用

    linux下ClamAV使用 第一步:Clamav下载http://www.clamav.net/downloads#yuminstall wget –y第二步:创建clamav用户和组groupad ...

  8. 【438】Python 处理文件

    1. 读取文件,计算 tweets 数目 python中readline判断文件读取结束的方法 line == '' python:如何检查一行是否为空行 line == '\n' or line = ...

  9. array_map array_walk

    $config = [ => [], => [], => [] ]; array_map(function($key) use ($config){ print_r($key); d ...

  10. 数据库分库分表中间件ShardingSphere推荐

    官网链接:http://shardingsphere.io/document/current/cn/overview/ 源起: 我今天首先去了解了一下国内好像是比较火的一个叫"MyCat&q ...