本文导读
登 录
UserController
package com.lct.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
/**
* Created by Administrator on 2018/7/28 0028.
* 用户控制器层
*/
@Controller
@RequestMapping("user")
public class UserController {
/**
* 用户登录
*
* @param username 账号
* @param password 密码
* @param model 用户设值返回页面
* @param httpSession 设值登录的 用户session
* @return 登录成功 必须重定向,/userList的映射在 com.lct.component.MyWebMvcConfigurerAdapter 类中配置好了
* @PostMapping ("login") 相当于 @RequestMapping(value = "login",method = RequestMethod.POST) 的简写
* 同理还有 @GetMapping 、@PutMapping 、@DeleteMapping
*/
@PostMapping("login")
public String login(String username, String password, Model model, HttpSession httpSession) {
/**
* 当账号不为空,密码为 123456 时,模拟登录成功,否则失败时重定向返回登录页面
* 重定向时 要以 "/" 开头表示应用根地址
*/
if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
httpSession.setAttribute("userName", username);
return "redirect:/userList";
} else {
//登录失败仍然重定向到登录页面,index是之后要配置的请求路径之一
return "redirect:/index";
}
}
}
WebMvcConfigurer
package com.lct.component;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Created by Administrator on 2018/7/29 0029.
* WebMvc 扩展配置类
* Spring Boot 2.0以前可以使用 继承 WebMvcConfigurerAdapter 抽象类,但2.0版本以后,此类过时了不再推荐使用
* 解决方案是 直接实现 WebMvcConfigurer接口即可,因为 WebMvcConfigurerAdapter类同样是实现 WebMvcConfigurer接口
*/
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
/**
* 添加视图跳转控制器
* 当请求为 localhost:8080/tiger/userList 时。自动映射到 类路径下的templates下的 userList.html页面
* 当请求为 localhost:8080/tiger/index 时。自动映射到 类路径下的templates下的 index.html页面
*
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
/** 往前端 Thymeleaf 模板引擎时,开头不要加 "/" ,因为它默认配置的前缀就是:
* spring.thymeleaf.prefix=classpath:/templates/
*/
registry.addViewController("/userList").setViewName("userList");
registry.addViewController("/index").setViewName("index");
}
}
html 页面
- <form>标签的action值指向后台的登录地址;同时加了一行登录错误时的提示信息
<!DOCTYPE html>
<!--xmlns写上之后 Thymeleaf就会有提示,更加方便-->
<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>
<!-- Bootstrap core CSS
如果没有导入bootstrap的webjars包,则不要使用th:href覆盖掉原来静态文件夹目录下的文件-->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<!-- Custom styles for this template
理解原来之后就知道,下面th:href取值就是覆盖掉默认的href属性值,好处是可以不和前端人员代码发生冲突
thymeleaf的@{}表达式会自动加上"/应用上下文路径"前缀,这就避免了传统jsp中的${request.context.path}这种操作了
-->
<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" th:action="@{/user/login}" method="post">
<!-- 取值替换原来默认的值-->
<img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" 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>
<!--登录失败提示:判断,如果存在 message 消息,不为null也不为空,则显示-->
<p style="color: red" th:text="${message}" th:if="${not #strings.isEmpty(message)}"></p>
<label class="sr-only" th:text="#{login_name}">Username</label>
<input type="text" name="username" class="form-control" th:placeholder="#{login_name}" placeholder="Username"
required="" autofocus="">
<label class="sr-only" th:text="#{login_password}">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password"
required="" th:placeholder="#{login_password}">
<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_button}">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/(l=zh_CN)}">中文</a>
<a class="btn btn-sm" th:href="@{/(l=en_US)}">English</a>
</form>
</body>
</html>
运行测试
拦 截
- 登录做完之后,就应该做拦截了,要不然,直接输入登录以外的后台地址,照样可以进入
LoginHandlerInterceptor
package com.lct.component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by Administrator on 2018/7/29 0029.
* 登录拦截器
*/
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("userName");
/**
* 已经成功登录,则放行;否则重定向到登录页面
*/
System.out.println("----" + user + " ::: " + request.getRequestURL());
if (user == null) {
response.sendRedirect("/tiger/index");
return false;
}
return true;
}
}
注册拦截器
- spring boot 2.x依赖的spring 5.x版本,相对于spring boot 1.5.x依赖的spring 4.3.x版本而言,针对资源的拦截器初始化时有区别
- 使用spring 5.x时,静态资源也会执行自定义的拦截器,因此在配置拦截器的时候需要指定排除静态资源的访问路径
Spring Boot 2.0 之前
package com.lct.component;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
/**
* Created by Administrator on 2018/7/29 0029.
* WebMvc 扩展配置类
* Spring Boot 2.0以前可以使用 继承 WebMvcConfigurerAdapter 抽象类,但2.0版本以后,此类过时了不再推荐使用
* 解决方案是 直接实现 WebMvcConfigurer接口即可,因为 WebMvcConfigurerAdapter类同样是实现 WebMvcConfigurer接口
*/
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
/**
* 添加视图跳转控制器
* 当请求为 localhost:8080/tiger/userList 时。自动映射到 类路径下的templates下的 userList.html页面
* 当请求为 localhost:8080/tiger/index 时。自动映射到 类路径下的templates下的 index.html页面
*
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
/** 往前端 Thymeleaf 模板引擎时,开头不要加 "/" ,因为它默认配置的前缀就是:
* spring.thymeleaf.prefix=classpath:/templates/
*/
registry.addViewController("/userList").setViewName("userList");
registry.addViewController("/index").setViewName("index");
}
/**
* 注册拦截器
* .addPathPatterns("/**"):表示拦截整个应用中的所有请求
* .excludePathPatterns("/user/login", "/index"):表示排除这些规则的请求不做拦截,因为 /index是去登录页的,/user/login是用户提交登录的,所以都不能拦截
* 如果是 Spring Boot2以前,声明拦截哪些请求,不拦截哪些请求,这样就可以了,对于所有静态资源目录下的静态资源,它是不会去拦截的
* 即 classpath:/META‐INF/resources/","classpath:/resources/","classpath:/static/","classpath:/public/"下的资源都不会被拦截
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index", "/user/login");
}
}
Spring Boot 2.0 之后
/**
* 注册拦截器
* 而Spring Boot 2及以后开始,默认情况下,Spring Boot 会拦截所有请求,包括静态资源请求
* 所以这样写时,运行之后所有静态资源都会被拦截
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index", "/user/login");
}
}
----null ::: http://localhost:8080/tiger/webjars/bootstrap/4.0.0/css/bootstrap.css
----null ::: http://localhost:8080/tiger/asserts/css/signin.css
----null ::: http://localhost:8080/tiger/asserts/img/bootstrap-solid.svg
/**
* 注册拦截器
* 而Spring Boot 2及以后开始,默认情况下,Spring Boot 会拦截所有请求,包括静态资源请求
* 所以要将静态资源路径排除在拦截的请求路径之内
* /webjars/**:所有 http://localhost:8080/tiger/asserts/** 不再拦截 tiger是应用上下文路径
* /asserts/**:所有 http://localhost:8080/tiger/asserts/** 不再拦截 tiger是应用上下文路径
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/index", "/user/login")
.excludePathPatterns("/webjars/**", "/asserts/**");
}
自定义资源映射
- classpath:/META‐INF/resources/","classpath:/resources/","classpath:/static/","classpath:/public/ ,当静态资源位于 Spring Boot 默认约定的这4个目录下时,则都可以使用在注册拦截器的同时将静态资源排除在外即可,如下的 asserts 与 webjars
/**
* 注册拦截器
* 而Spring Boot 2及以后开始,默认情况下,Spring Boot 会拦截所有请求,包括静态资源请求
* 所以要将静态资源路径排除在拦截的请求路径之内
* /webjars/**:所有 http://localhost:8080/tiger/asserts/** 不再拦截 tiger是应用上下文路径
* /asserts/**:所有 http://localhost:8080/tiger/asserts/** 不再拦截 tiger是应用上下文路径
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/index", "/user/login")
.excludePathPatterns("/webjars/**", "/asserts/**");
}
- 假如现在有另外的静态资源目录不是位于约定的那4个目录下,而是位于类路径下的其它目录怎么办呢?如下所示的“uploadFiles”目录,这个时候再使用上面的方式是不行的,因为uploadFiles本身就不是在约定的静态目录下
/**
* 自定义资源映射 addResourceHandlers
* registry.addResourceHandler("/uploadFiles/**"): 添加静态资源映射路径,和上面的 .excludePathPatterns 原来是一样的
* addResourceLocations("classpath:/uploadFiles/"):添加静态资源路径,即说明自定义的静态资源目录在哪里
* 效果就是:访问 http://localhost:8080/tiger/uploadFiles/** 时都会被当做静态资源而不被拦截,tiger是应用上下文件
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/uploadFiles/**").addResourceLocations("classpath:/uploadFiles/");
}
运行测试
- 在登录后的 userList.html 页面,将登录的用户账号获取并显示出来
<!-- 获取session中的值,替换登录的用户账号-->
<a class="navbar-brand col-sm-3 col-md-2 mr-0"
href="http://getbootstrap.com/docs/4.0/examples/dashboard/#" th:text="${session.userName}">Company name</a>
---后台拦截如下----
2018-07-29 11:52:24.211 INFO 13904 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 11 ms
----null ::: http://localhost:8080/tiger/userList
----华安 ::: http://localhost:8080/tiger/userList