You are creating your own instances of UsernameService:
Code:
UsernameService u = new UsernameService();
and
Code:
UsernameService us = new UsernameService();
The bean instance from which you are trying to get the username is not the same one on which you set the username.
If you want Spring to manage the lifetime of bean instances, you will have to obtain the instances through the Spring IoC container. For example:
Code:
@Controller
@RequestMapping("/login")
public class LoginController {
@Autowired
UsernameService service;
@RequestMapping(method = RequestMethod.POST)
public void submit(@RequestParam String username, @RequestParam String password) {
this.service.setUsername(username);
}
}
@Controller
@RequestMapping("/home")
public class HomeController {
@Autowired
UsernameService service;
public ModelAndView home() {
return new ModelAndView("home", new ModelMap("username", this.service.getUsername()));
}
}