0

Spring MVC ベースの Web アプリケーションがあります。現在、私のWebページでは、ユーザーがログインした後にユーザーの姓名を表示しています。これを行う方法は、@Controller@RequestMappingに入るすべてのHttpServletRequestに対して、プリンシパルオブジェクトを取得し、ユーザーの詳細を取得することです次に、ModelMap に firstname および lastname 属性を設定します。たとえば、サンプルコードは次のとおりです

@Autowired
private SecurityDetails securityDetails;

@RequestMapping(method = RequestMethod.GET)
public String showWelcomePage(HttpServletRequest request,
        HttpServletResponse response, ModelMap model, Principal principal)
{
    securityDetails.populateUserName(model, principal);
            ... lot of code here;
    return "home";
}



public boolean populateUserName(ModelMap model, Principal principal) {
    if (principal != null) {
        Object ob = ((Authentication)principal).getPrincipal();
        if(ob instanceof MyUserDetails)
        {
            MyUserDetails ud = (MyUserDetails)ob;
            model.addAttribute("username", ud.getFirstName() + " " + ud.getLastName());
        }
        return true;
    }
    else
    {
        logger.debug("principal is null");
        return false;
    }
}

私の問題は、RequestMapping ごとに populateUserName メソッドを呼び出さなければならないことです。これを Interceptor メソッドに取り込むなど、アプリケーション全体でこのメソッドが 1 か所で呼び出されるようにするエレガントな方法はありますか?

4

2 に答える 2

2

コードの重複を防ぎたいのは良いことです。これを行う方法は次のとおりです。

  1. カスタムHandlerInterceptor http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/servlet/HandlerInterceptor.htmlを作成します

  2. Post ハンドルは、他のメソッドがデフォルトを返すため、私たちが関心を持っている唯一のメソッドです。

  3. ポスト ハンドル メソッドでは、コントローラーから返されたモデルとビューにアクセスできます。先に進んで、必要なものを追加してください。

  4. ここPrincipalでは直接利用できません。次のようなコードを使用して検索する必要がありますSecurityContextHolder.getContext().getAuthentication().getPrincipal()

  5. ハンドラー インターセプターを配線して、コントローラーのすべてまたは一部をインターセプトします。

お役に立てれば。

于 2013-04-24T20:46:27.990 に答える