55d99b669deca32d5f941b5ac369492ab9647399
[JavaForFun] /
1 package de.spring.example.rest.handler;
2
3 import javax.inject.Inject;
4 import javax.servlet.http.HttpServletRequest;
5 import javax.servlet.http.HttpServletResponse;
6
7 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
8
9 import de.spring.example.context.UsernameThreadContext;
10
11 public class UsernameHandler extends HandlerInterceptorAdapter {
12         private final UsernameThreadContext usernameThreadContext;
13         
14         @Inject
15         public UsernameHandler(UsernameThreadContext userNameThreadContext) {
16                 this.usernameThreadContext = userNameThreadContext;
17         }
18         
19         @Override
20         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
21                 throws Exception {
22                 final String userName = request.getHeader(UsernameThreadContext.USERNAME_HEADER);
23                 
24                 if (userName != null) {
25                         usernameThreadContext.setUsername(userName);
26                 } else {
27                         usernameThreadContext.clearUsername();
28                 }
29                 
30                 return super.preHandle(request, response, handler);
31         }
32         
33         @Override
34         public void afterCompletion(
35                         HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
36                         throws Exception {
37                 usernameThreadContext.clearUsername();
38         }
39 }