本文介绍了Spring - 禁用绑定异常(对于特定属性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Web应用程序中,我正在使用Spring 2.5.6.SEC01,我本质上有一个整型字段,它需要一个数字来确定要滚动到哪个页面。要求已更改,我们不再需要显示错误消息,但如果输入无效的数字,只要忽略该用户的输入即可,adfadf。



我是阅读您可以通过以下方式进行:



TypeMismatch.property =一些新的错误消息



然而,尝试,我们仍然得到原始的错误消息:
java.lang.Integer.TypeMismatch = ...



我只想禁用此消息给定的财产。我怎样才能做到这一点?我仍然希望绑定自动发生,我现在不想听到。



Walter

解决方案

根据



如果代码typeMismatch,对象名称user,字段age




  • typeMismatch.user.age

  • typeMismatch.age

  • typeMismatch.int

  • typeMismatch



所以你应该得到(我想你的命令名称叫做 em>并且您的财产是 age )根据您的代码修改

  typeMismatch.command.age 
typeMismatch.age
typeMismatch.java.lang.Integer
typeMismatch

注意第三个代码

  typeMismatch.java.lang.Integer 

它会解决你想要的



更新



我创建了一个Person命令类

  public class Person implements Serializable {

private Integer age;

public Integer getAge(){
return age;
}

public void setAge(Integer age){
this.age = age;
}

}

一个人控制器

  public class PersonController extends SimpleFormController {

public PersonController(){
setCommandClass(Person.class) ;
setValidator(new Validator(){
public boolean supports(Class clazz){
return clazz.isAssignableFrom(Person.class);
}

public void validate(Object command,Errors errors){
rejectIfEmpty(errors,age,Age is required);
}
});
}

@Override
protected ModelAndView onSubmit(Object command)throws异常{
返回新的ModelAndView();
}

}

这里是myMessages.properties根路径)

  typeMismatch.command.age = typeMismatch.command.age 
typeMismatch.age = typeMismatch。 age
typeMismatch.java.lang.Integer = typeMismatch.java.lang.Integer
typeMismatch = typeMismatch

所以,我做了以下测试

  public class PersonControllerTest {

私人PersonController personController;
私人MockHttpServletRequest请求;

私人MessageSource messageSource;

@Before
public void setUp(){
request = new MockHttpServletRequest();
request.setMethod(POST);

personController = new PersonController();

messageSource = new ResourceBundleMessageSource();
((ResourceBundleMessageSource)messageSource).setBasename(myMessages);
}

@Test
public void failureSubmission()throws异常{
/ **
* Ops ...一个bindException
*
*年龄不能是纯粹的字符串,它必须是一个纯整数
* /
request.addParameter(age,不是有意义的年龄);

ModelAndView mav = personController.handleRequest(request,new MockHttpServletResponse());

BindingResult bindException =(BindingResult)mav.getModel()。get(BindingResult.MODEL_KEY_PREFIX +command);
for(Object object:bindException.getAllErrors()){
if(object instanceof FieldError){
FieldError fieldError =(FieldError)object;

assertEquals(fieldError.getField(),age);

/ **
*输出typeMismatch.command.age
* /
System.out.println(messageSource.getMessage((FieldError)object,null)) ;
}
}
}

}

如果你想要第二个,你必须摆脱 typeMismatch.command.age关键资源束

  typeMismatch.age = typeMismatch.age 
typeMismatch.java.lang.Integer = typeMismatch.java.lang.Integer
typeMismatch = typeMismatch

或编写自己的MessageCodesResolver实现

  public class MyCustomMessageCodesResolver实现MessageCodesResolver {

private DefaultMessageCodesResolver defaultMessageCodesResolver = new DefaultMessageCodesResolver();

public String [] resolveMessageCodes(String errorCode,String objectName){
if(errorCode.equals(age))
/ **
*设置你的自定义消息就在这里
* /
return new String [] {typeMismatch.age};

返回defaultMessageCodesResolver.resolveMessageCodes(String errorCode,String objectName);
}

public void String [] resolveMessageCodes(String errorCode,String objectName,String field,Class fieldType){
if(errorCode.equals(age))
/ **
*在这里设置你的自定义消息
* /
return new String [] {typeMismatch.age};

return defaultMessageCodesResolver.resolveMessageCodes(String errorCode,String objectName,String field,Class fieldType);
}
}

