0

私は Struts2 フレームワークを使用しており、POJO クラスに次のメソッドがあります。

public String execute() {
    setUserPrincipal();
    //do something
    someMethod(getUserPrincipal().getLoggedInUserId());
    return SUCCESS;
}

メソッドは次のようになりsetUserPrincipal()ます

public void setUserPrincipal() {
    this.principal = (UserPrincipal) getServletRequest().getSession().getAttribute("principal");
}

基本的には、「principal」という名前のセッション属性を取得して設定するだけで、ログインしているユーザーが誰であるかを知ることができます。これを行うための呼び出しsetUserPrincipal()は、ほとんどの POJO で非常に一般的であり、セッション属性を設定する必要があるため、メソッドをテストするときにも面倒になります。

Spring などを使用してセッション属性を POJO に自動的に挿入する方法はありますか?

4

2 に答える 2

2

私は Struts2 を少ししか使用していませんが、Struts2 には特定のアクションに関連付けることができるインターセプター スタックがあります。セッション変数を注入する独自のインターセプターを作成できます。

public interface UserAware 
{
   void setUserPrincipal(String principal);
}

// Make your actions implement UserAware

public class MyInterceptor implements Interceptor
{
   public String intercept(ActionInvocation inv) throws Exception
   {
      UserAware action = (UserAware) inv.getAction();
      String principal = inv.getInvocationContext().getSession().get("principal");
      action.setUserPrincipal(principal);

      return inv.invoke();
   }
}

私が言ったように、Struts2 の経験はあまりないので、これはテストされていませんが、アイデアはそこにあると思います。

于 2012-05-31T18:09:27.407 に答える
0

セッションの挿入についてはわかりませんが、実行前にプリンシパルを設定する AOP コードが含まれている可能性があります。

ここにいくつかのドキュメントがあります:

http://static.springsource.org/spring/docs/2.5.x/reference/aop.html

于 2012-05-31T18:00:38.370 に答える