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

Sun*_*aik 6 spring servlets spring-mvc spring-aop

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

尝试以下方式.

    @Autowired
    private HttpServletResponse response;

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

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
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

小智 5

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

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();
Run Code Online (Sandbox Code Playgroud)

  • `方法getResponse()未定义为ServletRequestAttributes`类型 (4认同)

小智 2

基本上,我们从 jsp 页面进行重定向,即从 UI 层处理此类操作(重定向)。因此,我希望您在应用程序中使用一些宁静的服务。对于大多数静态服务,我们采用异步请求。如果是异步服务和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
}
Run Code Online (Sandbox Code Playgroud)

步骤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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

就是这样,您已经完成了更好的实现。保证...