SSM使用AOP切面获取用户登录操作日志

系统日志类 SysLog.java:

package com.ys.entity;

import java.sql.Timestamp;

import com.fasterxml.jackson.annotation.JsonFormat;

/**
 * 系统日志
 * @author Administrator
 *
 */
public class SysLog {

    private int id;//id
    private int user_id;//用户id
    private Timestamp createDate;//新建时间
    private String operation;//操作
    private String content;//内容
    private String ipAddress;//ip

    private String name;//用户名
    private String role_name;//角色

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getUser_id() {
        return user_id;
    }
    public void setUser_id(int user_id) {
        this.user_id = user_id;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    public Timestamp getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Timestamp createDate) {
        this.createDate = createDate;
    }
    public String getOperation() {
        return operation;
    }
    public void setOperation(String operation) {
        this.operation = operation;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRole_name() {
        return role_name;
    }
    public void setRole_name(String role_name) {
        this.role_name = role_name;
    }
    public String getIpAddress() {
        return ipAddress;
    }
    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }


}

系统日志方法 SysLogMapper.java:

package com.ys.mapper;


import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import com.ys.entity.SysLog;

@Repository
public interface SysLogMapper {

    /**
     * 查询所有的系统日志
     * @return
     */
    @Select("select u.name,r.role_name,s.id,s.createdate,s.operation,s.ipAddress,s.content from sys_syslog s left join sys_user u on s.user_id=u.user_id left join sys_role r on r.role_id=u.role_id order by s.createdate desc")
    List queryAllSysLog();

    /**
     * 新增系统日志
     * @param syslog
     * @return
     */
    @Insert("insert into sys_syslog (user_id,createDate,operation,content,ipAddress) values(#{user_id},#{createDate},#{operation},#{content},#{ipAddress})")
    int addSysLog(SysLog syslog);

    /**
     * 删除系统日志
     * @param id
     * @return
     */
    @Delete("delete from sys_syslog where id=#{id}")
    int deleteSysLog(int id);
}

系统日志控制层SysLogController.java:

package com.ys.controller;

import java.util.List;
import java.util.Map;

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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.entity.SysLog;
import com.ys.service.SysLogService;

/**
 * 系统日志 controller
 * @author Administrator
 *
 */
@Controller
public class SysLogController {

    @Autowired
    private SysLogService service;


    /**
     * 跳转到日志列表页
     * @return
     */
    @RequestMapping(value="sysLogListInput")
    public String sysLogListInput(){
        return "sysLogList";
    }

    /**
     * 获取日志列表数据
     * @return
     */
    @RequestMapping(value="queryAllSysLogData",method=RequestMethod.POST)
    @ResponseBody
    public List queryAllSysLogData(){
        return service.queryAllSysLog();
    }

    /**
     * 删除日志
     * @param data
     * @return
     */
    @RequestMapping(value="deleteSysLogData",method=RequestMethod.POST)
    @ResponseBody
    public Map deleteSysLogData(String data){
        return service.deleteSysLog(data);
    }

}

切面类 SysLogAop.java: (切点为登录、增、删、改方法, 这里去除系统日志的所有方法)

package com.ys.aop;

import java.net.InetAddress;
import java.util.Map;


import org.aspectj.lang.JoinPoint;  
import org.aspectj.lang.annotation.AfterReturning;  
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Pointcut;  
import org.springframework.beans.factory.annotation.Autowired;

import com.ys.entity.SysLog;
import com.ys.entity.User;
import com.ys.service.SysLogService;
import com.ys.utils.DateUtils;  

@Aspect  
public class SysLogAop {  

    public Integer id=null;   
    public static User u=new User();  
    @Autowired  
    SysLogService service;  

    /** 
     * 管理员登录方法的切入点 
     */  
    @Pointcut("execution(* com.ys.service.*.loginValid(..))")  
    public void loginCell(){  
    }  

    /** 
     * 添加业务逻辑方法切入点    去除日志的所有方法
     */ 
    @Pointcut("execution(* com.ys.service.*.add*(..)) && !execution(* com.ys.service.SysLogService.*(..))")  
    public void insertCell() {  
    }  

    /** 
     * 修改业务逻辑方法切入点 
     */  
    @Pointcut("execution(* com.ys.service.*.update*(..)) && !execution(* com.ys.service.SysLogService.*(..))")  
    public void updateCell() {  
    }  

