Spring Boot使用HandlerInterceptorAdapter和WebMvcConfigurerAdapter实现原始的登录验证
HandlerInterceptorAdapter的介绍:http://www.cnblogs.com/EasonJim/p/7704740.html,相当于一个Filter拦截器,但是这个颗粒度更细,能使用Spring的@Autowired注入。
WebMvcConfigurerAdapter的介绍:http://www.cnblogs.com/EasonJim/p/7720095.html,类似于配置Bean的XML。
最原始的登录验证实现原理:
1、通过Session保存登录状态。
2、加入Filter拦截器进行每个页面拦截判断Session是否有效,如果没有效就跳转到登录页面。
3、通过Bean注入器把Filter注入。
实现步骤:
1、新建Filter
package com.jsoft.springboottest.springboottest1.filter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.jsoft.springboottest.springboottest1.config.WebSecurityConfig; public class SecurityInterceptor extends HandlerInterceptorAdapter { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute(WebSecurityConfig.SESSION_KEY) != null)
return true; // 跳转登录
String url = "/login";
response.sendRedirect(url);
return false;
}
}
2、新建Config
package com.jsoft.springboottest.springboottest1.config; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.jsoft.springboottest.springboottest1.filter.SecurityInterceptor; @Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter { /**
* 登录session key
*/
public static final String SESSION_KEY = "user"; @Bean
public SecurityInterceptor getSecurityInterceptor() {
return new SecurityInterceptor();
} @Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor()); // 排除配置
addInterceptor.excludePathPatterns("/error");
addInterceptor.excludePathPatterns("/login**"); // 拦截配置
addInterceptor.addPathPatterns("/**");
}
}
3、新建Controller
package com.jsoft.springboottest.springboottest1.controller; import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute; import com.jsoft.springboottest.springboottest1.config.WebSecurityConfig; @Controller
public class TestController { @GetMapping("/")
public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String account, Model model) {
model.addAttribute("name", account);
return "index";
} @GetMapping("/login")
public String login() {
return "login";
} @PostMapping("/login")
public @ResponseBody Map<String, Object> loginPost(String account, String password, HttpSession session) {
Map<String, Object> map = new HashMap<String, Object>();
if (!"123456".equals(password)) {
map.put("success", false);
map.put("message", "密码错误");
return map;
} // 设置session
session.setAttribute(WebSecurityConfig.SESSION_KEY, account); map.put("success", true);
map.put("message", "登录成功");
return map;
} @GetMapping("/logout")
public String logout(HttpSession session) {
// 移除session
session.removeAttribute(WebSecurityConfig.SESSION_KEY);
return "redirect:/login";
}
}
4、HTML
login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>简单登录认证</title>
<script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script>
<script type="text/javascript">
/*<![CDATA[*/
var app = angular.module('app', []);
app.controller('MainController', function($rootScope, $scope, $http) {
$scope.message = '';
$scope.account = '';
$scope.password = '';
//登录
$scope.login = function() {
$scope.message = '';
$http(
{
url : '/login',
method : 'POST',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data : 'account=' + $scope.account + '&password='
+ $scope.password
}).success(function(r) {
if (!r.success) {
$scope.message = r.message;
return;
}
window.location.href = '/';
});
}
});
/*]]>*/
</script>
</head>
<body ng-app="app" ng-controller="MainController">
<h1>简单登录认证</h1> <table cellspacing="1" style="background-color: #a0c6e5">
<tr>
<td>账号:</td>
<td><input ng-model="account" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" ng-model="password" /></td>
</tr>
</table>
<input type="button" value="登录" ng-click="login()" />
<br />
<font color="red" ng-show="message">{{message}}</font>
</body>
</html>
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>简单登录认证</title>
</head>
<body>
<h1>简单登录认证</h1>
<h3 th:text="'登录用户:' + ${name}"></h3> <a href="/logout">注销</a>
</body>
</html>
示例代码:https://github.com/easonjim/5_java_example/tree/master/springboottest/springboottest4
参考:
http://www.cnblogs.com/GoodHelper/p/6343190.html
Spring Boot使用HandlerInterceptorAdapter和WebMvcConfigurerAdapter实现原始的登录验证的更多相关文章
- spring boot高性能实现二维码扫码登录(中)——Redis版
前言 本打算用CountDownLatch来实现,但有个问题我没有考虑,就是当用户APP没有扫二维码的时候,线程会阻塞5分钟,这反而造成性能的下降.好吧,现在回归传统方式:前端ajax每隔1秒或2秒发 ...
- spring boot高性能实现二维码扫码登录(下)——订阅与发布机制版
前言 基于之前两篇(<spring boot高性能实现二维码扫码登录(上)——单服务器版>和<spring boot高性能实现二维码扫码登录(中)——Redis版>)的基础, ...
- spring boot高性能实现二维码扫码登录(上)——单服务器版
前言 目前网页的主流登录方式是通过手机扫码二维码登录.我看了网上很多关于扫码登录博客后,发现基本思路大致是:打开网页,生成uuid,然后长连接请求后端并等待登录认证相应结果,而后端每个几百毫秒会循环查 ...
- 实战!spring Boot security+JWT 前后端分离架构认证登录!
大家好,我是不才陈某~ 认证.授权是实战项目中必不可少的部分,而Spring Security则将作为首选安全组件,因此陈某新开了 <Spring Security 进阶> 这个专栏,写一 ...
- Spring Boot 简单的请求示例(包括请求体验证)
1.先做个最简单的Get请求 新建一个Controller , 并给他添加注解@RestController 它是@Controller和@ResponseBody的组合注解,告诉Spring我是一个 ...
- spring boot springMVC扩展配置 。WebMvcConfigurer ,WebMvcConfigurerAdapter
摘要: 在spring boot中 MVC这部分也有默认自动配置,也就是说我们不用做任何配置,那么也是OK的,这个配置类就是 WebMvcAutoConfiguration,但是也时候我们想设置自己的 ...
- 第3章 Spring Boot 入门指南
Part II. 入门指南 如果你刚刚开始使用Spring Boot,这是你的一部分内容! 在这里我们将会回答一些基本的“what?”, “how?” 和 “why?”的问题. 在这里你会找到一个详细 ...
- SpringBoot官方文档学习(一)开发你的第一个Spring Boot应用
一些准备工作: 本节介绍如何开发一个简单的“ Hello World!” Web应用程序,该应用程序重点介绍Spring Boot的一些关键功能.我们使用Maven来构建该项目,因为大多数IDE都支持 ...
- Spring Boot项目中如何定制拦截器
本文首发于个人网站:Spring Boot项目中如何定制拦截器 Servlet 过滤器属于Servlet API,和Spring关系不大.除了使用过滤器包装web请求,Spring MVC还提供Han ...
随机推荐
- Eclipse--java.lang.OutOfMemoryError: PermGen space
这一段时间,Eclipse总是死掉,几乎是稍微操作快一点就会死掉,几分钟一次,搞得人郁闷至极.浪费了不少时间,在网上搜了下,看到很多朋友也出现类似的情况,在网上求救,但是网上的办法都只是说通过修改ec ...
- Web开发者不容错过的10个HTML5工具
HTML5已经成为当今世界的一个必然组成部分.由于World Wide Web万维网是使用超文本标记语言来架构和呈现的,于是HTML5成为了最流行的编程语言之一.随着网络的不断扩张,Web开发人员非常 ...
- 深入了解JVM(Java虚拟机)
虚拟机 JRE由Java API和JVM组成,JVM通过类加载器(Class Loader)加类Java应用,并通过Java API进行执行. 虚拟机(VM: Virtual Machine)是通过软 ...
- 枚举 || CodeForces 742B Arpa’s obvious problem and Mehrdad’s terrible solution
给出N*M矩阵,对于该矩阵有两种操作: 1.交换两列,对于整个矩阵只能操作一次 2.每行交换两个数. 交换后是否可以使每行都递增. *解法:N与M均为20,直接枚举所有可能的交换结果,进行判断 每次枚 ...
- golang 解析json 动态数组
#cat file { "Bangalore_City": "35_Temperature", "NewYork_City": " ...
- 【linux 06】 linux中的用户权限、文件权限与目录权限
1.用户及用户组的概念: 1.文件所有者 2.用户组 3.用户 以root登录Linux之后,执行ls -al,会看到有关文件属性的信息 -rw-r--r--,第1个字符代表这个文件是“目录,文件或链 ...
- redis:安装配置主从
1.安装依赖包 yum install gcc gcc-c++ -y 2.下载安装包,解压 cd /usr/local/src/wget http://download.redis.io/releas ...
- React深入 - 手写redux api
简介: 手写实现redux基础api createStore( )和store相关方法 api回顾: createStore(reducer, [preloadedState], enhancer) ...
- 周三面试Python开发,这几道Python面试题差点答错,Python面试题No7
第1题:阅读下面的代码,默读出A0,A1至An的最终值. A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5))) A1 = range(10) A2 = [ ...
- Spring MVC 接入 rabbitMQ
依赖包 <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spr ...