我想用Spring MVC实现简单的验证。
我添加到pom.xml
:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
这是我的 POJO :
import org.hibernate.validator.constraints.Range;
public class Goal {
@Range(min = 1, max = 120)
private int minutes;
// getters + setters
和 控制器 实施:
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 updateGoal(@Valid @ModelAttribute(value = "goal") Goal goal, BindingResult result) {
System.out.printf("Result has errors: %s%n", result.hasErrors());
System.out.printf("Minutes updated: %d%n", goal.getMinutes());
if (result.hasErrors()) {
return "addGoal";
}
return "redirect:/addMinutes.html";
}
}
addGoal.jsp
页面:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>Add Goal Here</title>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffeeee;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body>
Language: <a href="?language=en">English</a> | <a href="?language=uk">Ukrainian</a>
<form:form commandName="goal">
<form:errors path="*" cssClass="errorblock" element="div" />
<table>
<tr>
<td><spring:message code="goal.minutes"/></td>
<td><form:input path="minutes"/></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>
这是页面浏览:
适当的结果:
来自 控制台的
摘录:
Result has errors: false
Minutes updated: -5
它应该显示负输入的错误信息并保持在同一页而不是第二次屏幕截图。
我无法弄清楚造成这种麻烦。
有任何建议吗?
答案 0 :(得分:0)
在Tomcat上清理了解决方案 - webapps
文件夹。
我删除了已部署的旧webapp。 现在可以正常使用 。
它对我目前的申请有一些奇怪的影响。