原文地址:http://www.work100.net/training/monolithic-project-iot-cloud-admin-login.html
更多教程:光束雲 - 免費課程html
序號 | 文內章節 | 視頻 |
---|---|---|
1 | 刪除無用代碼 | - |
2 | 改造iot-cloud-commons項目 | - |
3 | 修改AuthManagerMapper.xml映射文件 | - |
4 | 修改AuthManagerDao接口 | - |
5 | 修改AuthManagerService接口 | - |
6 | 修改AuthManagerServiceImpl實現 | - |
7 | 改造LoginController | - |
8 | 改造login.jsp | - |
9 | 改造攔截器 | - |
10 | 測試運行 | - |
11 | 實例源碼 | - |
請參照如上章節導航
進行閱讀java
由於案例將採用數據庫存儲,故須要刪除之前用於模擬數據的相關代碼。git
iot-cloud-domain
項目下,刪除 User
類iot-cloud-web-admin
項目下,刪除 UserDao
接口iot-cloud-web-admin
項目下,刪除 UserDaoImpl
實現類及上層包 impl
iot-cloud-web-admin
項目下,刪除 UserService
接口iot-cloud-web-admin
項目下,刪除 UserServiceImpl
實現類ConstantUtils
工具類修改 net.work100.training.stage2.iot.cloud.commons.constant
包下 ConstantUtils
工具類,代碼以下:github
package net.work100.training.stage2.iot.cloud.commons.constant; /** * <p>Title: ConstantUtils</p> * <p>Description: </p> * <p>Url: http://www.work100.net/training/monolithic-project-iot-cloud-admin.html</p> * * @author liuxiaojun * @date 2020-02-22 16:20 * ------------------- History ------------------- * <date> <author> <desc> * 2020-02-22 liuxiaojun 初始建立 * ----------------------------------------------- */ public class ConstantUtils { public static final String SESSION_MANAGER = "manager"; public static final String COOKIE_MANAGER_REMEMBER = "manager_remember"; public static final String COOKIE_MANAGER_USERNAME = "manager_username"; }
CookieUtils
工具類包 net.work100.training.stage2.iot.cloud.commons.utils
下新增 CookieUtils
工具類,代碼以下:web
package net.work100.training.stage2.iot.cloud.commons.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; /** * <p>Title: CookieUtils</p> * <p>Description: </p> * <p>Url: http://www.work100.net/training/monolithic-project-iot-cloud-admin.html</p> * * @author liuxiaojun * @date 2020-02-15 11:36 * ------------------- History ------------------- * <date> <author> <desc> * 2020-02-15 liuxiaojun 初始建立 * ----------------------------------------------- */ public final class CookieUtils { /** * 獲得Cookie的值(不解碼) * * @param request 請求 * @param cookieName Cookie名稱 * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName) { return getCookieValue(request, cookieName, false); } /** * 獲得Cookie的值 * * @param request 請求 * @param cookieName Cookie名稱 * @param isDecoder 是否解碼 * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { if (isDecoder) { retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8"); } else { retValue = cookieList[i].getValue(); } break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; } /** * 獲得Cookie的值 * * @param request 請求 * @param cookieName Cookie名稱 * @param encodeString 編碼格式 * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString); break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; } /** * 設置Cookie的值 不設置生效時間默認瀏覽器關閉即失效,也不編碼 * * @param request 請求 * @param response 響應 * @param cookieName Cookie名稱 * @param cookieValue Cookie值 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) { setCookie(request, response, cookieName, cookieValue, -1); } /** * 設置Cookie的值 在指定時間內生效,但不編碼 * * @param request 請求 * @param response 響應 * @param cookieName Cookie名稱 * @param cookieValue Cookie值 * @param cookieMaxAge cookie生效的最大秒數 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxAge) { setCookie(request, response, cookieName, cookieValue, cookieMaxAge, false); } /** * 設置Cookie的值 不設置生效時間 * * @param request 請求 * @param response 響應 * @param cookieName Cookie名稱 * @param cookieValue Cookie值 * @param isEncode 是否編碼 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, boolean isEncode) { setCookie(request, response, cookieName, cookieValue, -1, isEncode); } /** * 設置Cookie的值 在指定時間內生效, 編碼參數 * * @param request 請求 * @param response 響應 * @param cookieName Cookie名稱 * @param cookieValue Cookie值 * @param cookieMaxAge cookie生效的最大秒數 * @param isEncode 是否編碼 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxAge, boolean isEncode) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxAge, isEncode); } /** * 設置Cookie的值 在指定時間內生效, 編碼參數(指定編碼) * * @param request 請求 * @param response 響應 * @param cookieName Cookie名稱 * @param cookieValue Cookie值 * @param cookieMaxAge cookie生效的最大秒數 * @param encodeString 編碼格式 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxAge, String encodeString) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxAge, encodeString); } /** * 刪除Cookie帶cookie域名 * * @param request 請求 * @param response 響應 * @param cookieName Cookie名稱 */ public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) { doSetCookie(request, response, cookieName, "", -1, false); } /** * 設置Cookie的值,並使其在指定時間內生效 * * @param request 請求 * @param response 響應 * @param cookieName Cookie名稱 * @param cookieValue Cookie值 * @param cookieMaxAge cookie生效的最大秒數 * @param isEncode 是否編碼 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxAge, boolean isEncode) { try { if (cookieValue == null) { cookieValue = ""; } else if (isEncode) { cookieValue = URLEncoder.encode(cookieValue, "utf-8"); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxAge > 0) { cookie.setMaxAge(cookieMaxAge); } if (null != request) { // 設置域名的cookie String domainName = getDomainName(request); if (!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } /** * 設置Cookie的值,並使其在指定時間內生效 * * @param request 請求 * @param response 響應 * @param cookieName Cookie名稱 * @param cookieValue Cookie值 * @param cookieMaxAge cookie生效的最大秒數 * @param encodeString 編碼格式 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxAge, String encodeString) { try { if (cookieValue == null) { cookieValue = ""; } else { cookieValue = URLEncoder.encode(cookieValue, encodeString); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxAge > 0) cookie.setMaxAge(cookieMaxAge); if (null != request) { // 設置域名的cookie String domainName = getDomainName(request); if (!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } /** * 獲得cookie的域名 * * @param request 請求 * @return */ private static final String getDomainName(HttpServletRequest request) { String domainName = null; String serverName = request.getRequestURL().toString(); if (serverName == null || serverName.equals("")) { domainName = ""; } else { serverName = serverName.toLowerCase(); serverName = serverName.substring(7); final int end = serverName.indexOf("/"); serverName = serverName.substring(0, end); final String[] domains = serverName.split("\\."); int len = domains.length; if (len > 3) { // www.xxx.com.cn domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1]; } else if (len <= 3 && len > 1) { // xxx.com or xxx.cn domainName = "." + domains[len - 2] + "." + domains[len - 1]; } else { domainName = serverName; } } if (domainName != null && domainName.indexOf(":") > 0) { String[] ary = domainName.split("\\:"); domainName = ary[0]; } return domainName; } }
因
CookieUtils
依賴javax.servlet:javax.servlet-api
包,因此將iot-cloud-web-admin
項目下對javax.servlet:javax.servlet-api
的依賴移動到iot-cloud-commons
項目下。spring
在 AuthManagerMapper.xml
映射文件中新增 getByUserName
查詢,用於經過 UserName
獲取用戶信息,代碼以下:數據庫
<select id="getByUserName" resultType="AuthManager"> SELECT <include refid="authManagerColumns" /> FROM auth_manager AS a WHERE a.user_name = #{userName} </select>
修改 AuthManagerDao
接口,增長 getByUserName
方法,代碼以下:api
/** * 獲取帳戶對象 * * @param userName 用戶名 * @return */ AuthManager getByUserName(String userName);
修改 AuthManagerService
接口,增長 login
方法,代碼以下:瀏覽器
/** * 登陸驗證 * * @param userName 用戶名 * @param password 密碼 * @return */ AuthManager login(String userName, String password);
修改 AuthManagerServiceImpl
實現,增長 login
方法的實現,代碼以下:spring-mvc
@Override public AuthManager login(String userName, String password) { AuthManager authManager = authManagerDao.getByUserName(userName); if (authManager != null && authManager.getStatus() == 1) { // 驗證密碼,若是驗證經過,則返回用戶信息 if (EncryptionUtils.validateEncryptPassword(password, authManager.getPassword())) { return authManager; } } return null; }
改造 LoginController
類,經過 authManagerService
來實現管理後臺登陸,並完成記住我功能(記住我含義:記住用戶名),代碼以下:
package net.work100.training.stage2.iot.cloud.web.admin.web.controller; import net.work100.training.stage2.iot.cloud.commons.constant.ConstantUtils; import net.work100.training.stage2.iot.cloud.commons.utils.CookieUtils; import net.work100.training.stage2.iot.cloud.domain.AuthManager; import net.work100.training.stage2.iot.cloud.web.admin.service.AuthManagerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <p>Title: LoginController</p> * <p>Description: </p> * <p>Url: http://www.work100.net/training/monolithic-frameworks-spring-mvc-maven-module.html</p> * * @author liuxiaojun * @date 2020-02-22 16:15 * ------------------- History ------------------- * <date> <author> <desc> * 2020-02-22 liuxiaojun 初始建立 * ----------------------------------------------- */ @Controller public class LoginController { @Autowired private AuthManagerService authManagerService; /** * 登陸頁面 * * @return */ @RequestMapping(value = {"", "login"}, method = RequestMethod.GET) public String login(HttpServletRequest request, Model model) { boolean isRemember = "on".equals(CookieUtils.getCookieValue(request, ConstantUtils.COOKIE_MANAGER_REMEMBER)); if (isRemember) { String userName = CookieUtils.getCookieValue(request, ConstantUtils.COOKIE_MANAGER_USERNAME); model.addAttribute("remember", isRemember); model.addAttribute("userName", userName); } return "login"; } /** * 登陸邏輯 * * @param userName 用戶名 * @param password 登陸密碼 * @return */ @RequestMapping(value = "login", method = RequestMethod.POST) public String login(@RequestParam(required = true) String userName, @RequestParam(required = true) String password, @RequestParam(required = false) String remember, Model model, HttpServletRequest request, HttpServletResponse response) { boolean isRemember = "on".equalsIgnoreCase(remember); AuthManager authManager = authManagerService.login(userName, password); // 登陸成功 if (authManager != null) { // 處理記住我功能(記住用戶名) if (isRemember) { // Cookie 存儲一週 CookieUtils.setCookie(request, response, ConstantUtils.COOKIE_MANAGER_REMEMBER, "on", 7 * 24 * 60 * 60); CookieUtils.setCookie(request, response, ConstantUtils.COOKIE_MANAGER_USERNAME, userName, 7 * 24 * 60 * 60); } else { // 刪除 Cookie CookieUtils.deleteCookie(request, response, ConstantUtils.COOKIE_MANAGER_REMEMBER); CookieUtils.deleteCookie(request, response, ConstantUtils.COOKIE_MANAGER_USERNAME); } // 將登陸信息記入Session request.getSession().setAttribute(ConstantUtils.SESSION_MANAGER, authManager); return "redirect:/main"; } // 登陸失敗 else { model.addAttribute("userName", userName); model.addAttribute("remember", isRemember); model.addAttribute("message", "用戶名或者密碼錯誤!"); return "login"; } } /** * 登陸註銷 * * @param request * @return */ @RequestMapping(value = "logout", method = RequestMethod.GET) public String logout(HttpServletRequest request) { request.getSession().invalidate(); return "redirect:/login"; } }
改造 login.jsp
頁面的 form
表單部分,代碼以下:
<form action="/login" method="post"> <div class="input-group mb-3"> <input name="userName" type="text" class="form-control" placeholder="用戶名" value="${userName}"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-user"></span> </div> </div> </div> <div class="input-group mb-3"> <input name="password" type="password" class="form-control" placeholder="登陸密碼"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="row"> <div class="col-8"> <div class="icheck-primary"> <input type="checkbox" id="remember" name="remember" ${remember?"checked":""}> <label for="remember"> 記住我 </label> </div> </div> <!-- /.col --> <div class="col-4"> <button type="submit" class="btn btn-primary btn-block">登陸</button> </div> <!-- /.col --> </div> </form>
爲了區分後臺和前臺用戶的 Session
及 Cookie
,咱們修改了對應 Session
及 Cookie
的 ID
,所以要調整攔截器的代碼。
package net.work100.training.stage2.iot.cloud.web.admin.web.interceptor; import net.work100.training.stage2.iot.cloud.commons.constant.ConstantUtils; import net.work100.training.stage2.iot.cloud.domain.AuthManager; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <p>Title: LoginInterceptor</p> * <p>Description: </p> * <p>Url: http://www.work100.net/training/monolithic-project-iot-cloud-admin.html</p> * * @author liuxiaojun * @date 2020-02-20 16:22 * ------------------- History ------------------- * <date> <author> <desc> * 2020-02-20 liuxiaojun 初始建立 * ----------------------------------------------- */ public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("LoginInterceptor"); AuthManager authManager = (AuthManager) request.getSession().getAttribute(ConstantUtils.SESSION_MANAGER); // 未登陸 if (authManager == null) { response.sendRedirect("/login"); } // 爲 true 時放行,進入 postHandle return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
package net.work100.training.stage2.iot.cloud.web.admin.web.interceptor; import net.work100.training.stage2.iot.cloud.commons.constant.ConstantUtils; import net.work100.training.stage2.iot.cloud.domain.AuthManager; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <p>Title: PermissionInterceptor</p> * <p>Description: </p> * <p>Url: http://www.work100.net/training/monolithic-project-iot-cloud-admin.html</p> * * @author liuxiaojun * @date 2020-02-20 21:16 * ------------------- History ------------------- * <date> <author> <desc> * 2020-02-20 liuxiaojun 初始建立 * ----------------------------------------------- */ public class PermissionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("PermissionInterceptor"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (modelAndView != null && "login".equals(modelAndView.getViewName())) { AuthManager authManager = (AuthManager) request.getSession().getAttribute(ConstantUtils.SESSION_MANAGER); if (authManager != null) { response.sendRedirect("/main"); } } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
在 AuthManagerServiceTest
單元測試文件中增長測試方法,代碼以下:
@Test public void testLogin() { String userName = "xiaojun.liu"; String password = "123456"; AuthManager authManager = authManagerService.login(userName, password); Assert.assertNotNull(authManager); }
運行
testLogin
方法,預期將測試成功
從新配置 Tomcat
,並啓動運行,登陸頁面以下:
輸入用戶名及密碼,默認管理員帳戶爲:
用戶名 | 密碼 |
---|---|
xiaojun.liu | 123456 |
而後,驗證登陸、退出、以及記住我等功能。
實例源碼已經託管到以下地址:
若是對課程內容感興趣,能夠掃碼關注咱們的
公衆號
或QQ羣
,及時關注咱們的課程更新