SpringBoot中重定向时,采用Model向前台传递数据时会失败,正确的做法是使用RedirectAttributes。
示例:
@RestController
@RequestMapping("/admin")
public class UserController {
@Resource
private UserService userService;
/**
* 打开后台管理员登录页面
* @return
*/
@GetMapping("/showLogin")
public String showLogin() {
return "admin/login";
}
@PostMapping("/login/{username}/{password}")
public String lgoin(@PathVariable("username") String username, @PathVariable("password")String password,
HttpSession session, RedirectAttributes attributes){
User user = userService.login(username, password);
if(user != null){
user.setPassword(null);
session.setAttribute("user",user);
return "admin/index";
} else {
attributes.addFlashAttribute("msg","用户名或密码错误");
return "redirect:/admin/showLogin"; //重定向
}
}
}