I am trying to develop a small Spring MVC application where I would like the User object to be initialized from the beginning of each session.
I have a User class
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyUser implements User {
public void fillByName(String username) {
userDao.select(username);
}
}
And I want to initialize the MyUser object once Spring Security recognizes the user in the Interceptor class (Btw, is this a good practice?)
public class AppInterceptor extends HandlerInterceptorAdapter {
@Autowired
MyUser user;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
user.fillByName(auth.getName());
}
return true;
}
}
So, when the Controller processes the request, there is already an initialized User Session class. But when I try to serialize the MyUser object with Jackson, it just doesn't work:
@RequestMapping("/")
public String launchApp(ModelMap model) {
ObjectMapper mapper = new ObjectMapper();
try {
System.out.println(user.getUsername());
model.addAttribute("user", mapper.writeValueAsString(user));
} catch (JsonProcessingException e) {
}
return "app/base";
}
As you can see, MyUser object objects work well with the Controller class, but Jackson does not.
When I remove the @Scope annotation from the User object, Jackson serialization will start working.
Obviously the area with the bean proxy and singleton Controller is a problem
But how can I fix this?
-
, , :)
, ? MyUser ? ?