我在Spring引导应用程序中使用了Spring @Before,它应该在访问任何API之前执行。我的任务/要求:- -如果在请求头应用程序中没有传递名称--那么我们应该修改头部,并为每个API向应用程序添加“未知”值。我正在使用HttpServletWrapper类修改AOP @ as通知中的标头,如下所示。
问题是- AOP应该将更新的HttpServletrequest返回给控制器方法,但是它不能工作,不能在控制器中返回更新的方法。
控权人:
@GetMapping
@RequestMapping("/demo")
public ResponseEntity<String> getEmployee(HttpServletRequest request) {
System.out.println("Header, application-name"+request.getHeader("application-name"));
return new ResponseEntity<>("Success", HttpStatus.OK);
}春季AOP代码,
@Aspect
@Component
public class AOPExample {
@Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) ||"
+ "@annotation(org.springframework.web.bind.annotation.PostMapping)")
public void controllerRequestMapping() {}
@Before("controllerRequestMapping()")
public HttpServletRequest advice(JoinPoint jp) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
String header = request.getHeader("application-name");
if (header == null) {
HttpServletRequestWrapperClass wrappedRequest = new HttpServletRequestWrapperClass(request);
wrappedRequest.putHeader("application-name", "Unknown");
request = wrappedRequest;
} else {
//validate application name
//400 - throw bad request exception
}
System.out.println("After setting---"+request.getHeader("application-name"));
return request;
}
}发布于 2022-06-15 01:37:40
最后我解决了这个问题,
与使用“在通知使用之前”代替使用“the通知”,Before通知应该使用Instead方法返回对象。
@Aspect
@Component
public class AOPExample {
@Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) ||"
+ "@annotation(org.springframework.web.bind.annotation.PostMapping)")
public void controllerRequestMapping() {}
@Around("controllerRequestMapping()")
public Object advice(ProceedingJoinPoint jp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
String header = request.getHeader("application-name");
System.out.println("Header in AOP"+header);
if (header == null) {
HttpServletRequestWrapperClass wrappedRequest = new HttpServletRequestWrapperClass(request);
wrappedRequest.putHeader("application-name", "Unknown");
request = wrappedRequest;
} else {
//validate application name
//400 - throw bad request exception
//throw new BadRequestException("Invalid application name");
}
System.out.println("After setting---"+request.getHeader("application-name"));
return jp.proceed(new Object[] {request});
}
}更新的httpservlet请求正在进入控制器方法中。谢谢
https://stackoverflow.com/questions/72611106
复制相似问题