0014SpringBoot结合thymeleaf实现登录功能

该登录功能需要实现的需求如下:

1、输入用户名密码,如果验证通过,进入首页,并显示登录的用户名

2、如果验证不通过,则重新进入登录页面,并显示“用户名密码错误”

3、如果未经登录,不能直接访问首页等静态资源,也不能直接调用Controller层的方法,都需要转发到登录页面,并提示“没有权限,请先登录”

具体实现如下:

1、定义登录页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; 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="">
<title>Signin Template for Bootstrap</title>
<!-- @{}的形式是链接资源文件或者访问某个请求路径 -->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
</head>

<body class="text-center">
<!--此处要写成method="POST",不能写成th:method="POST"-->
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="POST">
<img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
<!--#{}的形式是从国际化配置文件中取值-->
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<span style="color:red" th:text="${msg}" ></span>
<label class="sr-only" th:text="#{login.username}">Username</label>
<!--要写上name="username",否则访问LoginController方法时,没有传username会报错-->
<input type="text" name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password" 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">© 2017-2018</p>
<!--要写成th:href="@{/index(l='zh_CN')}",而不能写成th:href="@{/login.html(l='zh_CN')}",
因为直接定位到静态资源的话是不会走自己定义的区域解析器的,
另外thymeleaf模板引擎是用中括号中放key=value的形式传参数-->
<a class="btn btn-sm" th:href="@{/index(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index(l='en_US')}">English</a>
</form>

</body>

</html>

2、定义Controller处理登录请求

package com.myself.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginConcroller {

// @RequestMapping
// @GetMapping
// @DeleteMapping
// @RequestMapping
@PostMapping(value = "/user/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> map, HttpSession session){
if(!StringUtils.isEmpty(username) && "123456".equals(password)){
//登录成功,session中加入登录用户名,用于在成功的首页中展示
session.setAttribute("loginUser",username);
//此处用重定向,会被我们定义的视图解析器解析,寻找对应dashboard.html
return "redirect:/main.html";
}else{
//登录失败,设置失败信息并返回登录页面
map.put("msg","用户名密码错误");
//由于此处不是重定向,所以相当于根据字符串直接去templates下找login.html
//所以不能写成返回"/"或者"/index.html",否则会报找不到页面
return "login";
}
}

}

3、定义登录成功后进入的首页

展示登录用户名
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>

4、定义拦截器用于在调用一些功能前先判断用户是否登录,如果未登录,则转发到登录页面

package com.myself.component;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object obj = request.getSession().getAttribute("loginUser");
if(obj == null){
//没有登录,设置错误信息并转发到登录页面
request.setAttribute("msg","没有权限请先登陆");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else{
//已登录,放行
return true;
}
}
}

5、在定义的配置类中以@Bean的形式加入WebMvcConfigurerAdapter组件,其中需要实现这个组件的

addInterceptors(InterceptorRegistry registry) 方法,在这里指定我们定义的拦截器拦截哪些请求,不拦截哪些请求
package com.myself.config;

import com.myself.component.LoginHandlerInterceptor;
import com.myself.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
// @Override
// public void addViewControllers(ViewControllerRegistry registry) {
// registry.addViewController("/index").setViewName("login");
// }
//
// //注册拦截器
// @Override
// public void addInterceptors(InterceptorRegistry registry) {
//
// registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
// .excludePathPatterns("/index.html","/","/user/login","/webjars/**","/**/*.css", "/**/*.js");
// }

//使用WebMvcConfigurerAdapter来扩展SpringMVC的功能
//所有的WebMvcConfigurerAdapter都会生效
//注意要写在标有@Configuration的类中,要在方法上标上@Bean注解
@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
WebMvcConfigurerAdapter webMvcConfigurerAdapter = new WebMvcConfigurerAdapter(){
//视图空值器,用于定义访问哪些路径时定位到哪些视图
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//访问http://localhost:8080/ 和 http://localhost:8080/index.html都会寻找静态资源下的templates/login.html
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
//访问"/main.html"会寻找静态资源下的templates/login.html
registry.addViewController("/main.html").setViewName("dashboard");
}
//注册拦截器,用于拦截用户需要先登录才能访问资源
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login","/webjars/**","/**/*.css", "/**/*.js");
}
};
return webMvcConfigurerAdapter;
}

//定义区域解析器,解析国际化中英文切换
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}

}

测试:
1、访问Controller中的方法会被转发到登录页面

2、访问css静态资源文件可以访问

 3、未登录直接访问首页,会被转发到登录页面

4、用户名密码输入错误,会被转发到登录页面,并提示错误信息 

 5、用户名密码输入正确,进入首页,变显示登录用户名

 若有理解不到之处,望指教!

 

猜你喜欢

转载自www.cnblogs.com/xiao1572662/p/11913974.html