0

Is using the ModelAndView in this manner "thread-safe"? The UserToken bean passed on the constructor is session-scoped and proxied, so each user should be accessing their own token, right? Or is using the same ModelAndView for all requests overwriting the UserToken each time for every user, thus possibly causing user A to see user B's token?

@Controller
public class ViewController {
    private final UserToken userToken;
    private final ModelAndView mav;

    @Value("${redirect.url}")
    String redirectUrl;

    @Autowired 
    public ViewController(UserToken userToken) {
        this.userToken = userToken;
        this.mav = new ModelAndView();
    }

    @RequestMapping("/")
    public ModelAndView defaultView() {
        return getModelAndView("home");
    }

    @RequestMapping("/entryPoint")
    public ModelAndView accessDenied(@RequestParam(required=false) String token) {
        userToken.deserialize(token);
        mav.addObject("userToken", userToken);
        return getModelAndView("redirect:/");
    }

    /**
     * Handle redirect if the userToken is invalid
     * @param viewName The view to map
     * @return the ModelAndView
     */
    private ModelAndView getModelAndView(String viewName) {
        if (userToken.isValid()) {
            mav.setViewName(viewName);
        } else {
            mav.setViewName("redirect:" + redirectUrl);
        }
        return mav;
    }

}

Not even sure how to test for thread-safety in this scenario, so any insight would be appreciated (techniques, tools, etc.).

rayduels
  • 83
  • 1
  • 5
  • 1
    Why do you reuse the `ModelAndView`, just create a new, you can also just add it as an argument to the `RequestMapping`-Method. Also what happens when a user access a resource at the same time twice, I assume your UserToken is basically immutable, so it should be fine, if it isn't this will also break. – dav1d Feb 10 '17 at 21:40
  • Reusing it simplifies the code. I understand there are other ways to do this as you've suggested and, for example, using "@ControllerAdvice" or adding "@ModelAttribute" to a method in the controller , but is the way I wrote it here "safe" since the UserToken is session-scoped and proxied (and it is basically immutable)? – rayduels Feb 14 '17 at 16:36
  • But the `ModelAndView` is not session scoped... – dav1d Feb 16 '17 at 11:54
  • Right, the controller is a singleton, but the UserToken is session-scoped due to Spring's proxy mechanism, so I think it should be safe. Thanks anyway, I changed my approach to use '@ModelAttribute' on a method in the controller. – rayduels Feb 17 '17 at 09:13

0 Answers0