2014-05-16 68 views
1

我得到了一個實體的用戶,我想每個控制器的每個方法有訪問登錄的用戶不喜歡打字什麼:包括登錄方法

model.addAttribute(userDao.getuser(principal.getUsername())); 

回答

1

你可以實現一個簡單的HandlerInterceptorAdapter,將增加用戶實例調用處理程序之後的模型。

class UserAddingHandlerInterceptor extends HandlerInterceptorAdapter { 

    // Autowire dependencies... 

    private static final String ATTRIBUTE = "user"; 

    @Override 
    public void postHandle(HttpServletRequest request, 
          HttpServletResponse response, 
          Object handler, 
          ModelAndView modelAndView) throws Exception { 

     if (modelAndView != null && !modelAndView.getModelMap().hasAttribute(ATTRIBUTE) { 
      modelAndView.addObject(ATTRIBUTE, userDao.getuser(principal.getUsername())); 
     } 
    } 
}