Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java spring framework form validation

I am using spring framework 3.0.5.

I have a form:

<form:form method="POST" modelAttribute="postedEntry">
    Category: <form:select path="category" items="${menus}" itemValue="id" itemLabel="menuName"/><form:errors path="category"/>
    <br/>Title: <form:input path="title"/><form:errors path="title"/>
    <br/>Short Description: <form:textarea path="shortDesc"/><form:errors path="shortDesc"/>
    <br/>Body: <form:textarea path="body"/><form:errors path="body"/>
    <br/><input type="submit" value="POST IT!11"/>
</form:form>

And a domain class Entry:

public class Entry {
    private int id;
    private int category;
    private String title;
    private String shortDesc;
    private String body;
    private Date date;
//getters and setters
}

And a controller:

@RequestMapping(value="/entryPost",method=RequestMethod.POST)
public String entryPost(@ModelAttribute("postedEntry") Entry entry,BindingResult result){
    entryValidator.validate(entry, result);
    if(result.hasErrors()){
        return "entryPost";
    }else{
        rusService.postEntry(entry);
        return "redirect:entryPost";
    }
}

And in my service object:

public void postEntry(final Entry entry){
    String sql = "INSERT INTO entries (category,title,shortDesc,body,date) VALUES(?,?,?,?,?)";
    jdbcTemplate.update(sql,new Object[]{entry.getCategory(),entry.getTitle(),entry.getShortDesc(),entry.getBody(),entry.getDate()});
}

And a validator:

public class EntryValidator implements Validator{
    public boolean supports(Class clazz){
        return Entry.class.isAssignableFrom(clazz);
    }
    public void validate(Object target,Errors errors){
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "category", "required.category","Category is required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "required.title", "Title is required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shortDesc","required.shortDesc", "Short description is required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "body", "required.body", "Body is required!");
        Entry entry = (Entry) target;
        entry.setDate(new Date());
    }
}

If somebody sends the string value of a category, not integer, it will type near the form: Failed to convert property value of type java.lang.String to required type int for property category; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "h" from type java.lang.String to type int; nested exception is java.lang.NumberFormatException: For input string: "h"

But I don't want that it typed this. How can I somehow validate this value and throw my own message? I tried to check it in my validator by adding:

int cat = entry.getCatrgory();
if(cat.equals("0"))
    errors.reject("invalid.category","The category is invalid!");

But it didn't work - it still threw ConversionFailedException exception.

like image 337
Tw1sty Avatar asked Jan 19 '23 04:01

Tw1sty


2 Answers

You can use typemismatch key in your resource bundle.

Example:

typeMismatch = This is not a number!
like image 142
Alfredo Osorio Avatar answered Jan 21 '23 19:01

Alfredo Osorio


You need to declare a message source for error messages. Then you can specify messages for type mismatch errors in it, as follows: JSR-303 Type Checking Before Binding (other error messages can be specified there as well).

like image 30
axtavt Avatar answered Jan 21 '23 19:01

axtavt