登录框html+layui
<div class="center">
<form class="loginContent layui-form" th:action="@{/admin/login}" method="post">
<div class="myitem">
<img class="myimg" th:src="@{/static/admin/img/icon-login-user.png}">
<input class="myinput" name="username" th:value="${shiroUser?.loginName}" placeholder="用户名" lay-verify="required" type="text" autocomplete="off">
</div>
<div class="myitem">
<img class="myimg" th:src="@{/static/admin/img/icon-login-pwd.png}">
<input class="myinput" name="password" th:value="${shiroUser?.password}" placeholder="密码" lay-verify="required" type="password" autocomplete="off">
</div>
<div class="myitem">
<input class="myinput" style="width: 230px" name="code" placeholder="验证码" lay-verify="required" type="text" autocomplete="off">
<img th:src="@{/admin/captcha}" width="116" height="36" th:id="randImage">
</div>
<div class="mybtn">
<button class="submit" lay-submit lay-filter="login">登 录</button>
</div>
<div style="margin-top: 30px">
<input type="checkbox" name="rememberMe" lay-skin="primary" title="记住密码" th:checked="${shiroUser?.rememberMe}">
</div>
</form>
</div>
layui.js处理
//引入layui规范
layui.use(['form', 'layer', 'jquery'], function () {
var form = layui.form,
layer = parent.layer === undefined ? layui.layer : parent.layer;
$ = layui.jquery;
//登录按钮事件
form.on("submit(login)", function (data) {
//layer进行页面弹层
var loadIndex = layer.load(2, {shade: [0.3, '#333']});
//把【记住密码】的状态赋给要传到后端的data
if ($('form').find('input[type="checkbox"]')[0].checked) {
data.field.rememberMe = true;
} else {
data.field.rememberMe = false;
}
//发起post提交,提供action路径
$.post(data.form.action, data.field, function (res) {
console.log(res)
//关闭layer弹层
layer.close(loadIndex);
//登录验证通过进行跳转
if (res.success) {
//跳转responseEntity.setAny("url", "/admin/index");
top.window.location.href = ctxpath + res.url;
} else {
layer.msg(res.reason);
//触发验证码点击事件
$("#randImage").click();
}
});
return false;
});
//验证码点击事件
$("#randImage").click(function () {
this.src = ctxpath + "/admin/captcha?t=" + Math.random();
});
}
控制层接受手动地址栏请求:http://localhost:8080/admin/login
@GetMapping("/admin/login")
public String login(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
//如果用户是第一次访问,那么得到的cookies将是null
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals("cxjk_user")) {
try {
//解码
String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
JSONObject data = JSON.parseObject(value);
ShiroUser shiroUser = new ShiroUser(null, data.getString("loginName"), data.getString("password"), Boolean.parseBoolean(data.getString("rememberMe")), null, null, null);
request.setAttribute("shiroUser", shiroUser);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
return "/admin/login";
}
点击登录按钮,发起post请求
@PostMapping("/admin/login")
@ResponseBody// ResponseEntity继承自HashMap<String,Object>类
public ResponseEntity login(HttpServletRequest request, HttpServletResponse response, String username, String password, String code, String rememberMe) {
//验证输入框是否为空
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
return ResponseEntity.failure("登录失败", "用户名或者密码不能为空");
} else if (StringUtils.isBlank(code)) {
return ResponseEntity.failure("登录失败", "验证码不能为空");
}
//获取当前浏览器用户的session对象
HttpSession session = request.getSession();
if (session == null) {
return ResponseEntity.failure("登录失败", "session超时");
}
//获取session验证码值
String trueCode = (String) session.getAttribute(Constants.VALIDATE_CODE);
//验证码如果为空,则超时
if (StringUtils.isBlank(trueCode)) {
return ResponseEntity.failure("登录失败", "验证码超时");
}
//如果输入框code为空 或 验证码输入不正确 则验证码登录失败
if (StringUtils.isBlank(code) || !trueCode.toLowerCase().equals(code.toLowerCase())) {
return ResponseEntity.failure("登录失败", "验证码错误");
} else {
//清空 验证码
session.removeAttribute(Constants.VALIDATE_CODE);
String errorMsg = null;
/*当前用户*/
Subject user = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password, Boolean.parseBoolean(rememberMe));
try {
user.login(token);
log.debug(username + "用户" + LocalDate.now().toString() + ":======》登陆系统!");
if (Boolean.parseBoolean(rememberMe)) {
//加cookie
Cookie cookie = this.createCookie("cxjk_user", username, password, rememberMe);
if (cookie != null) {
cookie.setMaxAge(7*24*60*60);//最大保存时间 一周
response.addCookie(cookie);
}
} else {
Cookie[] cookies = request.getCookies();
//如果用户是第一次访问,那么得到的cookies将是null
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals("cxjk_user")) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}
}
} catch (IncorrectCredentialsException e) {
errorMsg = "用户名或密码错误!";
} catch (UnknownAccountException e) {
errorMsg = "用户名或密码错误!";
} catch (LockedAccountException e) {
errorMsg = "用户名或密码错误!";
} catch (DisabledAccountException e) {
errorMsg = "用户名或密码错误!";
}
//判断是否为空或空串
if (StringUtils.isBlank(errorMsg)) {
ResponseEntity responseEntity = new ResponseEntity();
responseEntity.setSuccess(Boolean.TRUE);
//登陆成功将index地址存入map中,key为"url"
responseEntity.setAny("url", "/admin/index");
return responseEntity;
} else {
return ResponseEntity.failure("登录失败", errorMsg);
}
}
}
createCookie方法
private Cookie createCookie(String key, String userName, String password, String rememberMe) {
try {
Map<String, String> data = new HashMap<>();
data.put("loginName", userName);
data.put("password", password);
data.put("rememberMe", rememberMe);
//转成JSON并进行加码
return new Cookie(key, URLEncoder.encode(JSON.toJSONString(data), "UTF-8"));
} catch (Exception e) {
log.error("缓存用户信息系统异常", e);
}
return null;
}
处理"/admin/index"请求进行跳转
@GetMapping("/admin/index")
public String index(HttpServletRequest request) {
return "/admin/index";
}
index.html
<!--右侧主体内容-->
<div class="layui-tab-content clildFrame">
<div class="layui-tab-item layui-show">
<iframe th:src="@{/admin/home}"></iframe>
</div>
</div>