先贴问题代码
@Controller
@RequestMapping("/Admin")
public class AdminController {
@Autowired
private AdminService adminService;
ModelAndView modelAndView = new ModelAndView();
LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
@RequestMapping("/loginUI")
public String AdminLoginUI() {
return "adminlogin";
}
@RequestMapping("/login")
public ModelAndView AdminLogin(@Param("username") String username, @Param("password") String password) {
lqw.eq(Admin::getUsername, username)
.eq(Admin::getPassword, password)
.select(Admin::getUsername, Admin::getPassword);
if (Utils.isNotnull(adminService.getOne(lqw))) {
modelAndView.setViewName("adminhome");
modelAndView.addObject("adminInfo", adminService.list());
} else {
modelAndView.addObject("msg", "密码输入错误");
modelAndView.setViewName("redirect:/Admin/loginUI");
}
return modelAndView;
}
}
以为Wrapper用法和ModelAndView一样,写在类里就ok的,实际并不是,这么写经过多次调用后, LambdaQueryWrapper后的条件会一直追加(虽然不会报错),SQL语句越来越长,只要有一次账密输入错误,之后的判断条件一直为false,导致无法登录,就像下面这样:
username和password会一直追加,正确的写法应该将Wrapper写到方法内部,而不是类的内部,就像这样:
@Controller
@RequestMapping("/Admin")
public class AdminController {
@Autowired
private AdminService adminService;
ModelAndView modelAndView = new ModelAndView();
@RequestMapping("/loginUI")
public String AdminLoginUI() {
return "adminlogin";
}
@RequestMapping("/login")
public ModelAndView AdminLogin(@Param("username") String username, @Param("password") String password) {
LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
lqw.eq(Admin::getUsername, username)
.eq(Admin::getPassword, password)
.select(Admin::getUsername, Admin::getPassword);
if (Utils.isNotnull(adminService.getOne(lqw))) {
modelAndView.setViewName("adminhome");
modelAndView.addObject("adminInfo", adminService.list());
} else {
modelAndView.addObject("msg", "密码输入错误");
modelAndView.setViewName("redirect:/Admin/loginUI");
}
return modelAndView;
}
}
这样就好啦,再试一遍
问题解决了,但是为什么会这样还是不明白,求大佬指点。