SpringAOP构建一个安全验证的切面

一. 前言

本次主要采用springboot以及MVC框架实现校友信息收集和展示界面,运用springAOP构建安全验证的切面

二. 开发环境

Windows10
jdk11
springboot
mysql 5.7

三. 具体过程

1.数据库设计

主要有两张表alumni和user


alumni.png

user如下:


user.png

2.mapper层代码自动生成

使用mybatis-generator插件自动生成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:生成一组对象的环境
        id:必选,上下文id,用于在生成错误时提示
        defaultModelType:指定生成对象的样式
            1,conditional:类似hierarchical;
            2,flat:所有内容(主键,blob)等全部生成在一个对象中;
            3,hierarchical:主键生成一个XXKey对象(key class),Blob等单独生成一个对象,其他简单属性在一个对象中(record class)
        targetRuntime:
            1,MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample;
            2,MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample;
        introspectedColumnImpl:类全限定名,用于扩展MBG
       -->

    <context id="collect" targetRuntime="MyBatis3">

        <!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;
            一般保留默认值,遇到数据库关键字(Java关键字),使用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:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <commentGenerator>
            <!-- 这个元素用来去除指定生成的注释中是否包含生成的日期 false:表示保护 -->
            <!-- 如果生成日期,会造成即使修改一个字段,整个实体类所有属性都会发生变化,不利于版本控制,所以设置为true -->
            <property name="suppressDate" value="true" />
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="false" />
        </commentGenerator>

        <!--数据库链接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对应DECIMAL和 NUMERIC数据类型
                false:默认,
                    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的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
            <property name="enableSubPackages" value="false" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- 生成映射文件的包名和位置
            注意,在Mybatis3之后,我们可以使用mapper.xml文件+Mapper接口(或者不用mapper接口),
                或者只使用Mapper接口+Annotation,所以,如果 javaClientGenerator配置中配置了需要生成XML的话,这个元素就必须配置
            targetPackage/targetProject:同javaModelGenerator
        -->
        <sqlMapGenerator targetPackage="com.xmu.mapper"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- 对于mybatis来说,即生成Mapper接口,注意,如果没有配置该元素,那么默认不会生成Mapper接口
            targetPackage/targetProject:同javaModelGenerator
            type:选择怎么生成mapper接口(在MyBatis3/MyBatis3Simple下):
                1,ANNOTATEDMAPPER:会生成使用Mapper接口+Annotation的方式创建(SQL生成在annotation中),不会生成对应的XML;
                2,MIXEDMAPPER:使用混合配置,会生成Mapper接口,并适当添加合适的Annotation,但是XML会生成在XML中;
                3,XMLMAPPER:会生成Mapper接口,接口完全依赖XML;
            注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
        -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.xmu.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- 选择一个table来生成相关文件,可以有一个或多个table,必须要有table元素
        选择的table会生成一下文件:
        1,SQL map文件
        2,生成一个主键类;
        3,除了BLOB和主键的其他字段的类;
        4,包含BLOB的类;
        5,一个用户生成动态查询的条件类(selectByExample, deleteByExample),可选;
        6,Mapper接口(可选)

        tableName(必要):要生成对象的表名;
        注意:大小写敏感问题。正常情况下,MBG会自动的去识别数据库标识符的大小写敏感度,在一般情况下,MBG会
            根据设置的schema,catalog或tablename去查询数据表,按照下面的流程:
            1,如果schema,catalog或tablename中有空格,那么设置的是什么格式,就精确的使用指定的大小写格式去查询;
            2,否则,如果数据库的标识符使用大写的,那么MBG自动把表名变成大写再查找;
            3,否则,如果数据库的标识符使用小写的,那么MBG自动把表名变成小写再查找;
            4,否则,使用指定的大小写格式查询;
        另外的,如果在创建表的时候,使用的""把数据库对象规定大小写,就算数据库标识符是使用的大写,在这种情况下也会使用给定的大小写来创建表名;
        这个时候,请设置delimitIdentifiers="true"即可保留大小写格式;

        可选:
        1,schema:数据库的schema;
        2,catalog:数据库的catalog;
        3,alias:为数据表设置的别名,如果设置了alias,那么生成的所有的SELECT SQL语句中,列名会变成:alias_actualColumnName
        4,domainObjectName:生成的domain类的名字,如果不设置,直接使用表名作为domain类的名字;可以设置为somepck.domainName,那么会自动把domainName类再放到somepck包里面;
        5,enableInsert(默认true):指定是否生成insert语句;
        6,enableSelectByPrimaryKey(默认true):指定是否生成按照主键查询对象的语句(就是getById或get);
        7,enableSelectByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询语句;
        8,enableUpdateByPrimaryKey(默认true):指定是否生成按照主键修改对象的语句(即update);
        9,enableDeleteByPrimaryKey(默认true):指定是否生成按照主键删除对象的语句(即delete);
        10,enableDeleteByExample(默认true):MyBatis3Simple为false,指定是否生成动态删除语句;
        11,enableCountByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询总条数语句(用于分页的总条数查询);
        12,enableUpdateByExample(默认true):MyBatis3Simple为false,指定是否生成动态修改语句(只修改对象中不为空的属性);
        13,modelType:参考context元素的defaultModelType,相当于覆盖;
        14,delimitIdentifiers:参考tableName的解释,注意,默认的delimitIdentifiers是双引号,如果类似MYSQL这样的数据库,使用的是`(反引号,那么还需要设置context的beginningDelimiter和endingDelimiter属性)
        15,delimitAllColumns:设置是否所有生成的SQL中的列名都使用标识符引起来。默认为false,delimitIdentifiers参考context的属性

        注意,table里面很多参数都是对javaModelGenerator,context等元素的默认属性的一个复写;
        -->
        <table tableName="alumni" domainObjectName="AlumniPo"
               enableCountByExample="true" enableUpdateByExample="true"
               enableDeleteByExample="false" enableSelectByExample="true"
               selectByExampleQueryId="true">
            <!-- 如果设置为true,生成的model类会直接使用column本身的名字,而不会再使用驼峰命名方法,比如BORN_DATE,生成的属性名字就是BORN_DATE,而不会是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">
            <!-- 如果设置为true,生成的model类会直接使用column本身的名字,而不会再使用驼峰命名方法,比如BORN_DATE,生成的属性名字就是BORN_DATE,而不会是bornDate -->
            <property name="useActualColumnNames" value="false"/>
            <!--mysql 配置-->
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

3.Controller层设计

/**
 * 收集信息的Controller
 */
@Controller /*普通的Controller对象*/
@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;
    }

    /**
     * 查找单个
     */
    @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.定义切点,在conrtroller层拦住

4.1.InfoSearchAspect

查找时检查是否登录

@Component
@Aspect
public class InfoSearchAspect {

    private static Logger logger = LoggerFactory.getLogger(InfoSearchAspect.class.getName());

    //切点就定义了“何处”
    @Pointcut("execution(* com.xmu.controller.CollectController.getInfo())")   //切入点 pointcut
    public void getInfo() {}

    //通知定义了“什么”和“何时”
    @Around("getInfo()")  // 连接点  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

更新时检查是否有权限(去数据库查user表)

@Component
@Aspect
public class InfoUpdateAspect {

    private static Logger logger = LoggerFactory.getLogger(InfoUpdateAspect.class.getName());

    @Autowired
    UserService userService;

    //切点就定义了“何处”
    @Pointcut("execution(* com.xmu.controller.CollectController.editInfoById(..))")   //切入点 pointcut
    public void editInfoById() {}

    //通知定义了“什么”和“何时”
    @Around("editInfoById()")  // 连接点  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("没有权限: " + userId);
            ModelAndView view=new ModelAndView();
            view.setViewName("error");
            view.addObject("errormsg","当前用户没有权限");
            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;

    //切点就定义了“何处”
    @Pointcut("execution(* com.xmu.controller.CollectController.download())")   //切入点 pointcut
    public void download() {}

    //通知定义了“什么”和“何时”
    @Around("download()")  // 连接点  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("没有权限: " + userId);
            ModelAndView view=new ModelAndView();
            view.setViewName("error");
            view.addObject("errormsg","当前用户没有权限");
            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" href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css">
</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;">毕业年份</th>
            <th style="text-align: center;">学院</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>

出错

<%@ 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](https://upload-images.jianshu.io/upload_images/21464706-e250f34e35e662f8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

image.png

image.png

四. 总结与讨论

本次主要困难点在于SSM框架的搭建,需要很多配置,aop的部分相对来说比较简单,前后端交互的部分存在配置上的难度。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容