原文地址:http://www.work100.net/training/monolithic-project-iot-cloud-admin-login.html
更多教程:光束云 - 免费课程
后台登录
序号 | 文内章节 | 视频 |
---|---|---|
1 | 删除无用代码 | - |
2 | 改造iot-cloud-commons项目 | - |
3 | 修改AuthManagerMapper.xml映射文件 | - |
4 | 修改AuthManagerDao接口 | - |
5 | 修改AuthManagerService接口 | - |
6 | 修改AuthManagerServiceImpl实现 | - |
7 | 改造LoginController | - |
8 | 改造login.jsp | - |
9 | 改造拦截器 | - |
10 | 测试运行 | - |
11 | 实例源码 | - |
请参照如上章节导航
进行阅读
1.删除无用代码
因为案例将采用数据库存储,故需要删除以前用于模拟数据的相关代码。
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
实现类
2.改造iot-cloud-commons项目
ConstantUtils
工具类
修改 net.work100.training.stage2.iot.cloud.commons.constant
包下 ConstantUtils
工具类,代码如下:
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
工具类,代码如下:
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
项目下。
3.修改AuthManagerMapper.xml映射文件
在 AuthManagerMapper.xml
映射文件中新增 getByUserName
查询,用于通过 UserName
获取用户信息,代码如下:
<select id="getByUserName" resultType="AuthManager">
SELECT
<include refid="authManagerColumns" />
FROM
auth_manager AS a
WHERE
a.user_name = #{userName}
</select>
4.修改AuthManagerDao接口
修改 AuthManagerDao
接口,增加 getByUserName
方法,代码如下:
/**
* 获取账户对象
*
* @param userName 用户名
* @return
*/
AuthManager getByUserName(String userName);
5.修改AuthManagerService接口
修改 AuthManagerService
接口,增加 login
方法,代码如下:
/**
* 登录验证
*
* @param userName 用户名
* @param password 密码
* @return
*/
AuthManager login(String userName, String password);
6.修改AuthManagerServiceImpl实现
修改 AuthManagerServiceImpl
实现,增加 login
方法的实现,代码如下:
@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;
}
7.改造LoginController
改造 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";
}
}
8.改造login.jsp
改造 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>
9.改造拦截器
为了区分后台和前台用户的 Session
及 Cookie
,我们修改了对应 Session
及 Cookie
的 ID
,因此要调整拦截器的代码。
LoginInterceptor
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 {
}
}
PermissionInterceptor
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 {
}
}
10.测试运行
单元测试
在 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 |
然后,验证登录、退出、以及记住我等功能。
11.实例源码
实例源码已经托管到如下地址:
-
https://github.com/work100-net/training-stage2/tree/master/iot-cloud3
-
https://gitee.com/work100-net/training-stage2/tree/master/iot-cloud3
如果对课程内容感兴趣,可以扫码关注我们的
公众号
或QQ群
,及时关注我们的课程更新