一. 前言
本次主要采用springboot以及MVC框架實(shí)現(xiàn)校友信息收集和展示界面,運(yùn)用springAOP構(gòu)建安全驗(yàn)證的切面
二. 開發(fā)環(huán)境
Windows10
jdk11
springboot
mysql 5.7
三. 具體過程
1.數(shù)據(jù)庫(kù)設(shè)計(jì)
主要有兩張表alumni和user
alumni.png
user如下:
user.png
2.mapper層代碼自動(dòng)生成
使用mybatis-generator插件自動(dòng)生成mapper層及po
配置信息如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--
context:生成一組對(duì)象的環(huán)境
id:必選,上下文id,用于在生成錯(cuò)誤時(shí)提示
defaultModelType:指定生成對(duì)象的樣式
1,conditional:類似hierarchical;
2,flat:所有內(nèi)容(主鍵,blob)等全部生成在一個(gè)對(duì)象中;
3,hierarchical:主鍵生成一個(gè)XXKey對(duì)象(key class),Blob等單獨(dú)生成一個(gè)對(duì)象,其他簡(jiǎn)單屬性在一個(gè)對(duì)象中(record class)
targetRuntime:
1,MyBatis3:默認(rèn)的值,生成基于MyBatis3.x以上版本的內(nèi)容,包括XXXBySample;
2,MyBatis3Simple:類似MyBatis3,只是不生成XXXBySample;
introspectedColumnImpl:類全限定名,用于擴(kuò)展MBG
-->
<context id="collect" targetRuntime="MyBatis3">
<!-- 自動(dòng)識(shí)別數(shù)據(jù)庫(kù)關(guān)鍵字,默認(rèn)false,如果設(shè)置為true,根據(jù)SqlReservedWords中定義的關(guān)鍵字列表;
一般保留默認(rèn)值,遇到數(shù)據(jù)庫(kù)關(guān)鍵字(Java關(guān)鍵字),使用columnOverride覆蓋
-->
<property name="autoDelimitKeywords" value="false"/>
<!-- 生成的Java文件的編碼 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 格式化java代碼 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代碼 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<!-- beginningDelimiter和endingDelimiter:指明數(shù)據(jù)庫(kù)的用于標(biāo)記數(shù)據(jù)庫(kù)對(duì)象名的符號(hào),比如ORACLE就是雙引號(hào),MYSQL默認(rèn)是`反引號(hào); -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<commentGenerator>
<!-- 這個(gè)元素用來去除指定生成的注釋中是否包含生成的日期 false:表示保護(hù) -->
<!-- 如果生成日期,會(huì)造成即使修改一個(gè)字段,整個(gè)實(shí)體類所有屬性都會(huì)發(fā)生變化,不利于版本控制,所以設(shè)置為true -->
<property name="suppressDate" value="true" />
<!-- 是否去除自動(dòng)生成的注釋 true:是 : false:否 -->
<property name="suppressAllComments" value="false" />
</commentGenerator>
<!--數(shù)據(jù)庫(kù)鏈接URL,用戶名、密碼 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/collect?serverTimezone=GMT%2B8" userId="dbuser" password="123456">
</jdbcConnection>
<javaTypeResolver>
<!--
true:使用BigDecimal對(duì)應(yīng)DECIMAL和 NUMERIC數(shù)據(jù)類型
false:默認(rèn),
scale>0;length>18:使用BigDecimal;
scale=0;length[10,18]:使用Long;
scale=0;length[5,9]:使用Integer;
scale=0;length<5:使用Short;
-->
<property name="forceBigDecimals" value="false" />
<!-- This property is used to specify whether MyBatis Generator should force the use of JSR-310 data types for DATE, TIME,
and TIMESTAMP fields, rather than using java.util.Date -->
<property name="useJSR310Types" value="true"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="com.xmu.model.po"
targetProject="src/main/java">
<!-- 在targetPackage的基礎(chǔ)上,根據(jù)數(shù)據(jù)庫(kù)的schema再生成一層package,最終生成的類放在這個(gè)package下,默認(rèn)為false -->
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成映射文件的包名和位置
注意,在Mybatis3之后,我們可以使用mapper.xml文件+Mapper接口(或者不用mapper接口),
或者只使用Mapper接口+Annotation,所以,如果 javaClientGenerator配置中配置了需要生成XML的話,這個(gè)元素就必須配置
targetPackage/targetProject:同javaModelGenerator
-->
<sqlMapGenerator targetPackage="com.xmu.mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 對(duì)于mybatis來說,即生成Mapper接口,注意,如果沒有配置該元素,那么默認(rèn)不會(huì)生成Mapper接口
targetPackage/targetProject:同javaModelGenerator
type:選擇怎么生成mapper接口(在MyBatis3/MyBatis3Simple下):
1,ANNOTATEDMAPPER:會(huì)生成使用Mapper接口+Annotation的方式創(chuàng)建(SQL生成在annotation中),不會(huì)生成對(duì)應(yīng)的XML;
2,MIXEDMAPPER:使用混合配置,會(huì)生成Mapper接口,并適當(dāng)添加合適的Annotation,但是XML會(huì)生成在XML中;
3,XMLMAPPER:會(huì)生成Mapper接口,接口完全依賴XML;
注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
-->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.xmu.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 選擇一個(gè)table來生成相關(guān)文件,可以有一個(gè)或多個(gè)table,必須要有table元素
選擇的table會(huì)生成一下文件:
1,SQL map文件
2,生成一個(gè)主鍵類;
3,除了BLOB和主鍵的其他字段的類;
4,包含BLOB的類;
5,一個(gè)用戶生成動(dòng)態(tài)查詢的條件類(selectByExample, deleteByExample),可選;
6,Mapper接口(可選)
tableName(必要):要生成對(duì)象的表名;
注意:大小寫敏感問題。正常情況下,MBG會(huì)自動(dòng)的去識(shí)別數(shù)據(jù)庫(kù)標(biāo)識(shí)符的大小寫敏感度,在一般情況下,MBG會(huì)
根據(jù)設(shè)置的schema,catalog或tablename去查詢數(shù)據(jù)表,按照下面的流程:
1,如果schema,catalog或tablename中有空格,那么設(shè)置的是什么格式,就精確的使用指定的大小寫格式去查詢;
2,否則,如果數(shù)據(jù)庫(kù)的標(biāo)識(shí)符使用大寫的,那么MBG自動(dòng)把表名變成大寫再查找;
3,否則,如果數(shù)據(jù)庫(kù)的標(biāo)識(shí)符使用小寫的,那么MBG自動(dòng)把表名變成小寫再查找;
4,否則,使用指定的大小寫格式查詢;
另外的,如果在創(chuàng)建表的時(shí)候,使用的""把數(shù)據(jù)庫(kù)對(duì)象規(guī)定大小寫,就算數(shù)據(jù)庫(kù)標(biāo)識(shí)符是使用的大寫,在這種情況下也會(huì)使用給定的大小寫來創(chuàng)建表名;
這個(gè)時(shí)候,請(qǐng)?jiān)O(shè)置delimitIdentifiers="true"即可保留大小寫格式;
可選:
1,schema:數(shù)據(jù)庫(kù)的schema;
2,catalog:數(shù)據(jù)庫(kù)的catalog;
3,alias:為數(shù)據(jù)表設(shè)置的別名,如果設(shè)置了alias,那么生成的所有的SELECT SQL語(yǔ)句中,列名會(huì)變成:alias_actualColumnName
4,domainObjectName:生成的domain類的名字,如果不設(shè)置,直接使用表名作為domain類的名字;可以設(shè)置為somepck.domainName,那么會(huì)自動(dòng)把domainName類再放到somepck包里面;
5,enableInsert(默認(rèn)true):指定是否生成insert語(yǔ)句;
6,enableSelectByPrimaryKey(默認(rèn)true):指定是否生成按照主鍵查詢對(duì)象的語(yǔ)句(就是getById或get);
7,enableSelectByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動(dòng)態(tài)查詢語(yǔ)句;
8,enableUpdateByPrimaryKey(默認(rèn)true):指定是否生成按照主鍵修改對(duì)象的語(yǔ)句(即update);
9,enableDeleteByPrimaryKey(默認(rèn)true):指定是否生成按照主鍵刪除對(duì)象的語(yǔ)句(即delete);
10,enableDeleteByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動(dòng)態(tài)刪除語(yǔ)句;
11,enableCountByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動(dòng)態(tài)查詢總條數(shù)語(yǔ)句(用于分頁(yè)的總條數(shù)查詢);
12,enableUpdateByExample(默認(rèn)true):MyBatis3Simple為false,指定是否生成動(dòng)態(tài)修改語(yǔ)句(只修改對(duì)象中不為空的屬性);
13,modelType:參考context元素的defaultModelType,相當(dāng)于覆蓋;
14,delimitIdentifiers:參考tableName的解釋,注意,默認(rèn)的delimitIdentifiers是雙引號(hào),如果類似MYSQL這樣的數(shù)據(jù)庫(kù),使用的是`(反引號(hào),那么還需要設(shè)置context的beginningDelimiter和endingDelimiter屬性)
15,delimitAllColumns:設(shè)置是否所有生成的SQL中的列名都使用標(biāo)識(shí)符引起來。默認(rèn)為false,delimitIdentifiers參考context的屬性
注意,table里面很多參數(shù)都是對(duì)javaModelGenerator,context等元素的默認(rèn)屬性的一個(gè)復(fù)寫;
-->
<table tableName="alumni" domainObjectName="AlumniPo"
enableCountByExample="true" enableUpdateByExample="true"
enableDeleteByExample="false" enableSelectByExample="true"
selectByExampleQueryId="true">
<!-- 如果設(shè)置為true,生成的model類會(huì)直接使用column本身的名字,而不會(huì)再使用駝峰命名方法,比如BORN_DATE,生成的屬性名字就是BORN_DATE,而不會(huì)是bornDate -->
<property name="useActualColumnNames" value="false"/>
<!--mysql 配置-->
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
</table>
<table tableName="user" domainObjectName="UserPo"
enableCountByExample="true" enableUpdateByExample="true"
enableDeleteByExample="false" enableSelectByExample="true"
selectByExampleQueryId="true">
<!-- 如果設(shè)置為true,生成的model類會(huì)直接使用column本身的名字,而不會(huì)再使用駝峰命名方法,比如BORN_DATE,生成的屬性名字就是BORN_DATE,而不會(huì)是bornDate -->
<property name="useActualColumnNames" value="false"/>
<!--mysql 配置-->
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
</table>
</context>
</generatorConfiguration>
3.Controller層設(shè)計(jì)
/**
* 收集信息的Controller
*/
@Controller /*普通的Controller對(duì)象*/
@RequestMapping(value = "/collection")
public class CollectController {
private static final Logger logger = LoggerFactory.getLogger(CollectController.class);
@Autowired
private CollectService collectService;
@Autowired
private UserService userService;
// @Autowired
// private HttpServletResponse httpServletResponse;
/**
* 收集校友信息
*/
@PostMapping(value = "collections")
public ModelAndView insertInfo(AlumniVo alumniVo)
{
int res=collectService.insert(alumniVo);
// httpServletResponse.
ModelAndView view = new ModelAndView();
if(res != 0){
//添加成功
view.setViewName("success");
}else{
//添加失敗
view.setViewName("error");
}
return view;
}
/**
* 查找單個(gè)
*/
@GetMapping(value = "collectionsById")
public ModelAndView findInfoById(long infoId)
{
AlumniPo alumniPo=collectService.getInfoById(infoId);
ModelAndView view = new ModelAndView();
if(alumniPo != null){
//添加成功
view.addObject("AlumniVo",alumniPo);
view.setViewName("edit");
}else{
//添加失敗
view.setViewName("error");
}
return view;
}
/**
* 修改校友信息
*/
@PostMapping(value = "editInfo")
public ModelAndView editInfoById(AlumniVo alumniVo)
{
int res=collectService.editInfoById(alumniVo);
ModelAndView view = new ModelAndView();
if(res != 0){
//添加成功
view.setViewName("success");
}else{
//添加失敗
view.setViewName("error");
}
return view;
}
/**
* 展示校友信息
*/
@GetMapping(value = "collections")
public ModelAndView getInfo()
{
List<AlumniVo> alumniVoList;
alumniVoList=collectService.getAllInfo();
ModelAndView view = new ModelAndView();
view.addObject("alumniVoList",alumniVoList);
view.setViewName("search");
return view;
}
/**
* 下載校友信息
*/
@GetMapping(value = "download")
public ModelAndView download()
{
// List<AlumniVo> alumniVoList;
// alumniVoList=collectService.getAllInfo();
ModelAndView view = new ModelAndView();
// view.addObject("alumniVoList",alumniVoList);
view.setViewName("success");
return view;
}
@PostMapping(value = "login")
public ModelAndView login(HttpServletRequest request, String username, String password)
{
List<UserPo> userPoList;
userPoList = userService.login(username, password);
if(userPoList==null)
return new ModelAndView("error");
for (UserPo userPo:userPoList)
// 保存id到session
request.getSession().setAttribute("userId", userPo.getId());
ModelAndView view = new ModelAndView();
view.setViewName("index");
return view;
}
4.定義切點(diǎn),在conrtroller層攔住
4.1.InfoSearchAspect
查找時(shí)檢查是否登錄
@Component
@Aspect
public class InfoSearchAspect {
private static Logger logger = LoggerFactory.getLogger(InfoSearchAspect.class.getName());
//切點(diǎn)就定義了“何處”
@Pointcut("execution(* com.xmu.controller.CollectController.getInfo())") //切入點(diǎn) pointcut
public void getInfo() {}
//通知定義了“什么”和“何時(shí)”
@Around("getInfo()") // 連接點(diǎn) Joinpoint
public Object checkLogin(ProceedingJoinPoint joinPoint) throws Throwable { //通知 advice
System.out.println("Silencing cell phones...");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Long userId = (Long) request.getSession().getAttribute("userId");
if (userId == null) {
logger.info("未登錄");
return new ModelAndView("login");
}
logger.info("userId: " + userId);
return joinPoint.proceed();
}
}
4.2.InfoUpdateAspect
更新時(shí)檢查是否有權(quán)限(去數(shù)據(jù)庫(kù)查user表)
@Component
@Aspect
public class InfoUpdateAspect {
private static Logger logger = LoggerFactory.getLogger(InfoUpdateAspect.class.getName());
@Autowired
UserService userService;
//切點(diǎn)就定義了“何處”
@Pointcut("execution(* com.xmu.controller.CollectController.editInfoById(..))") //切入點(diǎn) pointcut
public void editInfoById() {}
//通知定義了“什么”和“何時(shí)”
@Around("editInfoById()") // 連接點(diǎn) Joinpoint
public Object checkUpdate(ProceedingJoinPoint joinPoint) throws Throwable { //通知 advice
System.out.println("Silencing cell phones...");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Long userId = (Long) request.getSession().getAttribute("userId");
if (userId == null) {
logger.info("未登錄");
return new ModelAndView("login");
}
UserPo userPo=userService.selectById(userId);
if (userPo.getUpdateproxy()==0)
{
logger.info("沒有權(quán)限: " + userId);
ModelAndView view=new ModelAndView();
view.setViewName("error");
view.addObject("errormsg","當(dāng)前用戶沒有權(quán)限");
return view;
}
return joinPoint.proceed();
}
}
4.3.InfoDownloadAspect
@Component
@Aspect
public class InfoDownloadAspect {
private static Logger logger = LoggerFactory.getLogger(InfoDownloadAspect.class.getName());
@Autowired
UserService userService;
//切點(diǎn)就定義了“何處”
@Pointcut("execution(* com.xmu.controller.CollectController.download())") //切入點(diǎn) pointcut
public void download() {}
//通知定義了“什么”和“何時(shí)”
@Around("download()") // 連接點(diǎn) Joinpoint
public Object checkDownload(ProceedingJoinPoint joinPoint) throws Throwable { //通知 advice
System.out.println("Silencing cell phones...");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Long userId = (Long) request.getSession().getAttribute("userId");
if (userId == null) {
logger.info("未登錄");
return new ModelAndView("login");
}
UserPo userPo=userService.selectById(userId);
if (userPo.getAggregateproxy()==0)
{
logger.info("沒有權(quán)限: " + userId);
ModelAndView view=new ModelAndView();
view.setViewName("error");
view.addObject("errormsg","當(dāng)前用戶沒有權(quán)限");
return view;
}
return joinPoint.proceed();
}
}
5.前端界面jsp
login
<%--
Created by IntelliJ IDEA.
User: dell
Date: 2021/5/12
Time: 0:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登錄</title>
<link rel="stylesheet" href="css/login.css"/>
<link rel="stylesheet" >
</head>
<body>
<div id="login-box">
<h1>Login</h1>
<div class="form" >
<form action="collection/login.action" method="post">
<div class="item">
<i class="fa fa-github-alt" style="font-size:24px"></i>
<input type="text" placeholder="username" name="username">
</div>
<div class="item">
<i class="fa fa-search" style="font-size:24px"></i>
<input type="text" placeholder="password" name="password">
</div>
<input type="submit" value="登錄"/>
</form>
</div>
<button type="submit" value="登錄"/>
</div>
</body>
</html>
search
<%--
Created by IntelliJ IDEA.
User: dell
Date: 2021/5/12
Time: 8:05
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<div class="well">
<table class="table">
<thead>
<tr>
<th style="text-align: center;">真名</th>
<th style="text-align: center;">畢業(yè)年份</th>
<th style="text-align: center;">學(xué)院</th>
<th style="text-align: center;">操作</th>
<th style="width: 30px;"></th>
</tr>
</thead>
<tbody>
<c:forEach var="AlumniVo" items="${alumniVoList}" >
<tr>
<td style="text-align: center;"><c:out value="${AlumniVo.trueName}" /></td>
<td style="text-align: center;"><c:out value="${AlumniVo.graduateYear}" /></td>
<td style="text-align: center;"><c:out value="${AlumniVo.department}" /></td>
<a href="collectionsById.action?infoId=${AlumniVo.id}">修改</a>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div>
<a href="download.action">下載</a>
</div>
</body>
</html>
出錯(cuò)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%-- <meta charset="UTF-8">--%>
<%-- <style>--%>
<%-- body--%>
<%-- {--%>
<%-- background-image: url('img/error.png');--%>
<%-- background-repeat:no-repeat;--%>
<%-- background-attachment: fixed;--%>
<%-- background-position: 180px 50px;--%>
<%-- }--%>
<%-- </style>--%>
</head>
<body>
<p>失敗!</p>
<p>${errormsg}</p>
</body>
</html>
6.最終界面展示
image.png
image.png

image.png
image.png
四. 總結(jié)與討論
本次主要困難點(diǎn)在于SSM框架的搭建,需要很多配置,aop的部分相對(duì)來說比較簡(jiǎn)單,前后端交互的部分存在配置上的難度。