识别操作系统的人的身份,控制他的行为。
/**
* 对明文字符串进行MD5加密
* @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[] bytes = source.getBytes();
// 5.执行加密
byte[] digest = messageDigest.digest(bytes);
// 6.创建BigInteger对象
int signum = 1;
BigInteger bigInteger = new BigInteger(signum, digest);
// 7.按照16进制将bigInteger的值
int radix = 16;
String encoded = bigInteger.toString(radix).toUpperCase();
return encoded;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
package com.atguigu.crowd.exception;
/**
* 登录失败后抛出的异常
*/
public class LoginFailedException extends RuntimeException{
private static final long serialVersionUID= 1L;
public LoginFailedException() {
super();
}
public LoginFailedException(String message) {
super(message);
}
public LoginFailedException(String message, Throwable cause) {
super(message, cause);
}
public LoginFailedException(Throwable cause) {
super(cause);
}
protected LoginFailedException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.atguigu.crowd.mvc.config;
import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
//@ControllerAdvice表示当前类是一个基于注解的异常处理器类
@ControllerAdvice
public class CrowdExceptionResolver {
//@ExceptionHandler将一个具体的异常类型和一个方法关联起来
@ExceptionHandler(value = Exception.class)
public ModelAndView resolveException(
//实际捕获到的异常类型
Exception exception,
//当前请求对象
HttpServletRequest request,
//当前响应对象
HttpServletResponse response) throws IOException {
String viewName = "system-error";
return commonResolve(viewName,exception,request,response);
}
//@ExceptionHandler将一个具体的异常类型和一个方法关联起来
@ExceptionHandler(value = LoginFailedException.class)
public ModelAndView resolveLoginFailedException(
//实际捕获到的异常类型
LoginFailedException exception,
//当前请求对象
HttpServletRequest request,
//当前响应对象
HttpServletResponse response) throws IOException {
String viewName = "admin-login";
return commonResolve(viewName,exception,request,response);
}
/**
* 核心异常处理方法
* @param exception SpringMVC 捕获到的异常对象
* @param request 为了判断当前请求是“普通请求”还是“Ajax 请求” 需要传入原生 request 对象
* @param response 为了能够将 JSON 字符串作为当前请求的响应数
据返回给浏览器
* @param viewName 指定要前往的视图名称
* @return ModelAndView
* @throws IOException
*/
private ModelAndView commonResolve(
//异常页面
String viewName,
//实际捕获到的异常类型
Exception exception,
//当前请求对象
HttpServletRequest request,
//当前响应对象
HttpServletResponse response) throws IOException {
{
//1.判断当前请求类型
boolean b = CrowdUtil.judgeRequestType(request);
//2.如果是Ajax请求
if(b){
//3.创建ResultEntity对象
ResultEntity<Object> resultEntity = ResultEntity.failed(exception.getMessage());
//4.创建Gson对象
Gson gson = new Gson();
//5.将ResultEntity对象转换为JSON字符串
String json = gson.toJson(resultEntity);
//6.将JSON字符串作为响应体返回给浏览器
response.getWriter().write(json);
//7.由于上面已经通过原生的response对象返回了响应,所以不提供ModelAndView对象
return null;
}
//8.如果不是Ajax请求则创建ModelAndView对象
ModelAndView modelAndView = new ModelAndView();
//9.将Exception对象存入模型
modelAndView.addObject(CrowdConstant.ATTR_NAME_EXCEPTION,exception);
//10.设置对应的视图名称
modelAndView.setViewName(viewName);
//11.返回ModelAndView对象
return modelAndView;
}
}
}
<p>${requestScope.exception.message}</p>
<%--
Created by IntelliJ IDEA.
User: wangchenze.kuangwang
Date: 2022/11/3
Time: 20:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>主页</h1>
<p>${sessionScope.loginAdmin.userName}</p>
</body>
</html>
package com.atguigu.crowd.mvc.handler;
import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.service.api.AdminService;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class AmdinHandler {
@Autowired
private AdminService adminService;
@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对象存入Session域
session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN,admin);
return "admin-main";
}
}
@Override
public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
// 1.根据登录账号查询Admin对象
// ①创建AdminExample对象
AdminExample adminExample = new AdminExample();
// ②创建Criteria对象
Criteria criteria = adminExample.createCriteria();
// ③在Criteria对象中封装查询条件
criteria.andLoginAcctEqualTo(loginAcct);
// ④调用AdminMapper的方法执行查询
List<Admin> admins = adminMapper.selectByExample(adminExample);
// 2.判断Admin对象是否为null
if(admins == null || admins.size() == 0){
throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
}
if(admins.size() > 1){
throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
}
// 3.如果Admin对象为null则抛出异常
Admin admin = admins.get(0);
if(admin == null){
throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
}
// 4.如果Admin对象不为null则将数据库密码从Admin对象中取出
String userPswdDB = admin.getUserPswd();
// 5.将表单提交的明文密码进行加密
String userPswdForm = CrowdUtil.md5(userPswd);
// 6.对密码进行比较
if(!Objects.equals(userPswdDB,userPswdForm)){
// 7.如果比较结果是不一致则抛出异常
throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
}
// 8.如果一致则返回Admin对象
return admin;
}
为了避免跳转到后台主页面再刷新浏览器导致重复提交登录表单,重定向到目标页面。
所以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对象存入Session域
session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN,admin);
return "redirect:/admin/to/main/page.html";
}
修改页面
编写handler
@RequestMapping("/admin/do/logout.html")
public String doLogout(HttpSession session){
//强制Session失效
session.invalidate();
return "redirect:/admin/to/login/page.html";
}
<%--
Created by IntelliJ IDEA.
User: wangchenze.kuangwang
Date: 2022/11/4
Time: 15:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<base href="http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/"/>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="css/main.css">
<style>
.tree li {
list-style-type: none;
cursor:pointer;
}
.tree-closed {
height : 40px;
}
.tree-expanded {
height : auto;
}
</style>
<script type="text/javascript" src="jquery/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="script/docs.min.js"></script>
<script type="text/javascript" src="layer/layer.js"></script>
<script type="text/javascript">
$(function () {
$(".list-group-item").click(function(){
if ( $(this).find("ul") ) {
$(this).toggleClass("tree-closed");
if ( $(this).hasClass("tree-closed") ) {
$("ul", this).hide("fast");
} else {
$("ul", this).show("fast");
}
}
});
});
</script>
</head>
<%--
Created by IntelliJ IDEA.
User: wangchenze.kuangwang
Date: 2022/11/4
Time: 15:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<div><a class="navbar-brand" style="font-size:32px;" href="#">众筹平台 - 控制面板</a></div>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li style="padding-top:8px;">
<div class="btn-group">
<button type="button" class="btn btn-default btn-success dropdown-toggle" data-toggle="dropdown">
<i class="glyphicon glyphicon-user"></i> ${sessionScope.loginAdmin.userName} <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#"><i class="glyphicon glyphicon-cog"></i> 个人设置</a></li>
<li><a href="#"><i class="glyphicon glyphicon-comment"></i> 消息</a></li>
<li class="divider"></li>
<li><a href="admin/do/logout.html"><i class="glyphicon glyphicon-off"></i> 退出系统</a></li>
</ul>
</div>
</li>
<li style="margin-left:10px;padding-top:8px;">
<button type="button" class="btn btn-default btn-danger">
<span class="glyphicon glyphicon-question-sign"></span> 帮助
</button>
</li>
</ul>
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="查询">
</form>
</div>
</div>
</nav>
<%--
Created by IntelliJ IDEA.
User: wangchenze.kuangwang
Date: 2022/11/3
Time: 20:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<%@include file="/WEB-INF/include-head.jsp"%>
<body>
<%@ include file="/WEB-INF/include-nav.jsp" %>
<div class="container-fluid">
<div class="row">
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1 class="page-header">控制面板</h1>
<%@ include file="/WEB-INF/include-sidebar.jsp"%>
<div class="row placeholders">
<div class="col-xs-6 col-sm-3 placeholder">
<img data-src="holder.js/200x200/auto/sky" class="img-responsive" alt="Generic placeholder thumbnail">
<h4>Label</h4>
<span class="text-muted">Something else</span>
</div>
<div class="col-xs-6 col-sm-3 placeholder">
<img data-src="holder.js/200x200/auto/vine" class="img-responsive" alt="Generic placeholder thumbnail">
<h4>Label</h4>
<span class="text-muted">Something else</span>
</div>
<div class="col-xs-6 col-sm-3 placeholder">
<img data-src="holder.js/200x200/auto/sky" class="img-responsive" alt="Generic placeholder thumbnail">
<h4>Label</h4>
<span class="text-muted">Something else</span>
</div>
<div class="col-xs-6 col-sm-3 placeholder">
<img data-src="holder.js/200x200/auto/vine" class="img-responsive" alt="Generic placeholder thumbnail">
<h4>Label</h4>
<span class="text-muted">Something else</span>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: wangchenze.kuangwang
Date: 2022/11/3
Time: 20:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<%@include file="/WEB-INF/include-head.jsp"%>
<body>
<%@ include file="/WEB-INF/include-nav.jsp" %>
<div class="container-fluid">
<div class="row">
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
</div>
</div>
</div>
</body>
</html>
将部分资源保护起来,让没有登录的请求不能访问。
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/admin/to/login/page.html"/>
<mvc:exclude-mapping path="/admin/do/login.html"/>
<mvc:exclude-mapping path="/admin/do/logout.html"/>
<bean class="com.atguigu.crowd.mvc.interceptor.LoginInterceptor">bean>
mvc:interceptor>
mvc:interceptors>