Spring Boot使用HandlerInterceptorAdapter和WebMvcConfigurerAdapter實現原始的登錄驗證
阿新 • • 發佈:2017-10-25
onf ota throws 介紹 fig config sta apt 進行
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; importcom.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實現原始的登錄驗證