首先描述一下出现错误的情景:
我刚学springmvc,想做一个登录界面的东西。然后试着写了一个controller如下:
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login( String name,
String password, Model model) {
User u = userService.login(name, password);
if (u == null)
throw new UserException("no user exist!");
if (!u.getPassword().equals(password)) {
throw new UserException("password is not right!");
}
model.addAttribute("loginUser", u);
return "redirect:/user/users";
}
然后就出现了 400 badrequest这个错误了。网上找资料,说是属性不匹配吧,于是找jsp页面的错误,没有不匹配的地方,于是添加
log4j.logger.org.springframework.web=debug
到log4j日志里面,果然出现错误的地方了。究其原因是
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String show(@PathVariable int id, Model model) {
model.addAttribute("user", userService.load(id));
return "user/show";
}
因为这个mapping地址localhost:8080/xxx/user/id(int类型)的,
login的mapping地址localhost:8080/xxx/user/login(String类型)的,
所以在dispatch的时候,spring误认为是要去访问show这个方法,就造成了数据类型不匹配,也就是String型无法转变为int类型的错误,也就造成了400 bad request错误了,如此,解决方法就是在show方法的
@Request