0
我想用Spring MVC實現簡單驗證。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
應該顯示錯誤消息負輸入,並保持在同一頁面,而不是第二個截屏。
我找不出造成這種麻煩。
有什麼建議嗎?
你的jsp文件中'form'標籤的聲明在哪裏? – mic4ael
@ mic4ael我省略了它來縮短代碼片段。我編輯了問題。 –
好的,我認爲這可能是問題所在。 – mic4ael