如何在 Spring AOP 中获取 HttpServletRequest 和 HttpServletResponse 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30027912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:33:01  来源:igfitidea点击:

How can I get HttpServletRequest and HttpServletResponse object in Spring AOP

springspring-mvcservletsspring-aop

提问by Sunil Kumar Naik

I want to get the response object in spring AOP before advice. If the session is invalidate I want to redirect to the login page, but unable to get the HttpServletResponse object in the Before advice method.

我想在建议之前在 spring AOP 中获取响应对象。如果会话无效,我想重定向到登录页面,但无法在 Before 建议方法中获取 HttpServletResponse 对象。

Tried with the following way.

尝试了以下方法。

    @Autowired
    private HttpServletResponse response;

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

Stacktrace:

堆栈跟踪:

caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.servlet.http.HttpServletResponse com.****.****.aspect.LogProvider.response; nested exception is 

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.http.HttpServletResponse] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 33 more

Any help will be appreciated.

任何帮助将不胜感激。

采纳答案by Dilip Kumar Sahu

Basically we do redirect from a jsp page i.e. from UI layer we handle such kind of operation(redirection). So, I hope you will be using some restful services in your application. And for most of the restful services we go for Asynchronous request. If it is combination of Asynchronous and restful services; and I am sure you will be using this in your application. If your session is invalid and you try to access perform any operation on 'session' then it will land you in 'IllegalStateException'. For such type of scenario please follow the below centralized 'Exception Handling' mechanism provided by JAX-RS: javax.ws.rs.ext.ExceptionMapper. Please follow below steps: step-1:Create a user-defined unchecked exception like MyApplicationException:

基本上我们从一个jsp页面重定向,即从我们处理这种操作(重定向)的UI层。所以,我希望你会在你的应用程序中使用一些宁静的服务。对于大多数宁静服务,我们选择异步请求。如果是Asynchronous和restful服务的结合;我相信你会在你的应用程序中使用它。如果您的会话无效并且您尝试访问对“会话”执行任何操作,那么它将使您进入“IllegalStateException”。对于此类场景,请遵循 JAX-RS 提供的以下集中式“异常处理”机制:javax.ws.rs.ext.ExceptionMapper。请按照以下步骤操作: 第 1 步:创建一个用户定义的未经检查的异常,如 MyApplicationException:

public class MyApplicationException extends RuntimeException {
  public MyApplicationException() {super();}

  // implement other methods of RuntimeException as per your requirement
}

step-2:Create a user-defined type of ExceptionMapper

step-2:创建用户自定义类型的ExceptionMapper

public class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException>
{
    @Override
    public Response toResponse(MyApplicationException exception)
    {
        return Response.status(Status.FORBIDDEN).entity(exception.getMessage()).build(); 
// set any Status code of 4XX as this is client side error not server side
    }
}

step-3:In all your ajax request in the UI code check this Status Code and redirect to the login page.

第 3 步:In all your ajax request in the UI code check this Status Code and redirect to the login page.

That's it and you are done with a finer implementation. Guaranteed...

就是这样,您完成了更精细的实现。保证...

回答by shark

You can get response by under method:

您可以通过以下方法获得响应:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();

回答by Vishnu

To get the response object you can use this code:

要获取响应对象,您可以使用以下代码:

ServletWebRequest servletWebRequest=new ServletWebRequest(request);
HttpServletResponse response=servletWebRequest.getResponse();

To get the request object:

获取请求对象:

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getR?equest();

If you get a nullresponse then I can see the response is not yet formed when the control is returned. Then the only way ahead is to go with interceptors.

如果您收到null响应,那么我可以看到在返回控件时尚未形成响应。那么前进的唯一途径就是与interceptors.