利用SpringAop实现日志功能

下面将实现日志的查看,通知的记录工能。

使用技术:SM+SERVLET

1.创建日志实体类

import java.util.Date;

public class Log {
private Date oprTime; //操作时间
private String type;//系统日志,登录日志,操作日志
private String operator;//操作人员
private String moudle;//在那个部分
private String operation;//进行了什么操作
private String result;//结果
  
省略get(),set()...
}

2.dao接口
import java.util.List;

@Repository("logDao")
public interface LogDao {
void insert(Log log);//插入日志
List<Log> selectByType(String type);//根据日志类型获取日志

}

3.logDao.xml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mgy.dao.LogDao">
<resultMap id="resultMap" type="Log">
<result property="oprTime" column="opr_time" javaType="java.util.Date"/>
<result property="type" column="type" javaType="String"/>
<result property="operator" column="operator" javaType="String"/>
<result property="moudle" column="moudle" javaType="String"/>
<result property="operation" column="operation" javaType="String"/>
<result property="result" column="result" javaType="String"/>
</resultMap>

<insert id="insert" parameterType="Log">
insert into log values (#{oprTime},#{type},#{operator},#{moudle},#{operation},#{result})
</insert>

<select id="selectByType" parameterType="String" resultMap="resultMap">
select * from log where type = #{type} order by opr_time desc
</select>


</mapper>
4.实现logService
import com.mgy.entity.Log;

import java.util.List;

public interface LogService {
void addSystemLog(Log log);//插入系统日志
void addLoginLog(Log log);//插入登录日志
void addOperationLog(Log log);//插入操作日志

List<Log> getSystemLog();//得到系统日志
List<Log> getLoginLog();//得到登录日志
List<Log> getOperationLog();//得到操作日志
}

5.logServiceImpl
@Service("logService")
public class LogServiceImpl implements LogService {
@Resource
private LogDao logDao;
  /*
  *在这里将必备的时间,日志类型提前做好插入和准备。
  **/
public void addSystemLog(Log log) {
log.setOprTime(new Date());
log.setType("system");
logDao.insert(log);
}

public void addLoginLog(Log log) {
log.setOprTime(new Date());
log.setType("login");
logDao.insert(log);
}

public void addOperationLog(Log log) {
log.setOprTime(new Date());
log.setType("operation");
logDao.insert(log);
}

public List<Log> getSystemLog() {
return logDao.selectByType("system");
}

public List<Log> getLoginLog() {
return logDao.selectByType("login");
}

public List<Log> getOperationLog() {
return logDao.selectByType("operation");
}
}
6.LogAdvice  切面类,用于增强方法截取用户操作过程
@Component
@Aspect
public class LogAdvice {
@Resource
private LogService logService;
/*
* 操作日志
* */
//后置增强,对controller下所有*.controller进行方法增强,排除selefcontroller与to开头的方法(使用的框架为sm+servlet)
@After("execution(* com.mgy.controller.*.*(..)) && !execution(* com.mgy.controller.SelfController.*(..)) && execution(* com.mgy.controller.*.to*(..))")
public void operationLog(JoinPoint joinPoint){//需要通过joinpoint来获取
Log log = new Log();
log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());//获取类名
log.setOperation(joinPoint.getSignature().getName());//获取方法名
HttpServletRequest request = (HttpServletRequest) joinPoint.getArgs()[0];//获取参数列表
HttpSession session = request.getSession();//将拿到的参数列表的第一个参数获取到sessiong
Object o = session.getAttribute("USER");//从session中拿出用户session
Staff staff = (Staff)o;
log.setOperator(staff.getAccount());//将session中的用户记录
log.setResult("成功");//未发生异常set成功
logService.addOperationLog(log);

}
/*
* 系统异常日志
* */

@AfterThrowing(throwing = "e",pointcut = "execution(* com.mgy.controller.*.*(..)) && !execution(* com.mgy.controller.SelfController.*(..))")
public void systemLog(JoinPoint joinPoint,Throwable e){//需要通过joinpoint来获取
Log log = new Log();
log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());//获取类名
log.setOperation(joinPoint.getSignature().getName());//获取方法名
HttpServletRequest request = (HttpServletRequest) joinPoint.getArgs()[0];//获取参数列表
HttpSession session = request.getSession();//将拿到的参数列表的第一个参数获取到sessiong
Object o = session.getAttribute("USER");//从session中拿出用户session
Staff staff = (Staff)o;
log.setOperator(staff.getAccount());//将session中的用户记录
log.setResult(e.getClass().getSimpleName());//获取发生异常的类
logService.addSystemLog(log);
}

