2012-05-04 18 views
0

私のアプリケーションには、中央コントローラクラスを拡張する多数のコントローラがあります。現在、すべてのコントローラ関数で、私の関数が現在のユーザー名を取得するために、この関数に要求を渡す必要があります。このコントローラークラスは、余分なパラメーターとして要求することなく、独自の要求を取得することは可能ですか?あなたはこのようなものを使用することができますコントローラライブラリはHttpServletRequestに直接アクセスします

public class Controller { 
    protected String environment; 

    public Controller() { 

    } 

    public ModelAndView prepareModel (HttpServletRequest request, ModelAndView model) { 
     contentDao.clearExpiredLocks(); 

     model.addObject("currentUser", contentDao.findUser(request.getRemoteUser())); 

     //define current environment 
     this.environment = (request.getRequestURL().indexOf("localhost") > 0) ? "dev" : "uat"; 
     model.addObject("environment", this.environment); 

答えて

1

次のようにあなたが現在HttpServletRequestを取得することができます:

HttpServletRequest request = (HttpServletRequest) RequestContextHolder 
    .currentRequestAttributes() 
    .resolveReference(RequestAttributes.REFERENCE_REQUEST); 

あなたは、コントローラのメソッドで、このコードを使用するか、または公開するためにそれを使用することができますリクエストスコープのBeanとしてリクエストし、対応するスコープ付きプロキシをコントローラのフィールドとして注入します。

+0

完璧な、ちょうど私が探していたもの! – Webnet

1

:ちょうど1簡単なヒントだ

public abstract class AbstractController { 

    protected HttpServletRequest req 

    protected AbstractController(HttpServletRequest req) { 
     this.req = req 
    } 
} 

public class ConcreteController extends AbstractController { 

    protected ConcreteController(String name) { 
     super(name); 
    } 

    private void getUserName(){ 
     this.req.getRemoteUser(); 
    }  
} 

を、私はそれを行うにはどのように多くの可能性があると考えています。

0

私の場合、私はユーザーMainController.getLoginPerson()を取得し、すべてのコントローラのすべてのユーザーの情報を使用します。すべてのコントローラーはMainControllerに拡張されています。ここ は)メソッドMainController.getLoginPerson(ある:

MainController.getLoginPerson() { 
    // calls to authentication service method 
    authenticationService.getLoginPerson(); 
} 

authenticationService.getLoginPerson() { 
      Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
     if (auth != null) { 
      return (UserPrincipalImpl) auth.getPrincipal(); 
     } else { 
      return null; 
     } 
} 
関連する問題