取消controller的请求信息打印到日志中

本文介绍了一种在Java应用中实现接口请求日志记录的切面方法,并通过注解来选择性地忽略特定Controller的请求日志,确保敏感信息不被记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 使用该注解后,"不会"将controller的请求信息打印到日志中
 * @author wanlf
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiLogIgnore {

}

切面
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.miaoshaproject.annotation.ApiLogIgnore;

/**
 * 接口请求日志切面
 * @author wanlf
 */
@Component
@Aspect
public class ApiLogAop {
  
	private static Logger logger = LoggerFactory.getLogger(ApiLogAop.class);

	@Pointcut("execution(* com.xxx.xxx.feaute.*.controller..*(..))")
	public void controller() {
	}

	@Before("controller()")
	private void beforeController(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		if (method.isAnnotationPresent(ApiLogIgnore.class)) {
			return;
		}
		if (method.isAnnotationPresent(RequestMapping.class) 
		 || method.isAnnotationPresent(PostMapping.class)
		 || method.isAnnotationPresent(PutMapping.class)	
		 || method.isAnnotationPresent(DeleteMapping.class)
	     || method.isAnnotationPresent(GetMapping.class)) {
			StringBuffer sb = new StringBuffer();
			ServletRequestAttributes sra = (ServletRequestAttributes) 
			(RequestContextHolder.getRequestAttributes());
			HttpServletRequest request = sra.getRequest();
			String requestStr = requestToString(request);
			String bodyStr = bodyToString(joinPoint);
			sb.append(requestStr).append(bodyStr);
			logger.info("[接口请求AOP]{}", sb.toString());
		}
	}
	
	/**
	 * 将请求中的body转换为字符串
	 * @param joinPoint
	 * @return
	 */
	private String bodyToString(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		Annotation[][] parameterAnnotations = method.getParameterAnnotations();
		for (Annotation[] annotations : parameterAnnotations) {
			for (Annotation annotation : annotations) {
			if (annotation.annotationType().isAssignableFrom(RequestBody.class)) {
				StringBuffer sb = new StringBuffer();
				Object[] args = joinPoint.getArgs();
				for (Object arg : args) {
					sb.append(arg);
				}
				return sb.toString();
				}
			}
		}
		return "BODY:";
	}
	
