java aspect 切面怎么获取 POST 数据
/** * 切面 */ @Aspect @Component public class PostRequestBodyAspect { @Pointcut("execution(* com.example.controller.*.*(..))") public void controllerMethods() {} @Around("controllerMethods() && args(.., @RequestBody requestBody)") public Object aroundControllerMethods(ProceedingJoinPoint joinPoint, Object requestBody) throws Throwable { // 在这里获取到 POST 请求体中的参数 // requestBody 就是 POST 请求体中的参数 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String data=getFormData(request,requestBody); Date startDate=new Date(); try { // 执行原始方法 Object result = joinPoint.proceed(); // 可以对原始方法的返回值进行拦截和修改 return result; } catch (Exception e) { // 处理异常情况 throw e; } finally { HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttribute()) .getResponse(); Date endDate=new Date(); // 获取并处理Response对象 System.out.println("Response Status Code: " + response.getStatus()); System.out.println("Response Content Type: " + response.getContentType()); System.out.println("Response Body: " + response.getWriter().toString()); //写入日志到数据库 Int responseStatue=request.getStatus(); Long costTime=endDate.getTime()-startDate.getTime(); //耗时 } } /** * 获取POST GET的data数据 * @param request * @return大 */ private static String getFormData(HttpServletRequest request,object requestBody) { if("POST".equalsIgnoreCase(request.getMethod())){ return requestBody==null?"": JSONObject.toJsONString(requestBody); } String data = request.getParameterMap().entrySet().stream().map(entry -> { String result; String[] value = entry .getvalue(); if (value != null && value.length > 1) { result = Anrays.stream(value).map(s -> entry.getkey() + "=" + s).collect(Collectors.joining("&")); }else { result = entry.getKey() + "=" + value[o]; } return result; }).collect(Collectors.joining("&")) return data; } }
标签:java,String,request,requestBody,result,aspect,return,POST From: https://www.cnblogs.com/zhian/p/17987461