您可以創建一個HandlerInterceptor
可以在上下文中注入用戶:
public class PutUserInModelInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest aRequest, HttpServletResponse aResponse, Object aHandler) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest aRequest, HttpServletResponse aResponse, Object aHandler, ModelAndView aModelAndView) throws Exception {
if(aModelAndView != null) {
Principal user = aRequest.getUserPrincipal();
aModelAndView.addObject("__user", user);
}
}
@Override
public void afterCompletion(HttpServletRequest aRequest, HttpServletResponse aResponse, Object aHandler, Exception aEx) throws Exception { }
}
,然後註冊它:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new PutUserInModelInterceptor());
}
}
,然後在模板中使用它。例如:
<#if !(__user??)>
<a class="p-2" href="#" data-toggle="modal" data-target="#signinModal">Sign in</a>
<#else>
<span class="badge badge-secondary">${__user.getName()}</span>
</#if>