If you just want to print the username on the pages, you might like this solution. It is free from object casting and works without Spring Security too:
@RequestMapping(value = "/index.html", method = RequestMethod.GET) public ModelAndView indexView(HttpServletRequest request) { ModelAndView mv = new ModelAndView("index"); String userName = "not logged in"; // Any default user name Principal principal = request.getUserPrincipal(); if (principal != null) { userName = principal.getName(); } mv.addObject("username", userName); // By adding a little code (same way) you can check if user has any // roles you need, for example: boolean fAdmin = request.isUserInRole("ROLE_ADMIN"); mv.addObject("isAdmin", fAdmin); return mv; }
Note. Added parameter HttpServletRequest request .
This works fine because Spring introduces its own objects (wrappers) for HttpServletRequest, Principal, etc., so you can use standard java methods to retrieve user information.
L'sync Jul 25 2018-12-12T00: 00Z
source share