springmvc 10 表單與驗證

表單

表單用的是springmvc的form標(biāo)簽

  1. 引入springmvc的form標(biāo)簽
  2. 在form標(biāo)簽中使用modelAttribute屬性指明表單對應(yīng)的bean對象
  3. 如果bean對象是空值,那么表單沒有內(nèi)容
    如果bean對象有內(nèi)容,那么表單回顯內(nèi)容
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
    <form:form action="${pageContext.request.contextPath}/test" method="post" modelAttribute="employee">
        
        name:<form:input path="empName"/><br>
        <!-- path對應(yīng)的是bean對象的屬性名 -->
        
        email:<form:input path="empEmail"/><br>

        <br><button type="submit">提交</button>
    </form:form>

</body>
</html>
@Controller
public class Test {
    
    @RequestMapping(value="/test")
    public String test(Map<String,Object> map){

//      map.put("employee", new Employee());//"employee"是表單對應(yīng)的bean名稱
        
        Employee employee = new Employee();
        employee.setEmpName("dd");
        employee.setEmpEmail("1137@qq.com");
        map.put("employee", employee);
        return "test";
    }
}
Paste_Image.png
Paste_Image.png

JSR-303進(jìn)行校驗:

1. 新加hibernate-validator jar包
到官網(wǎng)下載>http://hibernate.org/validator/

Paste_Image.png

Paste_Image.png

2. 開啟<mvc:annotation-driven/>

3. 在bean屬性中添加對應(yīng)的注解

    @Email //表單驗證-郵箱格式
    @NotEmpty //表單驗證-不能為空
    private String empEmail;
空檢查
@Null       驗證對象是否為null
@NotNull    驗證對象是否不為null, 無法查檢長度為0的字符串
@NotBlank 檢查約束字符串是不是Null還有被Trim的長度是否大于0,只對字符串,且會去掉前后空格.
@NotEmpty 檢查約束元素是否為NULL或者是EMPTY.
 
Booelan檢查
@AssertTrue     驗證 Boolean 對象是否為 true  
@AssertFalse    驗證 Boolean 對象是否為 false  
 
長度檢查
@Size(min=, max=) 驗證對象(Array,Collection,Map,String)長度是否在給定的范圍之內(nèi)  
@Length(min=, max=) Validates that the annotated string is between min and max included.
 
日期檢查
@Past           驗證 Date 和 Calendar 對象是否在當(dāng)前時間之前  
@Future     驗證 Date 和 Calendar 對象是否在當(dāng)前時間之后  
@Pattern    驗證 String 對象是否符合正則表達(dá)式的規(guī)則
 
數(shù)值檢查,建議使用在Stirng,Integer類型,不建議使用在int類型上,因為表單值為“”時無法轉(zhuǎn)換為int,但可以轉(zhuǎn)換為Stirng為"",Integer為null
@Min            驗證 Number 和 String 對象是否大等于指定的值  
@Max            驗證 Number 和 String 對象是否小等于指定的值  
@DecimalMax 被標(biāo)注的值必須不大于約束中指定的最大值. 這個約束的參數(shù)是一個通過BigDecimal定義的最大值的字符串表示.小數(shù)存在精度
@DecimalMin 被標(biāo)注的值必須不小于約束中指定的最小值. 這個約束的參數(shù)是一個通過BigDecimal定義的最小值的字符串表示.小數(shù)存在精度
@Digits     驗證 Number 和 String 的構(gòu)成是否合法  
@Digits(integer=,fraction=) 驗證字符串是否是符合指定格式的數(shù)字,interger指定整數(shù)精度,fraction指定小數(shù)精度。
 
@Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.
@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;
 
@Valid 遞歸的對關(guān)聯(lián)對象進(jìn)行校驗, 如果關(guān)聯(lián)對象是個集合或者數(shù)組,那么對其中的元素進(jìn)行遞歸校驗,如果是一個map,則對其中的值部分進(jìn)行校驗.(是否進(jìn)行遞歸驗證)
@CreditCardNumber信用卡驗證
@Email  驗證是否是郵件地址,如果為null,不進(jìn)行驗證,算通過驗證。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)

4. 在目標(biāo)方法bean類型前面添加@Valid注解

public String save(@Valid Employee employee)

補(bǔ)充
還可以結(jié)合BindingResult,如果表單驗證出錯將會在后臺和前臺顯示出錯誤信息;這里還要用到一個標(biāo)簽

<form:errors path="bean屬性名"/>

        name:<form:input path="empName"/>
        <form:errors path="empName"/><br>
        
        
        email:<form:input path="empEmail"/>
        <form:errors path="empEmail"/><br>
        
        gender:
        <form:radiobuttons path="empGender" items="${genders}"/>
        <form:errors path="empGender"/><br>
    /**添加Employee*/
    @RequestMapping(value="/emp",method=RequestMethod.POST)
    public String save(@Valid Employee employee,BindingResult result,Map<String,Object> map){
        if (result.getFieldErrorCount()>0){
            for (FieldError error:result.getFieldErrors()){
                System.out.println(error.getField()+":"+error.getDefaultMessage());
            }
            
            Map<Integer,String> genders = new HashMap<Integer,String>();
            genders.put(0, "Female");
            genders.put(1, "Male");
            
            map.put("genders", genders);
            map.put("depts", departmentDao.getAll());
            
            //跳到要顯示錯誤的頁面(不能使用redirect)
            return "input";//
        }
        employeeDao.save(employee);
        return "redirect:/list";
    }
//empEmail:不是一個合法的電子郵件地址
//empEmail:不能為空
//empName:不能為空
//!!! @Valid修飾的bean對象必須緊挨著BindingResult對象
Paste_Image.png

自定義顯示錯誤信息

前面已經(jīng)在后臺和前臺輸出了表單驗證的錯誤信息,但是錯誤信息的內(nèi)容是已經(jīng)內(nèi)置好的,現(xiàn)在我們要自定義一份自己的表單驗證錯誤信息

  1. 配置國際化資源文件
    <!-- 配置國際化資源文件 -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="errors"></property>
    </bean>
  1. src下創(chuàng)建errors.properties資源文件
NotEmpty.employee.empName=\u8BF7\u8F93\u5165\u7528\u6237\u540D
NotNull.employee.empGender=\u8BF7\u9009\u62E9\u6027\u522B
NotEmpty.employee.empEmail=\u8BF7\u8F93\u5165\u90AE\u7BB1
Email.employee.empEmail=\u8BF7\u8F93\u5165\u6B63\u786E\u683C\u5F0F\u7684\u90AE\u7BB1
//格式:標(biāo)簽注解(不要@).bean名.bean對應(yīng)屬性
required:必要的參數(shù)不存在,如@RequiredParam("param1")標(biāo)注
了一個入慘,但是該參數(shù)不存在
typeMismatch:在數(shù)據(jù)綁定時,發(fā)生數(shù)據(jù)類型不匹配的問題,如日期格式不匹配
methodInvocation:Spring MVC在調(diào)用處理方法時發(fā)生了錯誤******

換個姿勢再來一次

Paste_Image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容