@RestController
@RequestMapping
(
"/users"
)
public
class
UserController
{
@Autowired
private
UserDao
userDao
;
/**
* 查询所有用户
*
* @param model
* @return
*/
@GetMapping
public
ModelAndView
list
(
Model
model
)
{
model
.
addAttribute
(
"userList"
,
userDao
.
listUsers
());
model
.
addAttribute
(
"title"
,
"用户管理"
);
return
new
ModelAndView
(
"user/list"
,
"userModel"
,
model
);
}
/**
* 根据id查询用户
*
* @param id
* @param model
* @return
*/
@GetMapping
(
"{id}"
)
public
ModelAndView
view
(
@PathVariable
(
"id"
)
Long
id
,
Model
model
)
{
User
user
=
userDao
.
getUserById
(
id
);
model
.
addAttribute
(
"user"
,
user
);
model
.
addAttribute
(
"title"
,
"查看用户"
);
return
new
ModelAndView
(
"user/view"
,
"userModel"
,
model
);
}
/**
* 获取创建表单页面
*
* @param model
* @return
*/
@GetMapping
(
"/form"
)
public
ModelAndView
createForm
(
Model
model
)
{
model
.
addAttribute
(
"user"
,
new
User
());
model
.
addAttribute
(
"title"
,
"创建用户"
);
return
new
ModelAndView
(
"user/form"
,
"userModel"
,
model
);
}
/**
* 保存或更新用户
*
* @param user
* @return
*/
@PostMapping
public
ModelAndView
saveOrUpdateUser
(
User
user
)
{
user
=
userDao
.
saveOrUpdateUser
(
user
);
return
new
ModelAndView
(
"redirect:/users"
);
}
/**
* 删除用户
*
* @param id
* @return
*/
@GetMapping
(
"/delete/{id}"
)
public
ModelAndView
delete
(
@PathVariable
(
"id"
)
Long
id
)
{
userDao
.
deleteUser
(
id
);
return
new
ModelAndView
(
"redirect:/users"
);
// 重定向到list页面
}
/**
* 获取修改用户的界面
*
* @param id
* @param model
* @return
*/
@GetMapping
(
"/modify/{id}"
)
public
ModelAndView
modify
(
@PathVariable
(
"id"
)
Long
id
,
Model
model
)
{
User
user
=
userDao
.
getUserById
(
id
);
model
.
addAttribute
(
"user"
,
user
);
model
.
addAttribute
(
"title"
,
"修改用户"
);
return
new
ModelAndView
(
"user/form"
,
"userModel"
,
model
);
}
} |