在表单上显示错误消息

时间:2015-02-21 09:41:25

标签: java spring jsp

我想在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>

控制器类方法:

@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";
    }

我想检查orderOlader方法中的amount字段和displayOrder方法中的id字段是否为整数,并在各个表单上显示相应的消息。对于ex- amount应该是整数或整数不在范围内等。 感谢。

2 个答案:

答案 0 :(得分:0)

在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>

答案 1 :(得分:0)

您可以使用validation-api和hibernate-validator并将所需的注释挂起到您的类字段,例如@ Size,@ NotNull等。在控制器中,只需将@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";
}