day02【后台】管理员登录

day02【后台】管理员登录

1、创建常量类

  • 创建常量类,用于管理整个系统中所用到的常量

day02【后台】管理员登录_第1张图片

public class CrowdConstant {
	
	public static final String MESSAGE_LOGIN_FAILED = "抱歉!账号密码错误!请重新输入!";
	public static final String MESSAGE_LOGIN_ACCT_ALREADY_IN_USE = "抱歉!这个账号已经被使用了!";
	public static final String MESSAGE_ACCESS_FORBIDEN = "请登录以后再访问!";
	public static final String MESSAGE_STRING_INVALIDATE = "字符串不合法!请不要传入空字符串!";
	public static final String MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE = "系统错误:登录账号不唯一!";
	
	public static final String ATTR_NAME_EXCEPTION = "exception";
	public static final String ATTR_NAME_LOGIN_ADMIN = "loginAdmin";
	public static final String ATTR_NAME_PAGE_INFO = "pageInfo";

}

2、管理员登录页面

2.1、创建管理员登录页面

2.1.1、引入前端静态资源

day02【后台】管理员登录_第2张图片

2.1.2、添加登录页面
  • WEB-INF文件夹下添加admin-login.jsp页面,注意如下几点:
    • 修改字符集
    • 添加base标签
    • 修改form表单的一些属性值
  • 页面代码如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html lang="zh-CN">
<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="keys" 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/login.css">
<script src="jquery/jquery-2.1.1.min.js">script>
<script src="bootstrap/js/bootstrap.min.js">script>
<style>
style>
<title>尚筹网title>
head>
<body>
	<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
		<div class="container">
			<div class="navbar-header">
				<div>
					<a class="navbar-brand" href="index.html" style="font-size: 32px;">尚筹网-创意产品众筹平台a>
				div>
			div>
		div>
	nav>

	<div class="container">

		<form action="admin/do/login.html" method="post" class="form-signin"
			role="form">
			<h2 class="form-signin-heading">
				<i class="glyphicon glyphicon-log-in">i> 管理员登录
			h2>
			<p>${requestScope.exception.message }p>
			<div class="form-group has-success has-feedback">
				<input type="text" name="loginAcct" class="form-control"
					id="inputSuccess4" placeholder="请输入登录账号" autofocus> <span
					class="glyphicon glyphicon-user form-control-feedback">span>
			div>
			<div class="form-group has-success has-feedback">
				<input type="text" name="userPswd" class="form-control"
					id="inputSuccess4" placeholder="请输入登录密码" style="margin-top: 10px;">
				<span class="glyphicon glyphicon-lock form-control-feedback">span>
			div>
			<button type="submit" class="btn btn-lg btn-success btn-block">登录button>
		form>
	div>
body>
html>

2.2、跳转至管理员登录页面

  • SpringMVC配置文件中配置view-controller,用于管理员登录页面跳转

day02【后台】管理员登录_第3张图片



<mvc:view-controller path="/admin/to/login/page.html" view-name="admin-login" />
  • 测试:能正常访问

day02【后台】管理员登录_第4张图片

3、layer弹层组件

3.1、引入layer组件

  • 引入layer组件的资源文件,将其放在webapp目录下

day02【后台】管理员登录_第5张图片

  • 添加对layer.js的引用,注意:放在jQuery的引用之后

day02【后台】管理员登录_第6张图片



3.2、测试

  • 添加一个button按钮
<button id="btn5">点我弹框button>
  • 按钮的单击时间处理过程
$("#btn5").click(function() {
	layer.msg("我出来了~");
});
  • 弹层效果

day02【后台】管理员登录_第7张图片

4、好看的错误页面

  • 修改WEB-INFsystem-error.jsp页面中的代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html lang="zh-CN">
<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="keys" 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/login.css">
<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">
	$(function() {
		$("button").click(function() {
			// 相当于浏览器的后退按钮
			window.history.back();
		});
	});
