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. TP5 分页数据加锚点

      TP5 分页数据加锚点跳转到相应位置   有这样一个需求,就是加载评论后,点下一页的时候回到相应的位置.  $comment = Db('comment')->order('addtime' ...

  2. tomcat的AJP(定向包协议)协议

    由于tomcat的html和图片解析功能相对其他服务器如apche等较弱,所以,一般都是集成起来使用,只有jsp和servlet服务交由tomcat处理,而tomcat和其他服务器的集成,就是通过aj ...

  3. ubuntu18源码包安装openresty

    author: headsen chen date : 2019-07-30  15:42:24 #在ubuntu18.04 环境下,openresty的依赖库有:PCRE.OpenSSL.zlib, ...

  4. Android Support v4、v7、v13、v14、v17的区别和应用场景

    Android Support v4.v7.v13.v14.v17的区别和应用场景   本文链接:https://blog.csdn.net/Aquarius_Seven/article/detail ...

  5. openresty开发系列23--lua面向对象

    openresty开发系列23--lua面向对象 面向对象编程(Object Oriented Programming,OOP)是一种非常流行的计算机编程架构.java,c++,.net等都支持面向对 ...

  6. 设置pycharm文件默认换行符onfiguring Line Separators

    http://www.jetbrains.com/help/pycharm/2016.2/configuring-line-separators.html PyCharm makes it possi ...

  7. Python web-Http

    web应用 Web应用程序一般指浏览器端/服务器端应用程序,这类应用程序一般借助谷歌,火狐等浏览器来运行.在网络编程的意义下,浏览器是一个socket客户端,服务器是一个socket服务端 impor ...

  8. 基于ADO的远程Oracle连接

    最近在一个通过MFC做一个界面,通过这个界面可以对布置在另一台服务器上的数据库MySQL.SQl Server.Oracle进行增删创建表的操作.其中我通过ADO很快就完成了对MySQL和SQL Se ...

  9. Delphi : TStringList的Find,IndexOf和Sort

    关键:Find要事先Sort排序,Indexof不用排序. TStringList内部查找相关的数据.待调试代码时才知道痛苦,浪费无数时间后,只得一步步跟踪,才发 现Find方法返回的Index总是错 ...

  10. docker进入容器内部执行命令

    [root@bogon ~]# docker ps -l CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 38a2cae4c32f jenk ...