Validation (the implimentation is called hibernate validation)
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Goal</title>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body>
<form:form commandName="goal">
<form:errors path="*" cssClass="errorblock" element="div" /> <!-- the * means disolay all errors -->
<table>
<tr>
<td>Enter Minutes:</td>
<td><form:input path="minutes" cssErrorClass="error" /></td>
<td><form:errors path="minutes" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Enter Goal Minutes"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
package com.pluralsight.controller;
import javax.validation.Valid;
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 com.pluralsight.model.Goal;
@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 updateGoal(@Valid @ModelAttribute("goal") Goal goal, BindingResult result) {
System.out.println("result has errors: " + result.hasErrors());
System.out.println("Minutes updated: " + goal.getMinutes());
if(result.hasErrors()) {
return "addGoal";
}
return "redirect:addMinutes.html";
}
}
package com.pluralsight.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;
}
}