springboot如何获取request请求的原始url与post参数
作者:qianggetaba
这篇文章主要介绍了springboot如何获取request请求的原始url与post参数问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
获取请求的完整url与请求参数,post的body中的数据,最根本的是利用HttpServletRequest ,来获取信息,然后是可以使用不同的方式,比如aop拦截,spring中已有过滤器类,方便使用
使用springboot的aop拦截
import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; 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; @Aspect @Component public class MyAspect { private final static Logger logger = LoggerFactory.getLogger(MyAspect.class); //这个切点的表达式需要根据自己的项目来写 @Pointcut("execution(public * com..*(..))") public void log() { } @Before("log()") public void doBefore(JoinPoint joinPoint) { logger.info("aop doBefore.."); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); logger.info("url={}",request.getRequestURI()); logger.info("method={}", request.getMethod()); logger.info("ip={}", request.getRemoteAddr()); logger.info("classMethod={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); Enumeration<String> paramter = request.getParameterNames(); while (paramter.hasMoreElements()) { String str = (String) paramter.nextElement(); logger.info(str + "={}", request.getParameter(str)); } } @After("log()") public void doAfter() { logger.info("aop doAfter"); } }
使用filter拦截器
@Bean public Filter loggingFilter(){ AbstractRequestLoggingFilter f = new AbstractRequestLoggingFilter() { @Override protected void beforeRequest(HttpServletRequest request, String message) { System.out.println("beforeRequest: " +message); StringBuilder msg = new StringBuilder(); ServletRequest copiedRequest = new HttpServletRequestWrapper(request); byte[] requestBody; try { requestBody = IOUtils.toByteArray(request.getInputStream()); msg.append(new String(requestBody)); } catch (IOException e) { e.printStackTrace(); } System.out.println("msg:"+msg); } @Override protected void afterRequest(HttpServletRequest request, String message) { System.out.println("afterRequest: " +message); } }; f.setIncludeClientInfo(true); f.setIncludePayload(true); // 在afterRequest的message最后会有post的body f.setIncludeQueryString(true); f.setIncludeHeaders(true); f.setMaxPayloadLength(10000); f.setBeforeMessagePrefix("BEFORE REQUEST [>"); f.setBeforeMessageSuffix("<]\n"); f.setAfterMessagePrefix("AFTER REQUEST [>"); f.setAfterMessageSuffix("<]\n"); return f; }
同类的还有CommonsRequestLoggingFilter
好处:
可以快速自定义拦截哪些url在shouldLog
方法配置
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.CommonsRequestLoggingFilter; import javax.servlet.http.HttpServletRequest; @Configuration public class LoggingFilter extends CommonsRequestLoggingFilter { private final Logger logger = LoggerFactory.getLogger(LoggingFilter.class); private static long beforeTime; private static long afterTime; public MyDeskCalendarLoggingFilter(){ super.setIncludeClientInfo(false); super.setIncludeHeaders(false); super.setIncludePayload(true); super.setMaxPayloadLength(2000); super.setIncludeQueryString(true); } @Override protected boolean shouldLog(HttpServletRequest request) { String requestURI = request.getRequestURI(); // Checks if request matches /api/calendarCompletionDate boolean shouldLog = requestURI.matches("^/api\\/calendarCompletionDate$"); if (shouldLog) { long currentUserId = SecurityUtils.getCurrentAccountUserId(); String method = request.getMethod(); super.setBeforeMessagePrefix("Before request [" + method + "," + "currentUserId:" + currentUserId + ","); //Default is just Before request super.setAfterMessagePrefix("After request [" + method + "," + "currentUserId:" + currentUserId + ","); //Default is just After request } return shouldLog; } @Override protected void beforeRequest(HttpServletRequest request, String message) { beforeTime = System.currentTimeMillis(); MemoryLogUtil.logUsed("beforeRequest");//only shows at this moment in time super.beforeRequest(request, message); } @Override protected void afterRequest(HttpServletRequest request, String message) { afterTime = System.currentTimeMillis(); logger.info("afterRequest: Time taken: " + (afterTime-beforeTime) + " in milliseconds"); MemoryLogUtil.logUsed("afterRequest");//only shows at this moment in time super.afterRequest(request, message); } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。