[英]Display error message back on form
I want to validate the form input in jsp and display the error messages back to the form only. 我想在jsp中验证表单输入并仅将错误消息显示回表单。 I am able to redirect to the form in case of error but haven't found something useful to display the errors.
我可以在出错的情况下重定向到表单,但是没有找到显示错误的有用信息。
create.jsp create.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Create Order</title>
</head>
<body>
<form method="POST" action="placeOrder.html">
<p>Product Name :
<input type="text" name="pname" required/>
</p>
<p>Customer Name :
<input type="text" name="cname" required/>
</p>
<p>Amount :
<input type="text" name="amount" required/>
</p>
<p>Address :
<input type="text" name="address" required/>
</p>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
controller class method : 控制器类方法:
@RequestMapping(value = "placeOrder.html", method = RequestMethod.POST)
public String orderPlaced(@ModelAttribute("orderweb") Orders o,
BindingResult binders) {
if (binders.hasErrors()) {
System.out.println(binders.getFieldError());
return "create";
}
this.orderservice.createOrder(o);
return "orderDetails";
}
@RequestMapping(value = "displayOrder.html", method = RequestMethod.POST)
public String displayOrder(@RequestParam("id") int id, Model model) {
model.addAttribute("orderweb", this.orderservice.getOrderbyId(id));
return "orderDetails";
}
I want to check whether amount field in orderPlaced method and id field in displayOrder method are integers or not and display the appropriate messages on repective forms. 我想检查orderOlader方法中的amount字段和displayOrder方法中的id字段是否为整数,并在各个表单上显示相应的消息。 For ex- amount should be integer or integer not in range etc. Thanks.
对于ex- amount应该是整数或整数不在范围等等。谢谢。
In your JSP add the below lines 在您的JSP中添加以下行
<spring:hasBindErrors name="YourCommandObjectName">
<font color="red">
<c:forEach items="${errors.allErrors}" var="error">
<spring:message code="${error.code}" text="${error.defaultMessage}"/>
</c:forEach>
</font>
</spring:hasBindErrors>
You can use validation-api and hibernate-validator and hangs required annotations to your class fields such as @Size, @NotNull and others. 您可以使用validation-api和hibernate-validator并将所需的注释挂起到您的类字段,例如@ Size,@ NotNull等。 In the controller simply add @Valid to your model attribute :
在控制器中,只需将@Valid添加到模型属性:
@RequestMapping(value = "placeOrder.html", method = RequestMethod.POST)
public String orderPlaced(@ModelAttribute("orderweb")
@Valid
Orders o,
BindingResult binders) {
if (binders.hasErrors()) {
System.out.println(binders.getFieldError());
return "create";
}
this.orderservice.createOrder(o);
return "orderDetails";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.