How to properly setup the validation with Spring MVC4 and Hibernate Validator?

时间:2017-04-10 01:34:49

标签: java spring-mvc hibernate-validator

I am learning Spring MVC and attempting to add validation to my controller based on the constraints I set for the model. When I am using the @Range(min=1, max=100) constraint, as long as I type in a number whether it is in the range or not, it strangely validates to true, otherwise, it validates to false. The validator seems not picking up the @Range Annotation I set up on the model. The minutes is the field I am validating. Is there anything I did wrong that caused this wrong behavior?

Goal.java

package io.test.model;

import org.hibernate.validator.constraints.Range;

public class Goal {

    @Range(min = 1, max = 120)
    private int minutes;

    public int getMinutes() {
        return minutes;
    }

    public void setMinutes(int minutes) {
        this.minutes = minutes;
    }
}

GoalController.java

package io.test.controller;

import io.test.model.Goal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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.SessionAttributes;

import javax.validation.Valid;

@Controller
@SessionAttributes("goal")
public class GoalController {

    @RequestMapping(value = "addGoal", method = RequestMethod.GET)
    public String addGoal(Model model) {
        Goal goal = new Goal();
        goal.setMinutes(10);
        model.addAttribute("goal", goal);

        return "addGoal";
    }

    @RequestMapping(value = "addGoal", method = RequestMethod.POST)
    public String addGoal(@Valid @ModelAttribute("goal") Goal goal, BindingResult result) {
        System.out.println("result has errors: " + result.hasErrors() + " | " + result.toString());
        System.out.println("Minutes updated: " + goal.getMinutes());
        return "redirect:addMinutes.html";
    }


}

addGoal.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>Add Goal</title>
</head>
<body>
<form:form commandName="goal">
    <table>
        <tr>
            <td>Enter Minutes</td>
            <td><form:input path="minutes"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Enter goal minutes">
            </td>
        </tr>
    </table>
</form:form>
</body>
</html>

0 个答案:

没有答案