How to provide a message of my choosing on form va

2020-07-22 16:56发布

问题:

I am using spring mvc 3.0.Here is my controller class:

    @Controller
@RequestMapping("/author")
public class AuthorController {
    @Autowired
    private IAuthorDao authorDao;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                dateFormat, true));
    }

    @RequestMapping(method = RequestMethod.GET)
    public String get(Model model) {
        return "author-list";
    }

    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute("author", new Author());
        return "author-form";
    }

    @RequestMapping(value = "/new", method = RequestMethod.POST)
    public String createPost(@ModelAttribute("author") Author author,
            BindingResult result) {
        new AuthorValidator().validate(author, result);
        if (result.hasErrors()) {
            return "author-form";
        } else {
            authorDao.persist(author);
            return "redirect:/author/" + author.getId();
        }
    }

    @RequestMapping(value = "/{authorId}", method = RequestMethod.GET)
    public String view(@PathVariable("authorId") int authorId) {
        return "author-view";
    }
}

I am trying to validate author object. it has dob attr which type is Date.

I am using following class for validation:

    public class AuthorValidator {
    public void validate(Author author, Errors errors) {

        if(author.getfName()==null)
            errors.rejectValue("fName", "required", "required");
        else if (!StringUtils.hasLength(author.getfName())) {
            errors.rejectValue("fName", "required", "required");
        }

        if(author.getfName()==null)
            errors.rejectValue("lName", "required", "required");
        else if (!StringUtils.hasLength(author.getlName())) {
            errors.rejectValue("lName", "required", "required");
        }

        if(author.getDob()==null)
            errors.rejectValue("dob", "required", "required");
        else if (!StringUtils.hasLength(author.getDob().toString())) {
            errors.rejectValue("dob", "required", "required");
        }
    }
}

when i do no enter anything to the form it gives required message, it is correct, but when i give the incorrect format then it gives writes Failed to convert property value of type java.lang.String to required type java.util.Date for property dob; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "asdads" required as a message. how to make it like "Invalid date".

thanks.

回答1:

If you use standard Spring facilities, all you need to do is:

Add messageSource:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="com.example.messages" />
</bean>

Add properties file com/example/messages.properties containing one of:

typeMismatch.author.date = Invalid date
typeMismatch.date = Invalid date
typeMismatch.java.util.Date = Invalid date
typeMismatch = Invalid date

first lets you configure error message for particular field (date) in particular command object (author), second - a date field in any command object, third - a message for binding error of a field of java.util.Date class, and the final - a general message for an error resulting from any conversion.

Here's my JSP page:

<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
   <sf:form commandName="author">
      <sf:errors path="date"  /><br />
      <sf:input path="name"/><br />
      <sf:input path="date"/><br />
      <input type="submit" value="ok" />
   </sf:form>
</body>
</html>