2015-01-15 35 views
0

在我的驗證器中,我爲每個字段添加了一些說明,並希望以表單(.jsp)顯示錯誤消息,但是當我顯示每個字段的消息時,錯誤消息是相同的,有什麼問題,我的代碼:如何在窗體中顯示每個字段的錯誤消息?

驗證

public class StoreValidator implements Validator { 

@Override 
public boolean supports(Class<?> clazz) { 
    return Store.class.equals(clazz); 
} 

@Override 
public void validate(Object target, Errors errors) { 
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty", "Name field is empty"); 
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "address.empty", "Address field is empty"); 
} 

}

控制器

@Autowired 
private StoreValidator storeValidator; 

@InitBinder 
protected void initBinder(WebDataBinder binder) { 
    binder.setValidator(storeValidator); 
} 

//post method create store 
@RequestMapping(value = "/regStoreSuccessful", method = RequestMethod.POST) 
public ModelAndView addStorePost(@Valid @ModelAttribute("storeForm") Store storeForm, BindingResult bindingResult, Principal principal, RedirectAttributes redirectAttrs) throws SQLException { 
    ModelAndView modelAndView = new ModelAndView("redirect:body"); 

    storeValidator.validate(storeForm,bindingResult); 

    if(bindingResult.hasErrors()) { 
     redirectAttrs.addFlashAttribute("error", bindingResult.getFieldError().getDefaultMessage()); 
     //modelAndView.addObject("storeForm", bindingResult.getFieldError().getDefaultMessage()); 
    //modelAndView.addObject("storeForm", storeForm); 

    //redirectAttrs.addFlashAttribute("errors", bindingResult.getFieldError().getRejectedValue()); 
     //redirectAttrs.addFlashAttribute("storeForm", storeForm); 

    //.. 
    } 
    //.. 
    } 

<form:form method="POST" action="/regStoreSuccessful" commandName="storeForm"> 
    <table> 
    <tr> 
    <td><form:label path="name">Name store</form:label></td> 
    <td><form:input path="name" /></td> 
    <td><form:errors path="name" /></td> 
    </tr> 
    <tr> 
    <td><form:label path="address">Address store</form:label></td> 
    <td><form:input path="address" /></td> 
    <td><form:errors path="address" /></td> 
    </tr> 
    </form:form> 

而且我試着用<form:errors path = "name" />,但沒有工作... enter image description here

回答

1

你應該hasErrors方法 並分別爲每個輸入添加整個對象模型屬性對每個輸入使用form:errors。

<form:errors path = "name" /> 
<form:errors path = "address" /> 

if(bindingResult.hasErrors()) { 
    model.addAttribute("storeForm",storeForm); 
//.. 
} 
+0

我編輯的代碼(嘗試不同的方法),但不工作,我不明白爲什麼,請看上面的問題的編輯的代碼,有什麼問題嗎?.. – badCoder

+1

只添加modelAndView.addObject (「storeForm」,storeForm);在您的hasErrors中,並返回您在獲取請求時顯示的相同視圖。 – tofindabhishek

相關問題