【问题标题】:Validation Spring confusion to render error message验证 Spring 混淆以呈现错误消息
【发布时间】:2013-06-19 14:12:33
【问题描述】:

我尝试呈现错误消息,但它没有出现:

我有验证器:

@Component
class ValidatorFBOSSearch implements Validator {

    @SuppressWarnings("rawtypes")
    @Override
    public boolean supports(Class clazz) {

        return FormBackObjectSearch.class.equals(clazz);
    }

    @Override
    public void validate(Object obj, Errors error) {    

        FormBackObjectSearch fbos = (FormBackObjectSearch)obj;  

        if ("".equals(fbos.particularDate)){            
            error.rejectValue("particularDate", "required.listOfDates", "This field is required");  
        }       
    }
}

它必须检查我在表单支持对象中的字段是否输入了值。 rejectValue 有三个参数。首先 - 在我的支持对象的模型属性中查找一个值,Secong 在属性文件中查找错误消息(我的属性文件位于资源/错误 forlder 中)methos 中的第三个参数表示它是否无法找到错误消息properties 文件将其呈现为默认值,这是我在 servlet-context.xml 中截取的代码

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

这是我为 messageSourse 配置的 xml 配置,用于在 servlet-context.xml 中获取 Validator 的错误:

<!-- Resolves error messages for validator from /Education/src/main/webapp/resources/errors-->
    <beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <beans:property name="basename" value="errors/errormessages"/>
    </beans:bean>

这里是我处理请求的控制器代码:

@RequestMapping(value="/search", method=RequestMethod.GET)
        public void search(Model model) {           
            FormBackObjectSearch fbos = new FormBackObjectSearch();
            model.addAttribute("fbosAttribute", fbos);      
        }


        @RequestMapping(value ="/result", method=RequestMethod.POST)
        public String extract(@RequestParam String nameOfInstitution,
                              @RequestParam String particularDate,
                              @RequestParam String typeOfInstitution,
                              @ModelAttribute("fbosAttribute") FormBackObjectSearch fbos,
                              BindingResult result, RedirectAttributes redirectAttributes, 
                              Model model) throws Exception {

            ValidatorFBOSSearch validatorFBOS = new ValidatorFBOSSearch();
                validatorFBOS.validate(fbos, result);

                if(result.hasErrors()) {
                    redirectAttributes.addFlashAttribute("fbosAttribute", fbos);    
                    return "redirect:/search";


                } else {

                    if(particularDate !="" && nameOfInstitution !="" && typeOfInstitution =="") {                   
                        controllerSupportClass.findWithDateAndName(nameOfInstitution, particularDate, model);                   
                    } else if(particularDate !="" && nameOfInstitution =="" && typeOfInstitution !="") {                    
                        controllerSupportClass.findWithAddedDateAndType(typeOfInstitution, particularDate, model);                  
                    } else if(particularDate !="" && nameOfInstitution =="" && typeOfInstitution ==""){         
                        controllerSupportClass.findWithAddedDate(particularDate, model);    
                    } else if(particularDate !="" && nameOfInstitution !="" && typeOfInstitution !="") {
                        throw new Exception("Search by choose all parameters is not exceptable");   
                    } else {    
                        throw new Exception("You didn't put any search parameters");    
                    }

                }
            return "search";
        }

这是我的 jsp 的平静:

<form:form action="result" method="post" modelAttribute="fbosAttribute" >

<table>

<tr>
<th>Date for extracting:</th> 
<td><form:select  path="particularDate">
<form:option value=""> -Choose date-</form:option>
<form:options items="${listOfDates}"></form:options>
</form:select> <td><form:errors path="particularDate" cssClass="error"/></td>
</td>

</tr>
</table>
</form:form>

问题是我看不到错误消息出现。我尝试使用 Flash 属性在riderect 后出现错误,但没有任何问题。因为我在这里发现,当我使用重定向时,它会删除我的模型和错误并开始新的。但是我如何才能利用闪存属性来解决我的问题。谢谢

【问题讨论】:

  • 你为什么要做重定向(在验证错误时)?
  • 是的,谢谢您的回答。我这样做是因为我希望没有在我的 jsp 中添加日期的返回用户 -> specificDate 再次执行此操作。先生,您有什么建议?
  • 您永远不应该将字符串与==!= 进行比较,而应使用equalsisEmpty(在您的控制器中)
  • 顺便说一句:你应该看看 springs 对 jsr303“bean 验证”的支持。与这种手写验证器相比,其基于注释的方法更易于用于简单验证。

标签: spring jsp spring-mvc attributes controller


【解决方案1】:

要为您需要的特定控制器注册验证器,可以使用 `@InitBimder' 注释。

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

有关如何注册验证器的更多详细信息,请参阅我的回答: Validation in Spring MVC


我认为你的检查语句是错误的:

if ("".equals(fbos.particularDate)){

如果用户不输入任何内容,则字符串不会为空(""),而是null。因此使用:

if (fbos.particularDate == null || fbos.particularDate.isEmpty())

【讨论】:

  • 谢谢先生您的回答。我在返回之前检查了它向我显示的空字符串,例如“”为了确保它是空的,我将 _ 和 _ 放在两者之间,它只是返回 _。这就是我放 if ("".equals(fbos.particularDate)) 的原因。我也考虑过 JSR 303,但有点想实现 Validator 接口看起来非常好,以便将来在复杂的应用程序中使用它。我也尝试了你的建议,我知道这是我的错误,但没有任何改变,我只是想自动知道验证器触发器?我有点困惑。谢谢。
  • @d.a.v.不,验证器仅在它被控制器验证时才会触发 - 请参阅我的扩展答案。 -- 下次尝试像您在上面的评论中那样清楚地表达您的问题。
  • 谢谢。我明白。对不起,如果我让你复杂了
猜你喜欢
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 2017-12-28
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多