    /** 
     * 删除业务逻辑方法切入点 
     */  
    @Pointcut("execution(* com.ys.service.*.delete*(..)) && !execution(* com.ys.service.SysLogService.*(..))")  
    public void deleteCell() {  
    }  

    /**
     * 获取用户登录成功传过来的user值
     * @param user
     * @return
     */
    public static User getUser(User user){
        u=user;
        return u;
    }


    /** 
     * 登录操作(后置通知) 
     * @param joinPoint 
     * @param object 
     * @throws Throwable 
     */  
    @AfterReturning(value = "loginCell()", argNames = "object", returning = "object")  
    public void loginLog(JoinPoint joinPoint, Object object) throws Throwable {  
        @SuppressWarnings("unchecked")
        //获取service登录执行后的参数  这里返回map
        Map map=(Map) object; 
        System.out.println(map);
        if (map.get("status")=="error") {  
            return;  
        }  
        if (joinPoint.getArgs() == null) {// 没有参数  
            return;  
        }  
        id=u.getUser_id();

        SysLog syslog=new SysLog();
        syslog.setContent(opContent(joinPoint));  
        syslog.setUser_id(id);
        syslog.setCreateDate(DateUtils.getTimestamp());  
        syslog.setOperation("登录"); 
        //PC-20170215CNRU/192.168.1.104截取为192.168.1.104
        syslog.setIpAddress(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/")+1));
        service.addSysLog(syslog); 
    }  

    /** 
     * 添加操作日志(后置通知) 
     *  
     * @param joinPoint 
     * @param object 
     */  
    @AfterReturning(value = "insertCell()", argNames = "object", returning = "object")  
    public void insertLog(JoinPoint joinPoint, Object object) throws Throwable {  
        // 判断参数  
        if (joinPoint.getArgs() == null) {// 没有参数  
            return;  
        }  

        SysLog syslog=new SysLog();
        syslog.setContent(opContent(joinPoint));  
        syslog.setUser_id(id);  
        syslog.setCreateDate(DateUtils.getTimestamp());  
        syslog.setOperation("添加");  
        syslog.setIpAddress(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/")+1));
        service.addSysLog(syslog);  
    }  

    /** 
     * 管理员修改操作日志(后置通知) 
     *  
     * @param joinPoint 
     * @param object 
     * @throws Throwable 
     */  
    @AfterReturning(value = "updateCell()", argNames = "object", returning = "object")  
    public void updateLog(JoinPoint joinPoint, Object object) throws Throwable {  
        // 判断参数  
        if (joinPoint.getArgs() == null) {// 没有参数  
            return;  
        }  

        // 创建日志对象  
        SysLog syslog=new SysLog();
        syslog.setContent(opContent(joinPoint));  
        syslog.setUser_id(id);  
        syslog.setCreateDate(DateUtils.getTimestamp());  
        syslog.setOperation("修改");  
        syslog.setIpAddress(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/")+1));
        service.addSysLog(syslog); 
    }  

    /** 
     * 删除操作 
     *  
     * @param joinPoint 
     * @param object 
     */  
    @AfterReturning(value = "deleteCell()", argNames = "object", returning = "object")  
    public void deleteLog(JoinPoint joinPoint, Object object) throws Throwable {  
        if (joinPoint.getArgs() == null) {// 没有参数  
            return;  
        }  

        // 创建日志对象  
        SysLog syslog=new SysLog();
        syslog.setContent(opContent(joinPoint));  
        syslog.setUser_id(id);  
        syslog.setCreateDate(DateUtils.getTimestamp());  
        syslog.setOperation("删除");  
        syslog.setIpAddress(InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/")+1));
        service.addSysLog(syslog);
    }  

   /**
    * 获取执行的操作的信息 
    * @param joinPoint
    * @return
    */
    public String opContent(JoinPoint joinPoint){
        //获取类名
        String className=joinPoint.getTarget().getClass().getName();
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        String str="执行了"+className+"类的"+methodName+"方法";
        return str;
    }




}

这里的登录操作是后台验证的时候传过来用户id。

用户登录 UserService:

/**
     * 验证登录
     * @param login_name
     * @param login_password
     * @param request
     * @return
     */
    public Map loginValid(String username,String password,HttpServletRequest request){
        User user=mapper.queryByUsernameAndPassword(username, password);
        Map map=new HashMap<>();
        if(user==null||"".equals(user)){
            map.put("status", "error");
            map.put("msg", "用户名或密码错误!");
        }else if(user!=null&&!"".equals(user.getUser_id())){
            SysLogAop.getUser(user);
            map.put("status", "ok");
            map.put("msg", "登录成功!");
            request.getSession().setAttribute("user", user);
            request.getSession().setMaxInactiveInterval(30*60);//session超时30min
        }
        return map;
    }

另外还需要修改springMVC配置文件:
引入AOP的命名空间:

"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
    ">

扫描切面类位置:

  
<aop:aspectj-autoproxy />  
<bean id="logBean" class="com.ys.aop.SysLogAop">bean> 

然后是系统日志的JSP页面 sysLogList.jsp:

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

<%@ include file="common.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>OA-系统日志title>
<link type="text/css" rel="stylesheet" href="${ctxStatic}/bootstrap/css/bootstrap.min.css"/>
<link type="text/css" rel="stylesheet" href="${ctxStatic}/bootstrap/css/bootstrap-table.css">

<script type="text/javascript" src="${ctxStatic}/jquery/jquery-2.1.1.min.js">script>
<script type="text/javascript" src="${ctxStatic}/bootstrap/js/bootstrap.js">script>
<script type="text/javascript" src="${ctxStatic}/bootstrap/js/bootstrap-table.js">script>
<script type="text/javascript" src="${ctxStatic}/bootstrap/js/bootstrap-table-zh-CN.js">script>

<script type="text/javascript" src="${ctxStatic}/layer/layer.js">script>

head>
<body>
<div id="toolbar" class="btn-group">
<a class="btn btn-default" href="javascript:del();" role="button"><i class="fa fa-trash">删除i>a>
div>
<table id="screenTable" >table>
body>
<script type="text/javascript">

            //设置加载效果
            var index = layer.load(2, {
                      shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
            $('#screenTable').bootstrapTable({
            method:'post',
            url: "${ctx}/queryAllSysLogData",
            dataType:'json',
            toolbar:'#toolbar',
            cache: false, //不使用缓存
            striped: true, //显示行间隔色
            pagination: true, //显示分页
            pageSize: 20, //每页的行数
            pageList: [10, 20], //自定义每页的行数
            search: true, //显示表格搜索
            showRefresh: true, //刷新按钮
            showToggle: true,
            showExport: true,    //是否显示导出
            showColumns:true,
            columns: [{
            field: "checked",
            checkbox: true,
            align: "center",
            valign: "middle"
            },{
            field: "name",
            title: "姓名",
            align: "center",
            valign: "middle"
            }, {
            field: "role_name",
            title: "角色名称",
            align: "center",
            valign: "middle"
            }, {
            field: "createDate",
            title: "操作时间",
            align: "center",
            valign: "middle"
            }, {
            field: "operation",
            title: "操作类型",
            align: "center",
            valign: "middle"
            }, {
            field: "content",
            title: "操作内容",
            align: "center",
            valign: "middle"
            }, {
            field: "ipAddress",
            title: "IP地址",
            align: "center",
            valign: "middle"
            }],
            formatNoMatches: function () {
            return '无符合条件的记录';
            }
            });
            layer.close(index);
script>
<script type="text/javascript">
    function del(){
        var checkData=$('#screenTable').bootstrapTable('getSelections');
        if(checkData.length<1){
            layer.msg("请选择要删除的数据!",{icon:7,shift:6,time:1000});
        }else{
            var data="";
            for(var i=0;i",";
            }
            layer.confirm('是否要删除选中数据?', {
                  icon:3,       
                  title:'提示!',
                  btn: ['是','否'] //按钮
                }, function(){
                    $.ajax({
                        method:'post',
                        url:'${ctx}/deleteSysLogData',
                        data:{data:data},
                        dataType:'json',
                        success:function(ret){
                            if(ret.status=="ok"){
                                layer.msg(ret.msg,{time:500,icon:1});
                                setTimeout(function(){ location.href='${ctx}/sysLogListInput'; },500);
                            }else if(ret.status=="error"){
                                layer.msg(ret.msg,{time:500,icon:7});
                            }
                        },
                        error:function(ret){
                            layer.msg("请求异常!错误代码:"+ret.status,{time:2000,icon:7});
                        }
                    })
                }, function(){
                      layer.msg('操作取消!', 
                        {time:500,
                        icon: 5}
                      );
                    });
        }



    }
script>
html>

这里使用bootStrap-Table显示列表,layer消息弹框。页面如下:

SSM使用AOP切面获取用户登录操作日志_第1张图片

获取用户的登录增删改操作信息。

你可能感兴趣的:(bootstrap-table,layer,aop切面,ssm框架)