RequestContextHolder的使用
RequestContextHolder顾名思义,持有上下文的Request容器.使用是很简单的,具体使用如下:
springMVC中,为了方便随时获取当前的request对象,可以通过RequestContextHolder的静态方法getRequestAttributes()获取Request相关的变量,如request, response等。
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
HttpServletRequest request =((ServletRequestAttributes)ra).getRequest();
通过这种方式,就不需要在接收或传递参数的时候通过定义HttpRequest或HttpResponse来获取参数了。
例子:aop实例模块中借鉴大坝监测的SystemAspect类中的环绕通知
package com.zuoton.aop.aspect;
import java.lang.reflect.Method;
import java.util.Map;
import com.zuoton.aop.aspect.annotation.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.spi.http.HttpContext;
/**
* 操作日志记录处理
*
* @author ruoyi
*/
@Aspect
@Component
public class LogAspect
{
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
// 配置织入点
@Pointcut("@annotation(com.zuoton.aop.aspect.annotation.Log)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point)throws Throwable{
//此处使用RequestContextHolder
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String username = request.getParameter("username");
Map<String, String[]> parameterMap = request.getParameterMap();
//先执行业务
Object result = point.proceed();
try {
handle(point);
} catch (Exception e) {
log.error("日志记录出错!", e);
}
System.out.println("环绕通知=======");
return result;
}
}