并设置您的PersonController

  public class PersonController extends SimpleFormController {

public PersonController(){
setMessageCodesResolver(new MyCustomMessageCodesResolver());
setCommandClass(Person.class);
setValidator(new Validator(){
public boolean supports(Class clazz){
return clazz.isAssignableFrom(Person.class);
}

public void validate(Object command,Errors errors){
rejectIfEmpty(errors,age,Age is required);
}
});
}


In a web application I'm working on using Spring 2.5.6.SEC01, I essentially have an Integer field that takes a number to determine which page to scroll to. The requirements changed, and we no longer want to display an error message, but simply ignore the user's input if they enter an invalid number, say "adfadf".

I was reading that you can do that via:

TypeMismatch.property=Some New Error Message

However, after having tried that, we are still getting the original error message:java.lang.Integer.TypeMismatch=...

I only want to disable this message for that given property. How can I do that? I still want binding to occur automatically, I just don't want to hear about it now.

Walter

解决方案

According to DefaultMessageCodesResolver

In case of code "typeMismatch", object name "user", field "age"

  • typeMismatch.user.age
  • typeMismatch.age
  • typeMismatch.int
  • typeMismatch

So you should get (I suppose your commandName is called command and your property is age) Adapt according to your code

typeMismatch.command.age
typeMismatch.age
typeMismatch.java.lang.Integer
typeMismatch

Notice The third code

typeMismatch.java.lang.Integer

It will solve what you want

UPDATE

I have created a Person command class

public class Person implements Serializable {

    private Integer age;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

And a person controller

public class PersonController extends SimpleFormController {

    public PersonController() {
        setCommandClass(Person.class);
        setValidator(new Validator() {
            public boolean supports(Class clazz) {
                return clazz.isAssignableFrom(Person.class);
            }

            public void validate(Object command, Errors errors) {
                rejectIfEmpty(errors, "age", "Age is required");
            }
        });
    }

    @Override
    protected ModelAndView onSubmit(Object command) throws Exception {
        return new ModelAndView();
    }

}    

Here goes my myMessages.properties (root of the classpath)

typeMismatch.command.age=typeMismatch.command.age
typeMismatch.age=typeMismatch.age
typeMismatch.java.lang.Integer=typeMismatch.java.lang.Integer
typeMismatch=typeMismatch

So, i have done the following test

public class PersonControllerTest {

    private PersonController personController;
    private MockHttpServletRequest request;

    private MessageSource messageSource;

    @Before
    public void setUp() {
        request = new MockHttpServletRequest();
        request.setMethod("POST");

        personController = new PersonController();

        messageSource = new ResourceBundleMessageSource();
        ((ResourceBundleMessageSource) messageSource).setBasename("myMessages");
    }

    @Test
    public void failureSubmission() throws Exception {
        /**
         * Ops... a bindException
         * 
         * Age can not be a plain String, It must be a plain Integer
         */
        request.addParameter("age", "not a meaningful age");

        ModelAndView mav = personController.handleRequest(request, new MockHttpServletResponse());

        BindingResult bindException = (BindingResult) mav.getModel().get(BindingResult.MODEL_KEY_PREFIX + "command");
        for (Object object : bindException.getAllErrors()) {
            if(object instanceof FieldError) {
                FieldError fieldError = (FieldError) object;

                assertEquals(fieldError.getField(), "age");

                /**
                  * outputs typeMismatch.command.age
                  */
                System.out.println(messageSource.getMessage((FieldError) object, null));
            }
        }
    }

}

If you want the second one, you must get rid of typeMismatch.command.age key resource bundle

typeMismatch.age=typeMismatch.age
typeMismatch.java.lang.Integer=typeMismatch.java.lang.Integer
typeMismatch=typeMismatch

Or write your own implementation of MessageCodesResolver

public class MyCustomMessageCodesResolver implements MessageCodesResolver {

    private DefaultMessageCodesResolver defaultMessageCodesResolver = new DefaultMessageCodesResolver();

    public String [] resolveMessageCodes(String errorCode, String objectName) {
        if(errorCode.equals("age"))
            /**
              * Set up your custom message right here
              */
            return new String[] {"typeMismatch.age"};

        return defaultMessageCodesResolver.resolveMessageCodes(String errorCode, String objectName);
    }

    public void String[] resolveMessageCodes(String errorCode, String objectName, String field, Class fieldType) {
        if(errorCode.equals("age"))
            /**
              * Set up your custom message right here
              */
            return new String[] {"typeMismatch.age"};

        return defaultMessageCodesResolver.resolveMessageCodes(String errorCode, String objectName, String field, Class fieldType);
    }
}

And set up your PersonController

public class PersonController extends SimpleFormController {

    public PersonController() {
        setMessageCodesResolver(new MyCustomMessageCodesResolver());
        setCommandClass(Person.class);
        setValidator(new Validator() {
            public boolean supports(Class clazz) {
                return clazz.isAssignableFrom(Person.class);
            }

            public void validate(Object command, Errors errors) {
                rejectIfEmpty(errors, "age", "Age is required");
            }
        });
    }

这篇关于Spring - 禁用绑定异常(对于特定属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 12:22