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
参考: