web-dev-qa-db-ja.com

SpringAOPでHttpServletRequestおよびHttpServletResponseオブジェクトを取得するにはどうすればよいですか。

アドバイスの前に、春のAOPで応答オブジェクトを取得したいと思います。セッションが無効な場合、ログインページにリダイレクトしたいのですが、BeforeアドバイスメソッドでHttpServletResponseオブジェクトを取得できません。

次の方法で試してみました。

    @Autowired
    private HttpServletResponse response;

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

スタックトレース:

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

どんな助けでもありがたいです。

6

基本的に、jspページからリダイレクトします。つまり、UIレイヤーから、このような種類の操作(リダイレクト)を処理します。したがって、アプリケーションでいくつかのRESTfulサービスを使用することを願っています。そして、ほとんどのRESTfulサービスでは、非同期リクエストを使用します。非同期サービスとRESTfulサービスの組み合わせの場合。そして、私はあなたがあなたのアプリケーションでこれを使うことになると確信しています。セッションが無効で、「セッション」で何らかの操作を実行しようとすると、「IllegalStateException」が発生します。このようなタイプのシナリオでは、JAX-RSが提供する以下の一元化された「例外処理」メカニズムに従ってください:javax.ws.rs.ext.ExceptionMapper。以下の手順に従ってください:step-1: MyApplicationExceptionのようなユーザー定義のチェックされていない例外を作成します:

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

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

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
    }
}

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

これで、より細かい実装が完了しました。保証...

1

あなたはメソッドの下で応答を得ることができます:

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