2016-06-08 190 views
0

我想驗證包含電子郵件的Spring Bean,但當請求Bean中的電子郵件以空字符串形式出現時,驗證程序和BindingResult都不會顯示任何錯誤。 請參閱下面的代碼:爲什麼Spring BindingResult或驗證器不顯示任何錯誤?

豆:

import org.springframework.context.annotation.Scope; 
import org.springframework.stereotype.Component; 
import org.springmodules.validation.bean.conf.loader.annotation.handler.Email; 
import org.springmodules.validation.bean.conf.loader.annotation.handler.NotEmpty; 

@Component("grouponRedemptionFormBean") 
@Scope("prototype") 
public class GrouponRedemptionBean { 

@NotEmpty(message = "Please enter your email addresss.") 
@Email(message = "Please correct your email.") 
private String email; 
    … 
} 

控制器:

import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.validation.Valid; 

import org.apache.log4j.Logger; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Qualifier; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.validation.BeanPropertyBindingResult; 
import org.springframework.validation.BindingResult; 
import org.springframework.validation.Errors; 
import org.springframework.validation.Validator; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 


@Controller 
public class GrouponVoucherRedemptionController { 

@Autowired 
@Qualifier("defaultBeanValidator") 
private Validator validator; 

@RequestMapping(value="/groupon-redemption.ep", method=RequestMethod.POST) 
public String PostGrouponRedemption(@Valid @ModelAttribute GrouponRedemptionBean grouponRedemptionBean, BindingResult bindingResult, 
HttpServletRequest request, HttpServletResponse response, Model model){ 

    Errors errors = new BeanPropertyBindingResult(grouponRedemptionBean, "grouponRedemptionFormBean"); 
    validator.validate(grouponRedemptionBean, errors); 
    if(errors.hasErrors()) { 
     bindingResult.addAllErrors(errors); 
    } 
    if (bindingResult.hasErrors()) { 
     return GROUPON_REDEMPTION_VIEW; 
    }  
... 

XML配置:

<mvc:annotation-driven /> 

回答

2

你有錯誤的參數順序 - BindingResult必須立即模型對象(GrouponRedemptionBean在你的情況)。見documentation

ErrorsBindingResult參數必須遵循被立即綁定方法簽名可能有不止一個模型對象和Spring會爲他們每個人創建一個單獨的BindingResult實例,這樣的模型對象以下示例將不起作用:

BindingResult和@ModelAttribute的無效排序。

@RequestMapping(method = RequestMethod.POST) 
public String processSubmit(@ModelAttribute("pet") Pet pet, Model model, BindingResult result) { ... } 

注意,有在PetBindingResult之間的Model參數。爲了得到這個工作,你必須重新排序參數如下:

@RequestMapping(method = RequestMethod.POST) 
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, Model model) { ... } 
+1

我改變BindingResult的位置,並添加驗證 - 結果是一樣的 –

+0

做任何其他項目中的工作驗證? – Roman

+0

你是什麼意思? –

相關問題