瀏覽代碼

利用AOP处理Web请求日志

sunyj 9 年之前
父節點
當前提交
156f182c1f

+ 8 - 0
pom.xml

@@ -50,6 +50,7 @@
 		<fastjson.version>1.1.39</fastjson.version>
 		<httpclient.version>4.5.2</httpclient.version>
 		<itextpdf.version>5.5.9</itextpdf.version>
+		<aspectjweaver.version>1.8.9</aspectjweaver.version>
 	</properties>
 
 	<dependencies>
@@ -147,6 +148,13 @@
 			<artifactId>itextpdf</artifactId>
 			<version>${itextpdf.version}</version>
 		</dependency>
+
+		<!-- aspectjweaver -->
+		<dependency>
+			<groupId>org.aspectj</groupId>
+			<artifactId>aspectjweaver</artifactId>
+			<version>${aspectjweaver.version}</version>
+		</dependency>
 	</dependencies>
 
 	<build>

+ 81 - 0
src/main/java/com/uas/report/aop/WebLogAspect.java

@@ -0,0 +1,81 @@
+package com.uas.report.aop;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.log4j.Logger;
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.Signature;
+import org.aspectj.lang.annotation.AfterReturning;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Before;
+import org.aspectj.lang.annotation.Pointcut;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Component;
+
+import com.alibaba.druid.util.StringUtils;
+import com.uas.report.util.IpHelper;
+
+/**
+ * 利用AOP处理Web请求日志
+ * 
+ * @author sunyj
+ * @since 2016年12月20日 下午5:46:56
+ */
+@Aspect
+@Component
+@EnableAspectJAutoProxy
+public class WebLogAspect {
+
+	private Logger logger = Logger.getLogger(WebLogAspect.class);
+
+	@Pointcut("execution(* com.uas.report.controller.*.*(..))")
+	public void log() {
+
+	}
+
+	@Before("log()")
+	public void before(JoinPoint joinPoint) {
+		StringBuilder stringBuilder = new StringBuilder("request... ");
+
+		// 类名
+		Object target = joinPoint.getTarget();
+		Class<?> clazz = target.getClass();
+		stringBuilder.append(clazz.getSimpleName());
+
+		// 方法名
+		Signature signature = joinPoint.getSignature();
+		String methodName = signature.getName();
+		stringBuilder.append(".").append(methodName);
+
+		// 方法全名
+		String methodString = signature.toString();
+		// 取出参数类型
+		String substring = methodString.substring(methodString.indexOf("(") + 1, methodString.lastIndexOf(")"));
+		if (!StringUtils.isEmpty(substring)) {
+			stringBuilder.append(": ");
+			String[] strs = substring.split(",");
+			Object[] args = joinPoint.getArgs();
+			for (int i = 0; i < strs.length; i++) {
+				if (strs[i].equals("HttpServletRequest")) {
+					// 如果参数是HttpServletRequest,打印ip
+					stringBuilder.append("ip=").append(IpHelper.getIp((HttpServletRequest) args[i]));
+				} else if (strs[i].equals("HttpServletResponse")) {
+					// 如果参数是HttpServletResponse,不做处理
+					continue;
+				} else {
+					// 参数类型和参数值
+					stringBuilder.append(strs[i]).append("=").append(args[i]);
+				}
+				if (i != strs.length - 1) {
+					stringBuilder.append(",");
+				}
+			}
+		}
+		logger.info(stringBuilder.toString());
+	}
+
+	@AfterReturning(value = "log()", returning = "result")
+	public void afterReturning(JoinPoint joinPoint, Object result) {
+		logger.info("result... " + result + "\n");
+	}
+}

+ 2 - 16
src/main/java/com/uas/report/controller/PrintController.java

@@ -24,7 +24,6 @@ import com.uas.report.core.exception.ReportException;
 import com.uas.report.service.FileService;
 import com.uas.report.service.PrintService;
 import com.uas.report.util.FileUtils;
-import com.uas.report.util.IpHelper;
 import com.uas.report.util.PathUtils;
 import com.uas.report.util.ReportConstants;
 import com.uas.report.util.ReportUtils;
