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. Vue 中Axios 使用

    1.安装axios npm install axios 2.在使用的地方导入 import axios from 'axios' 3.再方法中调用 sendHttp: function () { ax ...

  2. EnvironmentError: mysql_config not found

    Collecting MySQL-python==1.2.5 (from -r requirementsNoGit.txt (line 9)) Using cached https://files.p ...

  3. docker 安装redis 并配置外网可以访问

    1, docker 拉去最新版本的redis docker pull redis #后面可以带上tag号, 默认拉取最新版本 2, docker安装redis container 安装之前去定义我们的 ...

  4. Python适配器模式代码

    Python设计模式之适配器模式,代码,思考等 # -*- coding: utf-8 -*- # author:baoshan class Computer: def __init__(self, ...

  5. python接入微博第三方API之1环境准备

    环境准备: 1.注册微博账号 2.注册应用

  6. 四、postman增加断言

    预期和实际结果的判断 预期==实际:用例通过,写到报告里 预期!==实际:用例失败,写到报告里 一.例子演示 相当于首页右侧的10大每天的内容 url:http://www.v2ex.com/api/ ...

  7. Nginx搭建负载均衡集群

    (1).实验环境 youxi1 192.168.5.101 负载均衡器 youxi2 192.168.5.102 主机1 youxi3 192.168.5.103 主机2 (2).Nginx负载均衡策 ...

  8. PP篇9 更改计划订单

    首先看了下这个函数的版本  还挺新的 S4版本应该是有更新过,里面用了新语法 导入: PLANNEDORDER    计划订单号HEADERDATA          表头数据(来自外部系统) HEA ...

  9. Swift细节记录<一>

    1.全局变量记录: import UIKit class HHTSwitchGlobalData: NSObject { var isWaiterAutoPop: Bool = true privat ...

  10. C语言中结构体的构造函数

    示例代码: #include <iostream> using namespace std; struct Node { int x, y, z; Node(int _x, int _y, ...