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实现原始的登录验证的更多相关文章

  1. spring boot高性能实现二维码扫码登录(中)——Redis版

    前言 本打算用CountDownLatch来实现,但有个问题我没有考虑,就是当用户APP没有扫二维码的时候,线程会阻塞5分钟,这反而造成性能的下降.好吧,现在回归传统方式:前端ajax每隔1秒或2秒发 ...

  2. spring boot高性能实现二维码扫码登录(下)——订阅与发布机制版

     前言 基于之前两篇(<spring boot高性能实现二维码扫码登录(上)——单服务器版>和<spring boot高性能实现二维码扫码登录(中)——Redis版>)的基础, ...

  3. spring boot高性能实现二维码扫码登录(上)——单服务器版

    前言 目前网页的主流登录方式是通过手机扫码二维码登录.我看了网上很多关于扫码登录博客后,发现基本思路大致是:打开网页,生成uuid,然后长连接请求后端并等待登录认证相应结果,而后端每个几百毫秒会循环查 ...

  4. 实战!spring Boot security+JWT 前后端分离架构认证登录!

    大家好,我是不才陈某~ 认证.授权是实战项目中必不可少的部分,而Spring Security则将作为首选安全组件,因此陈某新开了 <Spring Security 进阶> 这个专栏,写一 ...

  5. Spring Boot 简单的请求示例(包括请求体验证)

    1.先做个最简单的Get请求 新建一个Controller , 并给他添加注解@RestController 它是@Controller和@ResponseBody的组合注解,告诉Spring我是一个 ...

  6. spring boot springMVC扩展配置 。WebMvcConfigurer ,WebMvcConfigurerAdapter

    摘要: 在spring boot中 MVC这部分也有默认自动配置,也就是说我们不用做任何配置,那么也是OK的,这个配置类就是 WebMvcAutoConfiguration,但是也时候我们想设置自己的 ...

  7. 第3章 Spring Boot 入门指南

    Part II. 入门指南 如果你刚刚开始使用Spring Boot,这是你的一部分内容! 在这里我们将会回答一些基本的“what?”, “how?” 和 “why?”的问题. 在这里你会找到一个详细 ...

  8. SpringBoot官方文档学习(一)开发你的第一个Spring Boot应用

    一些准备工作: 本节介绍如何开发一个简单的“ Hello World!” Web应用程序,该应用程序重点介绍Spring Boot的一些关键功能.我们使用Maven来构建该项目,因为大多数IDE都支持 ...

  9. Spring Boot项目中如何定制拦截器

    本文首发于个人网站:Spring Boot项目中如何定制拦截器 Servlet 过滤器属于Servlet API,和Spring关系不大.除了使用过滤器包装web请求,Spring MVC还提供Han ...

随机推荐

  1. (2)Ngixn 编译安装设置开机自启

    设置nginx开机自启 #!/bin/sh # # nginx - this script starts and stops the nginx daemon # # chkconfig: - 85 ...

  2. cluvfy comp命令用法

    1.获取集群验证工具cluvfy的帮助信息 grid@rac1:/home/grid>cluvfy -help USAGE: cluvfy [ -help ] cluvfy stage { -l ...

  3. docker新手入门(基本命令以及介绍)

    Docker 的核心内容 镜像 (Image) 容器 (Container) 仓库 (Repository) Registry 用来保存用户构建的镜像 docker的开始使用: 1. docker  ...

  4. mfc消息

    ON_COMMAND是菜单和工具栏项处理消息的宏 ON_MESSAGE是处理自定义消息的宏 ON_NOTIFY 是控件向其父窗口发送消息处理的宏 对这几个消息的理解要先了解一下Window消息的背景. ...

  5. python之道03

    1.有变量name = " aleX leNb " 完成如下操作: 移除 name 变量对应的值两边的空格,并输出处理结果 答案: name = " aleX leNb ...

  6. [SNOI2019]数论

    题目 考虑对于每一个\(a_i\)计算有多少个\(0<x\leq T-1\)满足\(x\equiv a_i(mod\ P)\)且\(x\ mod\ Q \in B\) 显然\(x=a_i+k\t ...

  7. 深度学总结:skip-gram pytorch实现

    文章目录 skip-gram pytorch 朴素实现网络结构训练过程:使用nn.NLLLoss()batch的准备,为unsupervised,准备数据获取(center,contex)的pair: ...

  8. Spring框架 (log4j :WARN No appenders could be found for logger log4j:WARN Please initialize the log4j system properly.)问题解决

    Spring框架需要的jar包 1.Spring压缩包中的四个核心JAR包 beans .context.core 和expression 下载地址: https://pan.baidu.com/s/ ...

  9. Java 垃圾回收机制 (分代垃圾回收ZGC)

    什么是自动垃圾回收? 自动垃圾回收是一种在堆内存中找出哪些对象在被使用,还有哪些对象没被使用,并且将后者删掉的机制.所谓使用中的对象(已引用对象),指的是程序中有指针指向的对象:而未使用中的对象(未引 ...

  10. mysql 数据库 show命令

    MySQL中有很多的基本命令,show命令也是其中之一,在很多使用者中对show命令的使用还容易产生混淆,本文汇集了show命令的众多用法. 1. show tables或show tables fr ...