2017-04-25 119 views
0

我將Struts 1.3項目轉換爲Spring。而不是struts表單域,我使用的是spring表單。在DAO驗證後,Spring-MVC表單驗證突出顯示輸入字段

我在struts中使用ActionErrors來使用errorStyleClass屬性突出顯示該字段。

同樣,在春季cssErrorClass可用。但是,如何在dao驗證後使用它?

@RequestMapping(value = "/login", method = RequestMethod.POST) 
public String login(@ModelAttribute("login") @Validated Login login, BindingResult result, Model model) { 

    if (result.hasErrors()) { 

     //THIS VALIDATION DONE BY ANNOTATION AND HIGHLIGHTING THE FIELD 
     //USING "cssErrorClass" 

     return HOMEPAGE; 
    } 

    boolean checkAuthentication = authService.checkAuthentication(login); 

    if(!checkAuthentication){ 

     // HOW TO SET THE ERROR HERE? 

     // Is there any way to set the error like 

     // error.setMessage("userId","invalid.data"); 

     // so that, is it possible to display error message by 
     // highlighting the fields using "cssErrorClass"? 

    } 


    return HOMEPAGE; 
} 
+0

你看這個問題:HTTP ://stackoverflow.com/questions/4013378/spring-mvc-and-jsr-303-hibernate-conditional-validation RQ = 1? –

+0

是的。我見過這個例子。但是,它表示,沒有定義驗證方法。如果要創建驗證方法,那裏面的實現應該是什麼? – Shakthi

回答

0

你需要註釋使用Java Bean驗證框架JSR 303您的實體,這樣

public class Model{ 
    @NotEmpty 
    String filed1; 

    @Range(min = 1, max = 150) 
    int filed2; 

    .... 
} 

並添加@Valid到控制器,這樣

public class MyController { 

public String controllerMethod(@Valid Customer customer, BindingResult result) { 
    if (result.hasErrors()) { 
     // process error 
    } else { 
     // process without errors 
    } 
} 

你可以找到更多的例子因爲它herehere

編輯:

如果您想基於代碼自定義的驗證步驟來註冊更多的錯誤,你可以使用rejectValue()方法在BindingResult情況下,像這樣:

bindingResult.rejectValue("usernameField", "error code", "Not Found username message"); 
+0

嗨。我的問題是,在其他部分,我有dao調用並驗證數據庫中的登錄證書。如果細節不正確,你將如何實現相同的場景,比如else部分中的result.hasErrors()(在db調用之後)? – Shakthi

+0

@Shakthi,我已經更新了我的答案,請檢查 – fujy

+0

嗨朋友。 'result.rejectValue(「usernameField」,「error code」,「Not Found username message」);'工作正常。 – Shakthi