vendredi 20 mars 2015

Passing from @ControllerAdvice to @Controller in Spring MVC

I want to check if user exists in ControllerAdvice and treat user as @ModelAttribute if user exists. On the other hand, I also want to access user object in @Controller directly. So I add @ModelAttribute annotation on the parameter of @RequestMapping method.


I'm using @ControllerAdvice like:



@ControllerAdvice
public class UserAdvice {

@Autowired
private UserService userService;

@ModelAttribute("user")
public User user(@PathVariable("username") String username) {
User user = userService.findByUsername(username);
if (user != null) {
return user;
}
user = userService.findById(username);
if (user == null) {
throw new ResourceNotFoundException("user not found");
}

return user;
}
}


And UserController Like:



@RestController
@RequestMapping("/users/{username}")
public class UserController {

public static final Logger logger = LoggerFactory.getLogger(UserCourseListController.class);

@Autowired
private CourseService courseService;

@RequestMapping(value = "", method = RequestMethod.GET)
public void getUser(@ModelAttribute("user") User user, Model model) {
logger.info("{}", user);//user is null
logger.info("{}", model.asMap().get("user"));// not null
}

}


But now, the parameter user that annotated with @ModelAttribute is null while there is a "user" obj in Model Map.


Is there any mistakes I've made in this scenario? Or any misunderstanding of the concepts of @ModelAttribute and @ControllerAdvice?


Thanks very much!


Aucun commentaire:

Enregistrer un commentaire