@Controller
@RequestMapping("/user")
public class UserController {
private UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
* @param username
* @return 根据user从持久层获取用户信息, username==null则返回一个新的user对象,否则从持久层加载User的信息
*/
@ModelAttribute("user")
public User loadModel(@RequestParam(value = "username", required = false) String username) {
return username == null ? createUser() : userRepository.loadUserByUsername(username);
}
/**
* @return 当username未提供时, 将返回一个新的User对象,
* 因为模型在调用了{@link UserController#loadModel} 方法之后,
* {@link org.springframework.web.method.annotation.ModelAttributeMethodProcessor}不会再为{@link UserController#save(com.feexon.domain.User)}方法创建User实例
*/
private User createUser() {
return new User();
}
/**
* 设置@ModelAttribute("user")绑定的属性,其他属性将被忽略
*
* @param binder
*/
@InitBinder("user")
public void setBindingProperties(DataBinder binder) {
binder.setAllowedFields("password");
}
@RequestMapping("/save")
@ResponseBody
public User save(@ModelAttribute("user") User user) {
if (hasRegistered(user)) {
userRepository.saveUser(user);
}
return user;
}
/**
* 当user未注册时,{@link UserController#loadModel(java.lang.String)}返回的值为null.
*
* @param user
* @return
*/
private boolean hasRegistered(User user) {
return user != null;
}
}