SSM框架把日志信息保存到数据库过程详解
作者:等你的夏天 发布时间:2024-01-19 12:56:27
标签:SSM,框架,日志,数据库
1)在service层和mapper层中写一个插入方法和查询方法;
我们先写一个日志类;定义属性;并且要在数据库中建好表;
package entity;
public class Log {
private Integer id;
private Integer logtype;
private String description;
private String param;
public Log(){
}
public Log(Integer id, Integer logtype, String description, String param) {
this.id = id;
this.logtype = logtype;
this.description = description;
this.param = param;
}
@Override
public String toString() {
return "Log{" +
"id=" + id +
", logtype=" + logtype +
", description='" + description + '\'' +
", param='" + param + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getLogtype() {
return logtype;
}
public void setLogtype(Integer logtype) {
this.logtype = logtype;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
}
该写方法了
1、logService.java页面;
public interface LogService {
int insert(Log log);
List<Log> findAll();
}
2、logServiceImpl.java页面;
@Service
public class LogServiceImpl implements LogService {
@Autowired
private LogMapper logMapper;
@Override
public int insert(Log log) {
int i=logMapper.insert(log);
return i;
}
@Override
public List<Log> findAll() {
List<Log> logs=logMapper.findAll();
return logs;
}
}
3、logMapper.java页面:
public interface LogMapper {
int insert(Log log);
List<Log> findAll();
}
4、logMapper.xml页面;
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.LogMapper">
<insert id="insert">
<selectKey keyProperty="id" resultType="integer" order="BEFORE">
select seq_logaspect.nextval from dual
</selectKey>
insert into logaspect(id,logtype,description,param) values (#{id},#{logtype},#{description},#{param})
</insert>
<select id="findAll" resultType="entity.Log">
select * from logaspect
</select>
</mapper>
5、由于我们打印日志是通过切面,所以我们写一个切面类;
package aop;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.Log;
import entity.Student;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import service.LogService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
@Component//对象由spring管理
@Aspect//切面注解
public class LogAspect {
@Autowired
private LogService logService;
private static final Logger LOGGER = LogManager.getLogger(LogAspect.class);
//定义切入点,切入到添加了LogData注解的方法上
@Pointcut("@annotation(aop.LogData)")
public void pointCut(){
}
/**
* 记录日志的切面方法
* 在该方法中定义统一的日志记录逻辑
* @param joinPoint
*/
@Before("pointCut()")
public void log(JoinPoint joinPoint){
System.out.println("进入日志Aspect");
//获取到方法签名
MethodSignature signature= (MethodSignature) joinPoint.getSignature();
//获取到连接点方法对象
Method method=signature.getMethod();
//获取方法上面特定的注解
LogData annotation=method.getAnnotation(LogData.class);
LogType logType=annotation.logType();
String description=annotation.description();
LOGGER.info("获取到注解内容:logType="+logType.getType()
+",description:"+description);
//aop中获取request
ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request=requestAttributes.getRequest();
HttpSession session=request.getSession();
//获取操作人
Student student= (Student) session.getAttribute("student");
//获取请求数据
Map<String,String[]> parameterMap=request.getParameterMap();
//将对象转换成json字符串==>存储到请求数据字段中
//jackSon json字符串操作
ObjectMapper objectMapper=new ObjectMapper();
try {
String s=objectMapper.writeValueAsString(parameterMap);
LOGGER.info("请求数据:"+s);
Log log = new Log();
log.setLogtype(logType.getType());
log.setDescription(description);
log.setParam(s);
logService.insert(log);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//todo 将日志信息保存到数据库 LogController service mapper jsp
}
}
6、写一个loglist.jsp页面来展示信息;
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/selAll">
<input type="submit" value="查询">
</form>
<table border="1px">
<thead>
<tr>
<td>ID</td>
<td>LOGTYPE</td>
<td>DESCRIPTION</td>
<td>PARAM</td>
</tr>
</thead>
<tbody>
<c:forEach var="log" items="${logs}">
<tr>
<td>${log.id}</td>
<td>${log.logtype}</td>
<td>${log.description}</td>
<td>${log.param}</td>
</tr>
</c:forEach>
</tbody>
</table>
<a href="${pageContext.request.contextPath}/user/list" rel="external nofollow" >返回list页面</a>
</body>
</html>
7、最后,我们写一个控制层的方法;
package controller;
import aop.LogData;
import aop.LogType;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import entity.Log;
import entity.Student;
import mapper.StudentsMapper;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import service.LogService;
import service.StudentService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
/**
* 控制层调service,service调dao层
*/
@Controller
@RequestMapping("/user")
public class UserController {
//定义日志对象
//private static final Logger logger= LogManager.getLogger(UserController.class);
@Autowired
private StudentService studentService;
@Autowired
private LogService logService;
@RequestMapping("/list") //@ModelAttribute(name = "params") :向request域中存值
public String list(ModelMap modelMap,@RequestParam HashMap<String,Object> map){
//定义debug级别的日志
//logger.debug("前台传递的查询条件:"+map);
//logger.info("info级别日志:"+map);
System.out.println("前台传递的查询条件:"+map);
//List<Student> students = studentService.findAll();
// List<Student> students = studentService.findByMap(map);
// modelMap.put("students",students);
PageInfo<Student> page = studentService.findByPage(map);
//记录error级别日志
//logger.error("查询到分页数据:"+page);
System.out.println("查询到分页数据:"+page);
modelMap.put("page",page);
modelMap.put("params",map);//将查询条件回传到页面,用于回显查询条件
return "list.jsp";
}
@LogData(logType = LogType.DELETE,description = "学生信息删除")
@RequestMapping("/delete")
public String delete(Integer id){
studentService.delete(id);
return "redirect:list";
}
@LogData(logType = LogType.UPDATE,description = "学生信息修改")
@RequestMapping("/update2")
public String update2(Integer id,ModelMap modelMap){
Student student = studentService.selectById(id);
modelMap.put("student",student);
return "update.jsp";
}
//根据是否存在id值,来判断是执行新增还是修改操作
@RequestMapping("/update")
public String update(Student student){
studentService.update(student);
return "redirect:list";
}
@LogData(logType = LogType.INSERT,description = "学生信息新增")
@RequestMapping("/insert")
public String insert(Student student){
studentService.insert(student);
return "redirect:list";
}
@Autowired
private StudentsMapper studentsMapper;
@RequestMapping("list2")
public String list2(ModelMap modelMap){
PageHelper.startPage(1,5);
List<Student> students=studentsMapper.selectAll();
modelMap.put("students",students);
PageInfo<Student> pageInfo=new PageInfo<>(students);
System.out.println(pageInfo);
return "list.jsp";
}
@RequestMapping("/selAll")
public String findAll(ModelMap modelMap){
List<Log> logs = logService.findAll();
modelMap.put("logs",logs);
return "loglist.jsp";
}
}
测试结果,我们出来的页面效果是:
即说明打印日志成功了;
来源:https://www.cnblogs.com/xie-qi/p/13047345.html


猜你喜欢
- 本文实例讲述了Python实现公历(阳历)转农历(阴历)的方法。分享给大家供大家参考,具体如下:两个要点:1、公历转农历用了查表法(第126
- python中可以使用下标索引来访问列表中的值,对列表进行切片即截取,也可以对列表的数据项进行修改或更新。使用下标索引来访问列表中的值,例如
- key: [com.alibaba.druid.stat.DruidDataSourceStatManager.addDataSource(
- I/O吞吐量小,形成了瓶颈效应。 没有创建计算列导致查询不优化。 内存不足。 网络速度慢。 查询出的数据量过大(可以采用多次查询,其他的方法
- vue的面包屑导航组件 用来将其放到navbar中;Breadcrumb/index.vue<template> &
- 1、要连接MySql数据库必须首先下载MySql官方的连接.net的文件,文件下载地址为http://dev.mysql.com/downl
- 最近因项目需要用ACCESS做数据库开发WEB项目看论坛上还许多人问及ACCESS被注入的安全问题许多人解决的方法仍然是用Replace替换
- 表还是total_sales添加一项表:SQL语句:SELECT * from( SELECT a1.N
- 本文详细介绍了Python中类型关系和继承关系。分享给大家供大家参考。具体分析如下:如果一个对象A持有另一个对象B的ID,那么检索到A之后就
- 前言写 Python 的经常要写一些命令行工具,虽然标准库提供有命令行解析工具 Argparse,但是写起来非常麻烦,我很少会使用它。命令行
- Python 添加类型标注Python 如此简洁,书写者在声明变量时甚至无需考虑类型。但是简洁与复杂间,是存在一个平衡点的。当我们书写较为复
- 需求描述:在公司老旧系统里,数据库表很多,但是在设计之初并没有建立好关系图,导致新人刚入职,面对N个库,每个库几百张表,很不方便。例如:公司
- 使用axios发送post请求出现400错误出现400状态码主要有两种原因1.bad request:“错误的请求&qu
- 在《python深度学习》这本书中。一、21页mnist十分类导入数据集from keras.datasets import mnist(t
- 随机数我们都知道,就是计算机通过某种算法,“随机”的生成一个数字。很多编程语言都有内置的方法来生成随机数,那么 GoLang 中是怎样一种情
- BEGIN -- 声明变量 DECLARE v_addtime_begin varchar(13); DECLARE v_addtime_e
- 刚开始涉及到图像处理的时候,在opencv等库中总会看到mask这么一个参数,非常的不理解,在查询一系列资料之后,写下它们,以供翻阅。什么是
- 背景前段时间写了一个自动化安装 MySQL 的程序,其中有一个环节就是动态的渲染 my.cnf 文件;总的解决方案就是像 Django 渲染
- 使用Tensorflow进行深度学习训练的时候,需要对训练好的网络模型和各种参数进行保存,以便在此基础上继续训练或者使用。介绍这方面的博客有
- 本文实例讲述了C#处理MySql多个返回集的方法。分享给大家供大家参考。具体方法如下:关于Mysql返回多个集java和Php的较多,但是C