/*
* 登陆日志
* */

@After("execution(* com.mgy.controller.SelfController.login(..))")
public void loginLog(JoinPoint joinPoint){//需要通过joinpoint来获取
Log log = new Log();
log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());//获取类名
log.setOperation(joinPoint.getSignature().getName());//获取方法名
HttpServletRequest request = (HttpServletRequest) joinPoint.getArgs()[0];//获取参数列表
HttpSession session = request.getSession();//将拿到的参数列表的第一个参数获取到sessiong
Object o = session.getAttribute("USER");//从session中拿出用户session
if (o==null){
log.setOperation(request.getParameter("account"));//如果获取不到session证明未登陆成功,此时将用户输入的用户名记录
log.setResult("失败");
}else {
// 如果session中有值代表登陆成功
Staff staff = (Staff)o;
log.setOperator(staff.getAccount());//将session中的用户记录
log.setResult("成功");
}

logService.addLoginLog(log);

}


/*
* 登出日志
* */
@Before("execution(* com.mgy.controller.SelfController.logout(..))")
public void logoutLog(JoinPoint joinPoint){//需要通过joinpoint来获取
Log log = new Log();
log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());//获取类名
log.setOperation(joinPoint.getSignature().getName());//获取方法名
HttpServletRequest request = (HttpServletRequest) joinPoint.getArgs()[0];
HttpSession session = request.getSession();
Object o = session.getAttribute("USER");
if (o==null){
log.setOperation(request.getParameter("account"));
}else {
Staff staff = (Staff)o;
log.setOperator(staff.getAccount());
log.setResult("成功");
}

logService.addLoginLog(log);

}
}
7.LogController
@Controller
public class LogController {

@Resource
private LogService logService;

public void operationLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Log> operationLog = logService.getOperationLog();
request.setAttribute("LIST",operationLog);
request.setAttribute("TYPE","操作");//设置前台展示的日志title方便区分
request.getRequestDispatcher("/WEB-INF/page/log_list.jsp").forward(request,response);
}

public void loginLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Log> loginLog = logService.getLoginLog();
request.setAttribute("LIST",loginLog);
request.setAttribute("TYPE","登陆");
request.getRequestDispatcher("/WEB-INF/page/log_list.jsp").forward(request,response);
}

public void systemLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Log> systemLog = logService.getSystemLog();
request.setAttribute("LIST",systemLog);
request.setAttribute("TYPE","系统");
request.getRequestDispatcher("/WEB-INF/page/log_list.jsp").forward(request,response);
}

}
前端实现:
左侧导航栏:
<li>
<div class="nav_m">
<span><a>日志信息</a></span>
<i>&nbsp;</i>
</div>
<ul class="erji">
<li>
<span><a href="log/operationLog.do" target="main">操作日志</a></span>
</li>
<li>
<span><a href="log/loginLog.do" target="main">登陆日志</a></span>
</li>
<li>
<span><a href="log/systemLog.do" target="main">系统日志</a></span>
</li>
</ul>
</li>
跳转到的界面
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">${TYPE}日志</span>
</div>
<div class="space_hx">&nbsp;</div>
<!--列表-->
<table cellpadding="0" cellspacing="0" class="list_hy">
<tr>
<th scope="col">操作时间</th>
<th scope="col">操作人员</th>
<th scope="col">模块</th>
<th scope="col">操作</th>
<th scope="col">结果</th>
</tr>
<c:forEach items="${LIST}" var="log">
<tr>
<td><fmt:formatDate value="${log.oprTime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td>${log.operator}</td>
<td>${log.moudle}</td>
<td>${log.operation}</td>
<td>${log.result}</td>
</tr>
</c:forEach>
</table>
</div>

</div>
</div>
</body>

附上配置文件:

spring.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 全局扫描 -->
<context:component-scan base-package="com.mgy"/>
<aop:aspectj-autoproxy/>
<!-- Spring整合Mybatis -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/sm?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.mgy.entity"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mgy.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 声明式事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="search*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.mgy.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>

</beans>



web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">

<filter>
<filter-name>Encoding</filter-name>
<filter-class>com.mgy.global.EncodingFilter</filter-class>
<init-param>
<param-name>ENCODING</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>Login</filter-name>
<filter-class>com.mgy.global.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>


<servlet>
<servlet-name>Global</servlet-name>
<servlet-class>com.mgy.global.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Global</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>




posted @ 2019-08-13 11:00  福尔摩洋  阅读(609)  评论(0编辑  收藏  举报