Spring數據校驗

maoxiongyi 12年前發布 | 39K 次閱讀 Spring JEE框架 Java JSP

1.在servelet中添加校驗引用
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" /> <property name="cacheSeconds" value="0" /> </bean>
表示在"/WEB-INF/messages"目錄下存儲校驗信息

2.在實體類中設置校驗
     /**item_name */   
     @Length(min = 1, max = 30)
    private String item_name;//對長度校驗
    /**price */
    @NotNull//非空校驗
    @Min(1)//最小值
    @Max(9999999999L)//最大值
    private Long price;
    /**genre_id_1 */
    @Pattern(regexp = "([1-9]{1,6})")//正則表達式
    private String genre_id_1;

3.編寫jsp文件
添加標簽引用:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
添加校驗:
<form:form modelAttribute="itemForm" action="/minimall/itemRegister.do" method="post">
<table border="0">
<tr>
<td>商品名</td>
<td>
<input type="text" name="item_name" value="${itemForm.item_name }" >
<form:errors path="item_name" />
</td>
</tr>  
</table>
</form:form>

4.編寫校驗信息messages.properties
typeMismatch.itemForm.price=數字を入力してください

NotNull.itemForm.price=販売価格を入力してください

Length.itemForm.item_name=商品名の長さは1~30の間にあります

Min.itemForm.price=販売価格は1より大きいです

Max.itemForm.price=販売価格は9999999999より小きいです

Pattern.itemForm.genre_id_4=全部分類を選択してください

備注:Length與2中對應,itemForm與3中對應,item_name與2中對應

5.編寫controller層
    @RequestMapping(value = "/itemRegister.do", method = RequestMethod.POST)
    public ModelAndView doItemRegister(HttpServletRequest request, @Valid @ModelAttribute("itemForm") ItemForm itemForm, BindingResult bindingResult) {
        ItemForm sitemForm = this.sanitizing(itemForm);

        if (bindingResult.hasErrors()) {
            return new ModelAndView("/item_info_input", "itemForm", itemForm);
        } else {
            if (itemService.register(sitemForm)) {
                return new ModelAndView("/item_info_confirm", "itemForm", itemForm);
            } else {
                return new ModelAndView("/registerFailed");
            }
        }
    }

 本文由用戶 maoxiongyi 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!