@@ -123,12 +122,8 @@ public class PrintController {
 	@ResponseBody
 	public void export(String userName, String profile, String reportName, String whereCondition,
 			String otherParameters, String exportFileType, HttpServletRequest request, HttpServletResponse response) {
-		logger.info(new StringBuilder("ip=").append(IpHelper.getIp(request)).append(", userName=").append(userName)
-				.append(", reportName=").append(reportName).append(", whereCondition=").append(whereCondition)
-				.append(", otherParameters=").append(otherParameters));
 		ReportUtils.checkParameters(userName, reportName);
 
-		logger.info("开始导出报表:" + userName + "/" + reportName);
 		if (StringUtils.isEmpty(exportFileType)) {
 			exportFileType = ReportConstants.PDF_FILE_TYPE;
 		}
@@ -185,7 +180,6 @@ public class PrintController {
 		} catch (IOException e) {
 			logger.error("浏览器重复请求!");
 		}
-		logger.info("报表导出完成:" + userName + "/" + reportName + "\n");
 	}
 
 	/**
@@ -213,11 +207,7 @@ public class PrintController {
 	public Map<String, Object> loadPdfData(final String userName, final String profile, final String reportName,
 			final String whereCondition, final String otherParameters, Integer pageIndex, HttpServletRequest request,
 			HttpServletResponse response) {
-		logger.info(new StringBuilder("ip=").append(IpHelper.getIp(request)).append(", userName=").append(userName)
-				.append(", reportName=").append(reportName).append(", whereCondition=").append(whereCondition)
-				.append(", otherParameters=").append(otherParameters));
 		ReportUtils.checkParameters(userName, reportName);
-		logger.info("开始预览报表:" + userName + "/" + reportName);
 		Map<String, Object> result = new HashMap<>();
 
 		// 相对路径,返回给前端
@@ -230,14 +220,14 @@ public class PrintController {
 			// 文件无效(不存在或过期),重新创建pdf文件
 			if (!fileService.isFileValid(file.getPath(), fileService.getJrxmlFilePath(userName, reportName))) {
 				// 参数pageIndex为null或1,表示是直接打印或预览第一页,
-				// 需要生成第一页(可能页数过多,提示用户不支持预览打印),再后台开线程生成总的pdf
+				// 需要生成第一页(可能页数过多,提示用户不支持预览打印),再后台开线程生成总的pdf
 				// 先生成第一页pdf
 				Integer pageSize = printService.createPdfFile(userName, profile, reportName, whereCondition,
 						otherParameters, file.getPath().replace("." + ReportConstants.PDF_FILE_TYPE,
 								"_1." + ReportConstants.PDF_FILE_TYPE),
 						1);
 				result.put("pageSize", pageSize);
-				// 再开线程生成后面页的pdf、总的pdf(即未分页的pdf)、纯数据excel
+				// 再开线程生成后面页的pdf、总的pdf(即未分页的pdf)
 				new Thread(new Runnable() {
 					@Override
 					public void run() {
@@ -263,7 +253,6 @@ public class PrintController {
 			}
 		}
 		result.put("pdfPath", pdfPath);
-		logger.info("预览报表成功:" + userName + "/" + reportName + "\n");
 		return result;
 	}
 
@@ -290,9 +279,6 @@ public class PrintController {
 	@ResponseBody
 	public Map<String, Object> getGeneratedPdfOrXlsInformation(String userName, String profile, String reportName,
 			String whereCondition, String otherParameters, String fileType, HttpServletRequest request) {
-		logger.info(new StringBuilder("ip=").append(IpHelper.getIp(request)).append(", userName=").append(userName)
-				.append(", reportName=").append(reportName).append(", whereCondition=").append(whereCondition)
-				.append(", otherParameters=").append(otherParameters));
 		Map<String, Object> result = new HashMap<>();
 		if (StringUtils.isEmpty(fileType)) {
 			fileType = ReportConstants.PDF_FILE_TYPE;

+ 48 - 0
src/main/java/com/uas/report/filter/FileDeleteFilter.java

@@ -0,0 +1,48 @@
+package com.uas.report.filter;
+
+import java.io.IOException;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import com.uas.report.core.advice.ExceptionHandlerAdvice;
+import com.uas.report.util.IpHelper;
+
+/**
+ * 对文件删除进行过滤
+ * 
+ * @author sunyj
+ * @since 2016年12月13日 下午4:46:03
+ */
+public class FileDeleteFilter implements Filter {
+
+	@Override
+	public void init(FilterConfig filterConfig) throws ServletException {
+
+	}
+
+	@Override
+	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+			throws IOException, ServletException {
+		HttpServletRequest httpRequest = (HttpServletRequest) request;
+		HttpServletResponse httpResponse = (HttpServletResponse) response;
+		// 局域网内才允许执行
+		if (!IpHelper.isLAN(IpHelper.getIp(httpRequest))) {
+			ExceptionHandlerAdvice.handleError(httpResponse, HttpServletResponse.SC_FORBIDDEN, "没有权限");
+		} else {
+			chain.doFilter(httpRequest, response);
+		}
+	}
+
+	@Override
+	public void destroy() {
+
+	}
+
+}

+ 0 - 5
src/main/java/com/uas/report/service/impl/FileServiceImpl.java

@@ -76,7 +76,6 @@ public class FileServiceImpl implements FileService {
 
 	@Override
 	public String autoDeploy(String sourceUserName, String destinationUserNames) {
-		logger.info("request... " + destinationUserNames);
 		if (StringUtils.isEmpty(sourceUserName) || StringUtils.isEmpty(destinationUserNames)) {
 			throw new ReportException("参数不能为空:sourceUserName,destinationUserNames");
 		}
@@ -176,7 +175,6 @@ public class FileServiceImpl implements FileService {
 
 	@Override
 	public String upload(String filePath, Boolean isAbsolutePath, MultipartFile[] files) {
-		logger.info("request... " + filePath);
 		String message = "";
 		if (ArrayUtils.isEmpty(files)) {
 			message = "文件为空,无法进行上传!";
@@ -263,7 +261,6 @@ public class FileServiceImpl implements FileService {
 		if (StringUtils.isEmpty(filePath) || response == null) {
 			throw new ReportException("参数不能为空:filePath,response");
 		}
-		logger.info("request... " + filePath);
 		filePath = getAbsolutePath(filePath, isAbsolutePath);
 		File file = new File(filePath);
 		if (!file.exists()) {
@@ -311,7 +308,6 @@ public class FileServiceImpl implements FileService {
 
 	@Override
 	public String delete(String filePath, Boolean isAbsolutePath) {
-		logger.info("request... " + filePath);
 		// 路径不能为空,不能只包含'/'(根路径),不能含有'..'(不允许通过该方式删除上一级)
 		if (StringUtils.isEmpty(filePath) || StringUtils.isEmpty(filePath.replaceAll("/", ""))
 				|| filePath.contains("..")) {
@@ -331,7 +327,6 @@ public class FileServiceImpl implements FileService {
 
 	@Override
 	public List<Map<String, Object>> listFiles(String filePath, Boolean isAbsolutePath) {
-		logger.info("request... " + filePath);
 		filePath = getAbsolutePath(filePath, isAbsolutePath);
 		File file = new File(filePath);
 		if (!file.exists()) {

+ 1 - 4
src/main/java/com/uas/report/service/impl/PrintServiceImpl.java

@@ -85,7 +85,6 @@ public class PrintServiceImpl implements PrintService {
 		if (dataSource == null) {
 			throw new ReportException("获取数据源失败");
 		}
-		logger.info("dataSource getted...");
 		return print(userName, reportName, whereCondition, otherParameters, null, pageIndex, dataSource);
 	}
 
@@ -193,9 +192,7 @@ public class PrintServiceImpl implements PrintService {
 		} finally {
 			if (connection != null) {
 				try {
-					logger.info("connection.close...");
 					connection.close();
-					logger.info("connection.close done...");
 				} catch (SQLException e) {
 					throw new ReportException(e).setDetailedMessage(e);
 				}
@@ -212,7 +209,7 @@ public class PrintServiceImpl implements PrintService {
 	 */
 	private String maybeCompileJrxmlFile(String jrxmlFilePath) {
 		if (StringUtils.isEmpty(jrxmlFilePath)) {
-			logger.error("参数为空:" + jrxmlFilePath);
+			logger.error("参数不能为空:" + jrxmlFilePath);
 			return null;
 		}
 		File jrxmlFile = new File(jrxmlFilePath);

+ 1 - 1
src/main/webapp/WEB-INF/web.xml

@@ -71,7 +71,7 @@
 	<!-- 文件删除过滤 -->
 	<filter>
 		<filter-name>FileDeleteFilter</filter-name>
-		<filter-class>com.uas.report.controller.filter.FileDeleteFilter</filter-class>
+		<filter-class>com.uas.report.filter.FileDeleteFilter</filter-class>
 	</filter>
 	<filter-mapping>
 		<filter-name>FileDeleteFilter</filter-name>