springmvc學習筆記(14)-springmvc校正

來源:互聯網
上載者:User

springmvc學習筆記(14)-springmvc校正
springmvc學習筆記(14)-springmvc校正

本文主要介紹springmvc校正,包括環境準備,校正器配置,pojo張添加校正規則,捕獲和顯示檢驗錯誤資訊以及分組校正簡單樣本。

校正理解

項目中,通常使用較多是前端的校正,比如頁面中js校正。對於安全要求較高點建議在服務端進行校正。

服務端校正:

控制層conroller:校正頁面請求的參數的合法性。在服務端控制層conroller校正,不區分用戶端類型(瀏覽器、手機用戶端、遠程調用) 業務層service(使用較多):主要校正關鍵業務參數,僅限於service介面中使用的參數。 持久層dao:一般是不校正的。springmvc校正需求

springmvc使用hibernate的校正架構validation(和hibernate沒有任何關係)。

校正思路:

頁面提交請求的參數,請求到controller方法中,使用validation進行校正。如果校正出錯,將錯誤資訊展示到頁面。

具體需求:

商品修改,添加校正(校正商品名稱長度,生產日期的非空校正),如果校正出錯,在商品修改頁面顯示錯誤資訊。

環境準備

我們需要三個jar包:

hibernate-validator.jar jboss-logging.jar validation-api.jar

這裡我們添加maven依賴

    org.hibernate    hibernate-validator    5.2.4.Final

查看maven依賴樹

[INFO] \- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile[INFO]    +- javax.validation:validation-api:jar:1.1.0.Final:compile[INFO]    +- org.jboss.logging:jboss-logging:jar:3.2.1.Final:compile[INFO]    \- com.fasterxml:classmate:jar:1.1.0:compile

可以看到,另外兩個jar包被hibernate-validator依賴,所以不用再額外添加了。

配置校正器在springmvc.xml中添加
                                            classpath:CustomValidationMessages                            
校正器注入到處理器適配器中
在CustomValidationMessages.properties配置校正錯誤資訊:
#添加校正的錯誤提示資訊items.name.length.error=請輸入1到30個字元的商品名稱items.createtime.isNUll=請輸入商品的生產日期
在pojo中添加校正規則

在ItemsCustom.java中添加校正規則:

public class Items {    private Integer id;    //校正名稱在1到30字元中間    //message是提示校正出錯顯示的資訊    //groups:此校正屬於哪個分組,groups可以定義多個分組    @Size(min=1,max=30,message="{items.name.length.error}")    private String name;    private Float price;    private String pic;    //非空校正    @NotNull(message="{items.createtime.isNUll}")    private Date createtime;
捕獲和顯示校正錯誤資訊
@RequestMapping("/editItemsSubmit")public String editItemsSubmit(        Model model,        HttpServletRequest request,        Integer id,        @Validated ItemsCustom itemsCustom,        BindingResult bindingResult)throws Exception {
在controller中將錯誤資訊傳到頁面即可
//擷取校正錯誤資訊if(bindingResult.hasErrors()){    // 輸出錯誤資訊    List allErrors = bindingResult.getAllErrors();    for (ObjectError objectError :allErrors){        // 輸出錯誤資訊        System.out.println(objectError.getDefaultMessage());    }    // 將錯誤資訊傳到頁面    model.addAttribute("allErrors", allErrors);    //可以直接使用model將提交pojo回顯到頁面    model.addAttribute("items", itemsCustom);    // 出錯重新到商品修改頁面    return "items/editItems";}
頁面顯示錯誤資訊:
            ${ error.defaultMessage}    
分組校正需求:
在pojo中定義校正規則,而pojo是被多個controller所共用,當不同的controller方法對同一個pojo進行校正,但是每個controller方法需要不同的校正 解決方案:
定義多個校正分組(其實是一個java介面),分組中定義有哪些規則 每個controller方法使用不同的校正分組

1.校正分組

public interface ValidGroup1 {    //介面中不需要定義任何方法,僅是對不同的校正規則進行分組    //此分組只校正商品名稱長度}

2.在校正規則中添加分組

//校正名稱在1到30字元中間//message是提示校正出錯顯示的資訊//groups:此校正屬於哪個分組,groups可以定義多個分組@Size(min=1,max=30,message="{items.name.length.error}",groups = {ValidGroup1.class})private String name;

3.在controller方法使用指定分組的校正

// value={ValidGroup1.class}指定使用ValidGroup1分組的校正@RequestMapping("/editItemsSubmit")public String editItemsSubmit(        Model model,        HttpServletRequest request,        Integer id,        @Validated(value = ValidGroup1.class)ItemsCustom itemsCustom,        BindingResult bindingResult)throws Exception {

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.