簡體   English   中英

在表單上顯示錯誤消息

[英]Display error message back on form

我想在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應該是整數或整數不在范圍等等。謝謝。

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

您可以使用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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM