java通过filter实现操作日志入库的实现

java Web工程实现操作日志记录的方式有很多,比如通过spring aop方式实现,也可以通过Filter方式实现。

public class StoreLogFilter implements Filter {
	private static final Logger logger = LoggerFactory.getLogger(StoreLogFilter.class);
	private static Map logRelation = new HashMap();// 存放请求URL对应的日志类型和操作说明

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 从配置文件获取配置ip
		String path = "logRelation.properties";
		Properties prop = new Properties();
		try {
			InputStreamReader ins = new InputStreamReader(
					StoreLogFilter.class.getClassLoader().getResourceAsStream(path), "UTF-8");
			prop.load(ins);
			Enumeration keyNames = prop.keys();
			while (keyNames.hasMoreElements()) {
				String key = (String) keyNames.nextElement();
				if (StringUtils.isNotBlank(key)) {
					String value = prop.getProperty(key);
					logRelation.put(key, value);
				}
			}
		} catch (Exception e) {
			logger.error("init logRelation error," + e.getMessage());
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpServletRequest;
		try {
			MyResponseWrapper responseWrapper = new MyResponseWrapper((HttpServletResponse) response);
			chain.doFilter(request, responseWrapper);
			if (request instanceof HttpServletRequest) {
				httpServletRequest = (HttpServletRequest) request;
				String userName = CommonUtils.getUserName(httpServletRequest);
				String pathInfo = httpServletRequest.getPathInfo();
				pathInfo = pathInfo.substring(1, pathInfo.length());
				//http://localhost:8080/Coolmart/login/login
				String url = httpServletRequest.getRequestURI().toString();
				if(url.contains("/login/login")){
					userName = httpServletRequest.getParameter("account");
				}
				if (logRelation.get(pathInfo) != null && StringUtils.isNotBlank(userName)) {
					// 记录日志
					insertLog(responseWrapper, httpServletRequest, userName, pathInfo);
				}
			}
		} catch (Exception e) {
			String errorMsg = new StringBuilder().append("write log to database error,").append(e.getMessage())
					.toString();
			logger.error(errorMsg);
		} finally {
		}
	}

	@Override
	public void destroy() {

	}

	/**
	 * 记录日志
	 * 
	 * @param responseWrapper
	 * @param httpServletRequest
	 * @param userName
	 * @param pathInfo
	 */
	private void insertLog(MyResponseWrapper responseWrapper, HttpServletRequest httpServletRequest, String userName,
			String pathInfo) {
		MyWriter myWriter = responseWrapper.getMyWriter();
		String returnMsg = "";
		if (myWriter != null) {
			returnMsg = myWriter.getContent();
		}
		String ip = CommonUtils.getRequestIp(httpServletRequest);
		String param = CommonUtils.getParam(httpServletRequest);
		String value = logRelation.get(pathInfo);
		String[] values = value.split(",");
		String action = values[0];
		int type = Integer.parseInt(values[1]);
		// 根据返回的rtnCode值判断执行结果(0正常,1异常)
		int result = getProcessResult(returnMsg);
		String requestUrl = String.valueOf(httpServletRequest.getRequestURL());
		// 开始记录日志
		StoreService.getInstance().insertLog(userName, ip, param, action, type, result, returnMsg,requestUrl);
	}

	/**
	 * 根据返回的rtnCode值判断执行结果
	 * 
	 * @param returnMsg
	 * @return
	 */
	private int getProcessResult(String returnMsg) {
		if (StringUtils.isNotBlank(returnMsg)) {
			String code = String.valueOf(JSONObject.fromObject(returnMsg).get("rtnCode"));
			if (code.equalsIgnoreCase("null") || code.equals("0") || code.equals("000")) {
				return 0;
			} else {
				return 1;
			}
		}
		return 0;
	}
}
工具类:CommonUtils

public class CommonUtils {
	/**
	 * 获取请求ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getRequestIp(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值,第一个ip才是真实ip
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getRemoteAddr();
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

	/**
	 * 获取请求参数,以json字符串形式返回
	 * 
	 * @param request
	 * @return
	 * @throws JsonProcessingException
	 */
	public static String getParam(HttpServletRequest request) {
		Map params = getParamKv(request);
		return JSONObject.fromObject(params).toString();
	}

	/**
	 * 获取请求参数,以map形式返回
	 * 
	 * @param request
	 * @return
	 */
	public static Map getParamKv(HttpServletRequest request) {
		Map map = new HashMap();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					map.put(paramName, paramValue);
				}
			}
		}
		return map;
	}

	/**
	 * 获取用户名
	 * 
	 * @param request
	 * @return
	 */
	public static String getUserName(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object userNameObj = session.getAttribute(Constants.SS_ACCOUNT);
		String userName = "";
		if (userNameObj != null) {
			userName = (String) userNameObj;
		}
		return userName;
	}
}



你可能感兴趣的:(java,web开发)