7

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.

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.

3
  • 1
    Use a Filter or HandlerInterceptor which is better suited for this task. Or use Spring Security which handles a lot more for you. Commented May 4, 2015 at 10:52
  • I used the Filter for the first time session will be null so I is redirecting to the login page, not allowing to login also. I will try with the HandlerInterceptor Commented May 4, 2015 at 10:55
  • Fix your filter to exclude the login page. Commented May 4, 2015 at 11:12

4 Answers 4

13

You can get response by under method:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();
Sign up to request clarification or add additional context in comments.

2 Comments

The method getResponse() is undefined for the type ServletRequestAttributes
How can we get the HttpServletResponse object ?
2

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:

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

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.

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

Comments

1
/**
 * @return the HttpServletResponse handled by the current thread
 */
public static Optional<HttpServletResponse> getThreadLocalResponse() {
    return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
            .filter(ra -> ra instanceof ServletRequestAttributes)
            .map(ServletRequestAttributes.class::cast)
            .map(ServletRequestAttributes::getResponse);
}

Comments

-2

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 null response 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.

1 Comment

getting response returns null!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.