我試圖將表單驗證添加到工作應用程序。我開始在登錄表單中添加一個NotNull檢查。我正在使用Bean Validation API的Hibernate impl。Spring MVC表單驗證 - 客戶端發送的請求在語法上不正確
這裏是我寫
代碼@Controller
@RequestMapping(value="/login")
@Scope("request")
public class LoginController {
@Autowired
private CommonService commonService;
@Autowired
private SiteUser siteUser;
@InitBinder
private void dateBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
binder.registerCustomEditor(Date.class, editor);
}
@ModelAttribute
protected ModelMap setupForm(ModelMap modelMap) {
modelMap.addAttribute("siteUser", siteUser);
return modelMap;
}
@RequestMapping(value="/form", method = RequestMethod.GET)
public ModelAndView form(ModelMap map){
if (siteUser.getId() == null){
map.addAttribute("command",new SiteUser());
return new ModelAndView("login-form",map);
}else {
return new ModelAndView("redirect:/my-dashboard/"+siteUser.getId());
}
}
@RequestMapping(value="/submit", method=RequestMethod.POST)
public ModelAndView submit(@Valid SiteUser user, ModelMap map, BindingResult result){
if (result.hasErrors()) {
map.addAttribute("command", user);
System.out.println("Login Error block");
return new ModelAndView("login/form",map);
}
else {
User loggedInUser = commonService.login(user.getEmail(), user.getPassword());
if (loggedInUser != null) {
siteUser.setId(loggedInUser.getId());
siteUser.setName(loggedInUser.getName());
System.out.println("site user attr set");
}
return new ModelAndView("redirect:/my-dashboard/"+loggedInUser.getId());
}
}
}
該模型是
@Component
@Scope("session")
public class SiteUser {
private Integer id = null;
@NotNull
private String name = null;
private String email = null;
private String password = null;
private List<String> displayPrivList = null;
private List<String> functionPrivList = null;
// And the getters and setters
}
的JSP是
<c:url var="loginSubmitUrl" value="/login/submit"/>
<form:form method="POST" action="${loginSubmitUrl}">
<form:errors path="*" />
<div class="row">
<div class="span4">
</div>
<div class="span4">
<h3>Please Login</h3>
<label><span style="color:red">*</span>Email</Label><form:input path="email" type="text" class="input-medium" />
<label><span style="color:red">*</span>Password</Label><form:input path="password" type="password" class="input-medium" />
<br/>
<button type="submit" class="btn btn-primary">Login</button>
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form:form>
我已經加入messages.properties和註釋驅動Bean在高清上下文xml。 關於這個問題的其他答案談論表單域沒有發佈。就我而言,這是預期的行爲 - 如果我提交一個空白表單,我應該會得到一個錯誤。
請指教我錯過了什麼?
發佈的日誌信息將幫助..一般春季報告所有這些種類的錯誤在一個非常詳細的方式參數後直接把BindingResult結果參數始終。 –
在這種情況下,沒有日誌消息。即使「登錄錯誤塊」系統輸出也不打印。有趣的是,如果我從方法簽名中刪除了「ModelMap map」參數,代碼將進入錯誤塊,但隨後顯示「Neither BindingResult和普通目標對象的bean名稱」命令'可作爲請求屬性「 –
我不確定但是,將@ModelAttribute與Valid一起添加到您的命令對象中,然後嘗試使用 –