script>
<style>
style>
head>
<body>
	<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
		<div class="container">
			<div class="navbar-header">
				<div>
					<a class="navbar-brand" href="index.html" style="font-size: 32px;">尚筹网-创意产品众筹平台a>
				div>
			div>
		div>
	nav>

	<div class="container">

		<h2 class="form-signin-heading" style="text-align: center;">
			<i class="glyphicon glyphicon-log-in">i> 尚筹网系统消息
		h2>
		
		<h3 style="text-align: center;">${requestScope.exception.message }h3>
		<button style="width: 150px; margin: 50px auto 0px auto;"
			class="btn btn-lg btn-success btn-block">点我返回上一步button>
	div>
body>
html>
  • 页面效果

day02【后台】管理员登录_第8张图片

5、管理员登录

5.1、管理员登录思路

day02【后台】管理员登录_第9张图片

5.2、MD5加密

  • util工程下的CrowdUtil工具类中添加MD5加密方法

day02【后台】管理员登录_第10张图片

/**
 * 尚筹网项目通用工具方法类
 * 
 * @author 吴彦祖
 *
 */
public class CrowdUtil {

	/**
	 * 对明文字符串进行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[] input = source.getBytes();
			// 5.执行加密
			byte[] output = messageDigest.digest(input);
			// 6.创建BigInteger对象
			int signum = 1;
			BigInteger bigInteger = new BigInteger(signum, output);
			// 7.按照16进制将bigInteger的值转换为字符串
			int radix = 16;
			String encoded = bigInteger.toString(radix).toUpperCase();
			return encoded;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 判断当前请求是否为Ajax请求
	 * 
	 * @param request 请求对象
	 * @return true:当前请求是Ajax请求 false:当前请求不是Ajax请求
	 */
	public static boolean judgeRequestType(HttpServletRequest request) {

		// 1.获取请求消息头
		String acceptHeader = request.getHeader("Accept");
		String xRequestHeader = request.getHeader("X-Requested-With");

		// 2.判断
		return (acceptHeader != null && acceptHeader.contains("application/json"))
				|| (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest"));
	}

}
  • 测试:在webui工程下添加StringTest类,进行单元测试

day02【后台】管理员登录_第11张图片

public class StringTest {
	
	@Test
	public void testMd5() {
		String source = "123123";
		String encoded = CrowdUtil.md5(source);
		System.out.println(encoded);
	}

}

5.3、创建自定义异常

  • util工程下创建LoginFailedException类,用于处理用户登录异常信息

day02【后台】管理员登录_第12张图片

/**
 * 登录失败后抛出的异常
 * 
 * @author Lenovo
 *
 */
public class LoginFailedException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public LoginFailedException() {
		super();
	}

	public LoginFailedException(String message, Throwable cause, boolean enableSuppression,
			boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public LoginFailedException(String message, Throwable cause) {
		super(message, cause);
	}

	public LoginFailedException(String message) {
		super(message);
	}

	public LoginFailedException(Throwable cause) {
		super(cause);
	}

}
  • component工程下的CrowdExceptionResolver异常处理类中,增加登录失败异常的处理

day02【后台】管理员登录_第13张图片

@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);
}
  • 重新定位至登录页面时,需显示异常信息

day02【后台】管理员登录_第14张图片

<p>${requestScope.exception.message }p>

5.4、AdminHandler

  • component工程下创建AdminHandler类,用于处理管理员的相关请求

day02【后台】管理员登录_第15张图片

@Controller
public class AdminHandler {

	@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";
	}

}
  • WEB-INF下创建临时的登陆成功跳转页面:admin-main.jsp

day02【后台】管理员登录_第16张图片

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
	<h1>临时主页h1>
	${sessionScope.loginAdmin.userName }
body>
html>

5.5、AdminService

  • component工程中创建与Service相关的接口和实现类

day02【后台】管理员登录_第17张图片

  • component工程中的AdminServiceImpl类中,添加getAdminByLoginAcct方法,用于处理用户的登录请求
@Service
public class AdminServiceImpl implements AdminService {
	@Autowired
	private AdminMapper adminMapper;

	@Override
	public void saveAdmin(Admin admin) {
		adminMapper.insert(admin);

		// throw new RuntimeException();
	}

