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. docker 安装redis 并配置外网可以访问

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

  2. 无法调用到appcode下的类

    解决方法: 右键 appp_code下的类, 点击 “属性”, 里面 [生成操作] 一项 由内容 改为 编译 即可

  3. Linux命令 – ln 软连接与硬链接区别介绍

    ln命令可以生成软链接和硬链接,也可叫做符号链接和实体链接. 有兴趣深入理解的可以查阅相关文档,一般的读者只需记住以下几点即可: 不管是软链接还是硬链接都不会额外增加磁盘空间(虽然实际情况可能会多占用 ...

  4. ISO/IEC 9899:2011 条款6.7.2——类型说明符

    6.7.2 类型说明符 语法 1.type-specifier: void char short int long float double signed unsigned _Bool _Comple ...

  5. 006-guava 集合-集合工具类-集合扩展工具类

    一.概述 需要实现自己的集合扩展.也许你想要在元素被添加到列表时增加特定的行为,或者你想实现一个Iterable,其底层实际上是遍历数据库查询的结果集 二.使用 2.1.ForwardingList装 ...

  6. maven项目新检出后不编译爬坑记 及 mvn clean package报错 WagonTransporterFactory: java.util.NoSuchElementException 异常【我】

    从SVN新检出一个maven项目,配置好后,发现项目无法编译(只有一个test包中的代码显示编译报错,其他所有包中的代码都不编译,也不报错), 先注释掉报错的test包中的所有内容, 用Eclipse ...

  7. (?:pattern) 与 (?=pattern)的区别

    共同点 (?:pattern) 与 (?=pattern)都匹配pattern,但不会把pattern结果放到Matches的集合中. 区别 (?:pattern) 匹配得到的结果包含pattern. ...

  8. Glide升级到4.x版本遇到的问题

    Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency ...

  9. HTML布局排版手机上浏览的网页

    前面做个几个简单的测试html布局排版的页面,都是在浏览器上查看的,C-LODOP可通过集中打印和广域网AO打印方式,让手机等也可以打印预览和打印. 集中打印的大体方法是通过一台windows电脑作为 ...

  10. Newtonsoft.Json 方法使用()

    JSON.NET1.3.0,旧版本的json.net,使用Newtonsoft.Json.JavaScriptConvert.DeserializeObject类进行转换 如果是新版本的json.ne ...