2016-10-26 6 views
2

コントローラからのビューでトリガエラー/検証メッセージをより適切に表現する方法を教えてください。現在、私はboolean属性を送信することでこれを行います。たとえば、製品を作成する際に、2つのエラーが考えられます。製品のUPCのフォーマットが無効です。コントローラからエラーが発生したビューを教えてください。 (Spring MVC)

<div id="menu3" 
      class="tab-pane fade <c:if test="${activeTab == 3}">in active</c:if>"> 
      <div class="container-fluid" style="padding: 2%;"> 
       <div class="row"> 
        <div class="col-md-12" 
         style="padding-left: 15%; padding-right: 15%;"> 
         <c:if test="${productCreated}"> 
          <div class="alert alert-success fade in"> 
           <a href="#" class="close" data-dismiss="alert" 
            aria-label="close">&times;</a> <strong>Success!</strong> 
           Product has been created! 
          </div> 
         </c:if> 
         <c:if test="${duplicateProduct}"> 
          <div class="alert alert-warning fade in"> 
           <a href="#" class="close" data-dismiss="alert" 
            aria-label="close">&times;</a> <strong>Oh no!</strong> 
           Product with the UPC ${upc} already exists! 
          </div> 
         </c:if> 
         <c:if test="${invalidFormat}"> 
          <div class="alert alert-warning fade in"> 
           <a href="#" class="close" data-dismiss="alert" 
            aria-label="close">&times;</a> <strong>Oops!</strong> 
           Invalid UPC format! 
          </div> 
         </c:if> 
         <form 
          action="${pageContext.request.contextPath}/manager/createProduct" 
          method="post"> 
          <div class="form-group"> 
           <label for="Name">Name </label> <input type="text" name="name" 
            class="form-control" required /> 
          </div> 
          <div class="form-group"> 
           <label for="UPC">UPC </label> <input type="number" name="upc" 
            class="form-control" required /> 
          </div> 
          <div class="form-group"> 
           <div class="form-group"> 
            <label for="category">Category</label> <select 
             class="form-control" name="category" required> 
             <option selected disabled value="">SELECT CATEGORY</option> 
             <c:forEach items="${categories}" var="item"> 
              <option>${item.getName()}</option> 
             </c:forEach> 
            </select> 
           </div> 
          </div> 
          <div class="form-group"> 
           <label for="description">Description</label> 
           <textarea class="form-control" rows="5" name="description"></textarea> 
          </div> 
          <div class="form-group"> 
           <label for="price">Price </label> <input type="number" 
            name="price" class="form-control" required /> 
          </div> 
          <div class="form-group"> 
           <label for="stock">Stock </label> <input type="number" 
            name="stock" class="form-control" required /> 
          </div> 
          <button type="submit" class="btn btn-primary">Add 
           product</button> 
         </form> 
        </div> 
       </div> 
      </div> 
     </div> 

ブールのトリガーを送信するよりも、この他を行うためのよりよいがあります:私はvalidati

@RequestMapping("/createProduct") 
public String createProduct(Model model, @RequestParam(value = "name") String name, 
     @RequestParam(value = "upc") String upc, @RequestParam(value = "category") String categoryName, 
     @RequestParam(value = "description") String description, @RequestParam(value = "price") BigDecimal price, 
     @RequestParam(value = "stock") int stock){ 

    model.addAttribute("activeTab", 3); 

    if(Validator.invalidUpcFormat(upc)){ 

     model.addAttribute("invalidFormat", true); //trigger for invalid format 
     return "management"; 
    } 

    Category category = productService.getCategory(categoryName); 

    Product product = new Product(upc, category, name, description, price); 
    InventoryProduct inventoryProduct = new InventoryProduct(product, stock); 

    try { 

     managerService.add(inventoryProduct); 
     model.addAttribute("productCreated", true); 
    } catch (DuplicateProductException e) { 

     model.addAttribute("upc", upc); 
     model.addAttribute("duplicateProduct", true); // trigger for duplicate product 
    } 



    return "management"; 
} 

そして、ここが私の見解であるともありますか?

+1

要求パラメータを使用しないでください。オブジェクトを使用し、そのオブジェクトにパラメータをバインドし、オブジェクトを検証します。他のすべてはフレームワークによって処理されます。 –

+0

「オブジェクトを使用し、パラメータをバインドしてオブジェクトを検証する」という意味を理解できません。これは私がspring mvcを使ってきた方法です。と私はかなり新しい春と春のMVC – saluyotamazing

+0

これは、ブーリアンよりも良いアプローチです。http://stackoverflow.com/a/22667775/410677 – kuhajeyan

答えて

2

Spring BindingResultを使用できます。これは典型的にはBindingとValidationの結果で満たされます。しかし、手作業でエラーを追加することもできます。

は、しかし、最初に、あなたは、あなたのコードをリファクタリングする必要がありますが、すべての@Param値の代わりに、単一のコマンド/フォームのバッキングオブジェクトを使用するように

public class CreateProductCommand { 
    private String name; 
    private String upc; 
    private String categoryName; 
    .... //other fields 
    public CreateProductCommand(){} //parameter less conturctor 

    Getter+Setter 
} 

コントローラ

@RequestMapping("/createProduct") 
public ModelAndView createProduct(CreateProductCommand createProductCommand, BindingResult bindingResult) //Binding result must be the parameter direct next to the object that should been validated!!! 
{ 


    if (someustomValidationForUcpFail()) { 
      bindingResult.rejectValue("upc", //the field name of the invalid field 
        "error.Message.Key", 
        "Default Error Message"); 
    } 

    if (bindingResult.hasErrors()) { 
     ModelMap model = new ModelMap(); 
     model.add("createProductCommand", createProductCommand); 
     return new ModelAndView("createForm", model) 
    } else { 
     Product product = ... 
     return new ModelAndView("showProduct", "product", product) 
    } 
} 

のjsp:

スプリングフォームと入力タグを使用する必要があります。

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" 
      xmlns:c="http://java.sun.com/jsp/jstl/core" 
      xmlns:springForm="http://www.springframework.org/tags/form" 
      version="2.0"> 
    .... 
    <springForm:form action="<c:url value="/manager/createProduct">" method="POST" modelAttribute="createProductCommand"> 
     <springForm:input path="name"/> <form:errors path="name" /> 
     <springForm:input path="ucp"/> <form:errors path="ucp" /> 
     .... 
    </springForm:form> 
    .... 
関連する問題