	@Override
	public List<Admin> getAll() {
		return adminMapper.selectByExample(new AdminExample());
	}

	@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> list = adminMapper.selectByExample(adminExample);

		// 2.判断Admin对象是否为null
		if (list == null || list.size() == 0) {
			throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
		}
		if (list.size() > 1) {
			throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
		}

		// 3.如果Admin对象为null则抛出异常
		Admin admin = list.get(0);
		if (admin == null) {
			throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
		}

		// 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;
	}

}

5.6、测试登录

  • 输入正确的用户名和密码后,跳转到临时主页~

day02【后台】管理员登录_第18张图片

5.7、管理员登录的改进

5.7.1、重写登陆成功页面
  • 重写WEB-INF下的登陆成功跳转页面:admin-main.jsp

    • 添加base标签
    {pageContext.request.serverName }:${pageContext.request.serverPort }${pageContext.request.contextPath }/" />
    
    • session域中取出用户姓名,并显示
    <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>
    
  • 页面代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html lang="zh-CN">
<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">
	$(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>

<body>

	<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="index.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>
	<div class="container-fluid">
		<div class="row">
			<div class="col-sm-3 col-md-2 sidebar">
				<div class="tree">
					<ul style="padding-left: 0px;" class="list-group">
						<li class="list-group-item tree-closed"><a href="main.html"><i
								class="glyphicon glyphicon-dashboard">i> 控制面板a>li>
						<li class="list-group-item tree-closed"><span><i
								class="glyphicon glyphicon glyphicon-tasks">i> 权限管理 <span
								class="badge" style="float: right">3span>span>
							<ul style="margin-top: 10px; display: none;">
								<li style="height: 30px;"><a href="user.html"><i
										class="glyphicon glyphicon-user">i> 用户维护a>li>
								<li style="height: 30px;"><a href="role.html"><i
										class="glyphicon glyphicon-king">i> 角色维护a>li>
								<li style="height: 30px;"><a href="permission.html"><i
										class="glyphicon glyphicon-lock">i> 菜单维护a>li>
							ul>li>
						<li class="list-group-item tree-closed"><span><i
								class="glyphicon glyphicon-ok">i> 业务审核 <span class="badge"
								style="float: right">3span>span>
							<ul style="margin-top: 10px; display: none;">
								<li style="height: 30px;"><a href="auth_cert.html"><i
										class="glyphicon glyphicon-check">i> 实名认证审核a>li>
								<li style="height: 30px;"><a href="auth_adv.html"><i
										class="glyphicon glyphicon-check">i> 广告审核a>li>
								<li style="height: 30px;"><a href="auth_project.html"><i
										class="glyphicon glyphicon-check">i> 项目审核a>li>
							ul>li>
						<li class="list-group-item tree-closed"><span><i
								class="glyphicon glyphicon-th-large">i> 业务管理 <span
								class="badge" style="float: right">7span>span>
							<ul style="margin-top: 10px; display: none;">
								<li style="height: 30px;"><a href="cert.html"><i
										class="glyphicon glyphicon-picture">i> 资质维护a>li>
								<li style="height: 30px;"><a href="type.html"><i
										class="glyphicon glyphicon-equalizer">i> 分类管理a>li>
								<li style="height: 30px;"><a href="process.html"><i
										class="glyphicon glyphicon-random">i> 流程管理a>li>
								<li style="height: 30px;"><a href="advertisement.html"><i
										class="glyphicon glyphicon-hdd">i> 广告管理a>li>
								<li style="height: 30px;"><a href="message.html"><i
										class="glyphicon glyphicon-comment">i> 消息模板a>li>
								<li style="height: 30px;"><a href="project_type.html"><i
										class="glyphicon glyphicon-list">i> 项目分类a>li>
								<li style="height: 30px;"><a href="tag.html"><i
										class="glyphicon glyphicon-tags">i> 项目标签a>li>
							ul>li>
						<li class="list-group-item tree-closed"><a href="param.html"><i
								class="glyphicon glyphicon-list-alt">i> 参数管理a>li>
					ul>
				div>
			div>
			<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
				<h1 class="page-header">控制面板h1>

				<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>Labelh4>
						<span class="text-muted">Something elsespan>
					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>Labelh4>
						<span class="text-muted">Something elsespan>
					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>Labelh4>
						<span class="text-muted">Something elsespan>
					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>Labelh4>
						<span class="text-muted">Something elsespan>
					div>
				div>
			div>
		div>
	div>
body>
html>
5.7.2、重定向
  • 解决表单重复提交:使用重定向,而不是转发
@Controller
public class AdminHandler {

	@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 "redirect:/admin/to/main/page.html";
	}

}
  • 给目标地址配置view-controller