	/**
	 * 将请求转换为字符串、除了body
	 * @param request
	 * @return
	 */
	private String requestToString(HttpServletRequest request){
		StringBuffer sb=new StringBuffer();
		
		//请求客户端IP
		
		String ip=IPUtils.getIP(request);
		sb.append("IP:").append(ip).append("|");
		
		//请求URL
		String method=request.getMethod();
		StringBuffer requestURL=request.getRequestURL();
		sb.append(method).append(" ").append(requestURL).append(" |");
		// 请求头
		/*sb.append("HEADERS:[");
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String headerName = headerNames.nextElement();
			String headerValue = request.getHeader(headerName);
			sb.append(headerName).append(":").append(headerValue).append(",");
		}
		sb.append("]|");*/
		
		//请求查询参数
		String queryString=request.getQueryString();
		sb.append("QUERY_STRING:").append(queryString).append("|");
		
		//请求表单参数
		sb.append("PARAMETERS:[");
					
		Map<String, String[]> paramterMap = request.getParameterMap();
		for (Map.Entry<String, String[]> key : paramterMap.entrySet()) {
			String[] values = paramterMap.get(key);
			if (values != null && values.length != 0) {
				StringBuffer valueBuffer = new StringBuffer();
				for (String value : values) {
					valueBuffer.append(value).append(",");
				}
				sb.append(key).append(":").append(valueBuffer);
			}
		}
		sb.append("]|");
		return sb.toString();
	}
}
### 解决 Fetch 请求无法加载响应数据的问题 当遇到 `Fetch` 请求无法加载响应数据的情况时,可能涉及多个方面的原因。以下是针对此问题的详细分析以及解决方案: #### 1. **检查 SameSite 属性配置** 如果请求涉及到 Cookie 的传递,而目标站点未正确设置 `SameSite` 属性,则可能导致请求被拒绝或返回的数据为空。可以通过显式设置 `credentials` 参数来控制是否发送 Cookies[^1]。 ```javascript fetch('https://api.example.com/data', { method: 'GET', credentials: 'include' // 或者 'same-origin' }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('错误:', error)); ``` 上述代码中的 `credentials: 'include'` 可以确保在跨域场景下也尝试携带 Cookies,从而避免因缺少必要的认证信息而导致的失败。 --- #### 2. **处理 Fetch 不支持取消操作的问题** 虽然 Fetch API 自身并不提供内置的取消机制,但可以借助控制器(AbortController)实现这一需求。这有助于防止长时间运行的任务占用资源并引发潜在的数据丢失问题[^2]。 ```javascript const controller = new AbortSignal(); setTimeout(() => controller.abort(), 5000); // 设置超时时间为 5 秒 fetch('https://api.example.com/data', { signal: controller.signal }) .then(response => { if (!response.ok) throw new Error(`HTTP 错误! 状态码: ${response.status}`); return response.json(); }) .then(data => console.log(data)) .catch(error => { if (error.name === 'AbortError') { console.log('请求取消'); } else { console.error('错误:', error); } }); ``` 通过引入 `AbortController` 和其信号对象,可有效管理长期挂起的请求,减少不必要的等待时间。 --- #### 3. **应对 no-cors 场景下的限制** 对于某些特定的服务端环境,可能会因为 CORS 配置缺失导致客户端收到的是不透明 (`opaque`) 类型的响应。此时即使成功完成 HTTP 调用也无法读取实际内容[^3]。 要解决此类情况,需确认以下几点: - 客户端发出的请求确实设置了合适的模式参数; - 更重要的是,服务器端已经开放了相应的访问权限给前端应用所在的域名地址列表。 示例调整如下所示: ```javascript // 如果仅限于简单 GET/POST 并且无需自定义头部字段 fetch('https://third-party-api.com/resource', { mode: 'no-cors' }) .then(response => { // 对于 no-cors 模式的响应 body 总是 undefined console.warn('注意:由于 no-cors 设定,此处无法解析具体数据'); }).catch(err => console.error('发生异常:', err)); // 推荐做法——联系后端团队完善 CORS 政策以便切换至 cors 模式 fetch('https://third-party-api.com/resource', { mode: 'cors' })... ``` 需要注意,在大多数情况下建议优先采用标准 CORS 流程而非依赖无状态交互方式^4]。 --- #### 4. **验证 Fetch 核心组件的状态** 最后一步是对整个流程进行全面排查,包括但不限于 Request、Response、Header 和 Body 是否均处于预期范围内工作正常[^4]。 例如打印调试日志查看每阶段进展状况: ```javascript function logStatus(res){ const statusText = `${res.status} (${res.statusText})`; console.info(`接收到服务器回复:`,statusText); return res; } fetch('/path/to/api') .then(logStatus) .then(r=>r.text()) // 将二进制流转换成字符串形式便于观察原始结构 .then(textBody=>{ try{ JSON.parse(textBody); console.debug('JSON 序列化成功!'); } catch(e){ console.error('未能解析为合法 JSON:'); } }); ``` 以上方法可以帮助快速定位是否存在编码差异或者格式不符等问题影响最终呈现效果。 --- ### 结论 综上所述,解决 Fetch 请求无法加载响应数据的关键在于综合考虑以下几个维度:合理设定 SameSite 属性规避安全风险;利用现代工具如 AbortController 实现灵活可控的操作逻辑;妥善协调前后两端关于资源共享协议方面的共识达成一致意见;同时密切监控各环节执行细节确保整体链路畅通无阻。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值