1. 目标
识别操作系统的人的身份,控制他的行为
2. 思路
3. 代码
3.1 创建工具方法执行 MD5 加密
/**
* 尚筹网项目通用工具方法类
*/
public class CrowdUtil {
/**
* 对明文字符串进行DM5加密
* @param source 传入的明文字符串
* @return 加密的结果
*/
public static String md5(String source){
// 1.判断source是否有效
if (source == null || source.length() == 0){
// 2.如果不是有效的字符串抛出异常
throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
}
try {
// 3.获取MessageDigest对象
String algorithm = "md5";
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
// 4.获取明文字符串对应的字节数组
byte[] input = source.getBytes();
// 5.执行加密
byte[] ouput = messageDigest.digest(input);
// 6.创建BigInteger对象
int signum = 1;
BigInteger bigInteger = new BigInteger(signum, ouput);
// 7.按照16进制将bigInteger的值转换为字符串
int radix = 16;
String encoded = bigInteger.toString(radix).toUpperCase();
return encoded;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
}
3.2 创建登录失败异常
/**
* 登录失败后抛出的异常
*/
public class LoginFailedException extends RuntimeException{
private static final long serialVersionUID = 1L;
public LoginFailedException() {
}
public LoginFailedException(String message) {
super(message);
}
public LoginFailedException(String message, Throwable cause) {
super(message, cause);
}
public LoginFailedException(Throwable cause) {
super(cause);
}
public LoginFailedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
3.3 在异常处理器类中增加登录失败异常的处理
@ExceptionHandler(value = ArithmeticException.class)
public ModelAndView resolveMathException(
ArithmeticException exception,
//当前请求对象
HttpServletRequest request,
//当前响应对象
HttpServletResponse response
) throws IOException {
String viewName = "admin-login";
return commonResolve(viewName, exception, request, response);
}
3.4 在登录页面显示异常消息
3.5 handler 方法
@RequestMapping("/admin/do/login.html")
public String doLogin(
@RequestParam("loginAcct") String loginAcct,
@RequestParam("userPswd") String userPswd,
HttpSession session
){
// 调用Service方法执行登录检查
// 这个方法如果能够返回admin对象说明登录成功,如果账号、密码不正确则会抛出异常
Admin admin = adminService.getAdminByLoginAcct(loginAcct, userPswd);
// 将登录成功返回的admin对象存入Ssssion域
session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN, admin);
return "redirect:/admin/to/main/page.html";
}
3.6 service 方法
@Override
public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
// 1,根据登录账号查询Admin对象
// 1.1创建AdminExample对象
AdminExample adminExample = new