<mvc:view-controller
		path="/admin/to/main/page.html" view-name="admin-main" />

5.8、退出登录

  • 修改admin-main.jsp页面中退出登录的超链接

day02【后台】管理员登录_第19张图片

<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>
  • AdminHandler中添加如下doLogout方法

day02【后台】管理员登录_第20张图片

@Controller
public class AdminHandler {

	@Autowired
	private AdminService adminService;

	@RequestMapping("/admin/do/logout.html")
	public String doLogout(HttpSession session) {
		// 强制Session失效
		session.invalidate();
		//重定向至页面
		return "redirect:/admin/to/login/page.html";
	}

}
  • 测试通过

day02【后台】管理员登录_第21张图片

6、抽取后台主页面

6.1、抽取head部分

  • WEB-INF下新建include-head.jsp,用于抽取页面公共的head部分

day02【后台】管理员登录_第22张图片

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<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>
<title>尚筹网</title>
</head>

6.2、抽取上方导航栏

  • WEB-INF下新建include-nav.jsp,用于抽取页面公共的上方导航栏

day02【后台】管理员登录_第23张图片

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<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>

6.3、抽取侧边栏

  • WEB-INF下新建include-sidebar.jsp,用于抽取页面公共的侧边栏

day02【后台】管理员登录_第24张图片

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<div class="col-sm-3 col-md-2 sidebar">
	<div class="tree">
		<ul style="padding-left: 0px;" class="list-group">
			<li class="list-group-item tree-closed"><a href="main.html"><i
					class="glyphicon glyphicon-dashboard">i> 控制面板a>li>
			<li class="list-group-item tree-closed"><span><i
					class="glyphicon glyphicon glyphicon-tasks">i> 权限管理 <span
					class="badge" style="float: right">3span>span>
				<ul style="margin-top: 10px; display: none;">
					<li style="height: 30px;"><a href="admin/get/page.html"><i
							class="glyphicon glyphicon-user">i> 用户维护a>li>
					<li style="height: 30px;"><a href="role.html"><i
							class="glyphicon glyphicon-king">i> 角色维护a>li>
					<li style="height: 30px;"><a href="permission.html"><i
							class="glyphicon glyphicon-lock">i> 菜单维护a>li>
				ul>li>
			<li class="list-group-item tree-closed"><span><i
					class="glyphicon glyphicon-ok">i> 业务审核 <span class="badge"
					style="float: right">3span>span>
				<ul style="margin-top: 10px; display: none;">
					<li style="height: 30px;"><a href="auth_cert.html"><i
							class="glyphicon glyphicon-check">i> 实名认证审核a>li>
					<li style="height: 30px;"><a href="auth_adv.html"><i
							class="glyphicon glyphicon-check">i> 广告审核a>li>
					<li style="height: 30px;"><a href="auth_project.html"><i
							class="glyphicon glyphicon-check">i> 项目审核a>li>
				ul>li>
			<li class="list-group-item tree-closed"><span><i
					class="glyphicon glyphicon-th-large">i> 业务管理 <span class="badge"
					style="float: right">7span>span>
				<ul style="margin-top: 10px; display: none;">
					<li style="height: 30px;"><a href="cert.html"><i
							class="glyphicon glyphicon-picture">i> 资质维护a>li>
					<li style="height: 30px;"><a href="type.html"><i
							class="glyphicon glyphicon-equalizer">i> 分类管理a>li>
					<li style="height: 30px;"><a href="process.html"><i
							class="glyphicon glyphicon-random">i> 流程管理a>li>
					<li style="height: 30px;"><a href="advertisement.html"><i
							class="glyphicon glyphicon-hdd">i> 广告管理a>li>
					<li style="height: 30px;"><a href="message.html"><i
							class="glyphicon glyphicon-comment">i> 消息模板a>li>
					<li style="height: 30px;"><a href="project_type.html"><i
							class="glyphicon glyphicon-list">i> 项目分类a>li>
					<li style="height: 30px;"><a href="tag.html"><i
							class="glyphicon glyphicon-tags">i> 项目标签a>li>
				ul>li>
			<li class="list-group-item tree-closed"><a href="param.html"><i
					class="glyphicon glyphicon-list-alt">i> 参数管理a>li>
		ul>
	div>
