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. ConsoleWebsocketServer服务端和ConsoleWebsocketClient客户端

    本文是简述了Websocket的服务端和客户端的实时通讯过程,Websocket的服务端和客户端的具体使用使用了2种Websocket的服务端和2种客户端. 以下代码使用的是Visual Studio ...

  2. JVM 类加载器的双亲委托机制

    1.类加载器的层次结构 在双亲委托机制中,各个加载器按照父子关系形成了树形结构(逻辑意义),除了根加载器之外,其余的类加载器都有且只有一个父加载器. public class MyTest13 { p ...

  3. graph embedding 使用方法

    无论是network embedding 还是graph embedding都是通过节点(node)和边的图,学出每个节点的embedding向量. 比较流行的算法有: Model Paper Not ...

  4. java(集合框架)(转)

    前言 集合①只能存放对象,存放基本类型会自动转成对应的对象②可以存放不同类型的对象(如果不使用泛型的话),且不限数量③集合中存放的只是对象的引用 集合详解 集合-1.png 集合-2.png   It ...

  5. android studio 把 ionic 打包时修改应用名称、修改应用图标、修改启动画面,升级打包

    在项目中resources中替换成自己的图标和启动画面即可 在config.xml 修改包名 打正式包和升级打包同原生的类似,在Androidmanifest.xml修改版本号和版本名

  6. Python爬取所有城市的aqi值

    # -*- coding: utf-8 -*- # author:baoshan import requests from bs4 import BeautifulSoup def get_city_ ...

  7. git git push某一次的commit记录

    $ git push <remote name> <commit hash>:<remote branch name> # Example:$ git push o ...

  8. SQLite数据库数据类型详解

    数据类型 类型 描             述 bit 整型 bit 数据类型是整型,其值只能是0.1或空值.这种数据类型用于存储只有两种可能值的数据,如Yes 或No.True 或Fa lse .O ...

  9. 戒邪淫利器:《楞严经 四种清净明诲》实例及原经文 (转自学佛网:http://www.xuefo.net/nr/article55/545256.html)

    今日得持首楞严,不读天下糟粕书! 当你读完楞严经后就会很真实的升起这个感觉!根本觉得其他书都是多余的!所以<楞严经>还是要多读,多看!并且<楞严经>戒淫的效果特别好!好好的珍惜 ...

  10. 编译Flink 1.9.0

    闲来无事,编个Flink 1.9 玩玩 1.下载flink.flink-shaded 源码.解压 flink flink-shaded 7.0 [venn@venn release]$ ll tota ...