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

最新文章

  1. JS函数无响应
  2. 如何在CentOS 7中禁止IPv6
  3. JAVA中序列化和反序列化
  4. 使用本地yum源
  5. css float对于之后布局的影响
  6. php xml 互相转换
  7. 第一个C#应用 【搜索软件】
  8. 李洪强iOS开发之OC[015]#pragma mark的使用
  9. 对typesafe enum模式的改进
  10. Node 之 Express 学习笔记 第一篇 安装
  11. jQuery 在Table中选择input之类的东西注意事项
  12. 【python密码学编程】6.凯撒加密法
  13. Access数据库自动生成设计文档
  14. Go smtp发送邮件,带附件
  15. 用juery的ajax方法调用aspx.cs页面中的webmethod方法
  16. docker17.03.2安装
  17. go 语言之 生产者消费模型
  18. IIS最小配置
  19. Windows下安装Tensorflow—GPU版本
  20. Python小白学习之路(二)—【Pycharm安装与配置】【创建项目】【运算符】【数据类型】

热门文章

  1. C++#pragma pack指令
  2. Android(java)学习笔记184:多媒体之 MediaPlayer使用
  3. 深度剖析 MySQL 事务隔离
  4. VBA Promming——入门教程
  5. 油猴和EX-百度脚本 百度网盘下载
  6. Windows Server 2012 R2 with Update (x64) - DVD (Chinese-Simplified)
  7. 【软件构造】第三章第四节 面向对象编程OOP
  8. JavaSE-31 Java正则表达式
  9. Angular JavaScript内存溢出问题 (FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory)
  10. 北京化工大学2018年10月程序设计竞赛部分题解(A,C,E,H)