div>

6.4、后台管理主页面

  • 抽取后,后台管理主页面的代码如下

day02【后台】管理员登录_第25张图片

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<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">
			<%@ include file="/WEB-INF/include-sidebar.jsp" %>
			<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
				<h1 class="page-header">控制面板h1>

				<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>Labelh4>
						<span class="text-muted">Something elsespan>
					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>Labelh4>
						<span class="text-muted">Something elsespan>
					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>Labelh4>
						<span class="text-muted">Something elsespan>
					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>Labelh4>
						<span class="text-muted">Something elsespan>
					div>
				div>
			div>
		div>
	div>
body>
html>

6.5、制作JSP模板

  • JSP模板代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<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">
			<%@ include file="/WEB-INF/include-sidebar.jsp" %>
			<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
				
			div>
		div>
	div>
body>
html>
  • 创建JSP模板

day02【后台】管理员登录_第26张图片

  • 使用模板

day02【后台】管理员登录_第27张图片

7、用户权限验证

7.1、权限验证思路

day02【后台】管理员登录_第28张图片

7.2、创建拦截器

  • util工程下创建AccessForbiddenException异常类:用户权限不足的异常

day02【后台】管理员登录_第29张图片

/**
 * 表示用户没有登录就访问受保护资源时抛出的异常
 * 
 * @author Lenovo
 *
 */
public class AccessForbiddenException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public AccessForbiddenException() {
		super();
	}

	public AccessForbiddenException(String message, Throwable cause, boolean enableSuppression,
			boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public AccessForbiddenException(String message, Throwable cause) {
		super(message, cause);
	}

	public AccessForbiddenException(String message) {
		super(message);
	}

	public AccessForbiddenException(Throwable cause) {
		super(cause);
	}

}
  • component工程下创建LoginInterceptor拦截器,用于拦截用户请求,实现权限验证

day02【后台】管理员登录_第30张图片

public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 1.通过request对象获取Session对象
		HttpSession session = request.getSession();
		
		// 2.尝试从Session域中获取Admin对象
		Admin admin = (Admin) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);

		// 3.判断admin对象是否为空
		if (admin == null) {
			// 4.抛出异常
			throw new AccessForbiddenException(CrowdConstant.MESSAGE_ACCESS_FORBIDEN);
		}

		// 5.如果Admin对象不为null,则返回true放行
		return true;
	}

}

7.3、注册拦截器类

  • SpringMVC的配置文件中注册拦截器,即注册LoginInterceptor bean

day02【后台】管理员登录_第31张图片


<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" />
  mvc:interceptor>
mvc:interceptors>

7.4、基于XML的异常映射

  • SpringMVC配置文件中,添加对AccessForbiddenException异常的映射;当发生此类异常,重定向至登录页面

day02【后台】管理员登录_第32张图片


<bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    
    <property name="exceptionMappings">
        <props>
            
            
            <prop key="java.lang.Exception">system-errorprop>
            <prop key="com.atguigu.crowd.exception.AccessForbiddenException">admin-loginprop>
        props>
    property>
bean>
  • 测试成功~

day02【后台】管理员登录_第33张图片

你可能感兴趣的:(SpringMVC,权限验证,全局异常处理)