1. 程式人生 > >SpringMVC-表單驗證

SpringMVC-表單驗證

1.mvc:annotation-driven

實際開發時建議都配置該引數。
配置<mvc:annotation-driven/>後,SpringMVC會自動註冊RequestMappingHandlerMapping,
RequestMappingHandlerAdapter,ExceptionHandlerExceptionResolver三個bean。
還將提供一下支援
-支援用ConversionServices例項對錶單引數進行型別轉換,通過配置conversion-service屬性自定義型別轉換。
-支援使用@NumberFormat註解,@DateTimeFormat註解完成資料型別格式化
-支援使用@Valid註解對JavaBean例項進行JSR303驗證
-支援使用@ReqeustBody和@ResponseBody註解

2.InitBinder註解

WebDataBinder用於完成表單欄位到JavaBean屬性的繫結,而@InitBinder註解則可以對WebDataBinder物件進行初始化,
以及資料設定的相關限制。被InitBinder註解修飾的方法不能有返回值,且引數通常為WebDataBinder。
如下例子,規定name屬性不會被表單欄位自動繫結。
package spring;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class TestController {
	
	@RequestMapping(value="/test", method=RequestMethod.GET)
	public String testGet(Map<String, Object>map){
		Person person = new Person();
		map.put("person", person);
		return "form";
	}
	
	@RequestMapping(value="/test", method=RequestMethod.POST)
	public String testPost(Person person){
		System.out.println(person);
		return "success";
	}
	
	@InitBinder
	public void testBinder(WebDataBinder dataBinder){
		dataBinder.setDisallowedFields("name");
	}
}

3.資料格式化

表單的資料轉換是將字串形式的表單資料轉換為JavaBean物件,如果是簡單的物件不需要格式,則不需要特殊指定,但是比如日期型別的格式,如果不指定,則無法進行格式化,因為不知道是2016/6/4格式,還是2016-6-4格式。為了讓SpringMVC在進行格式化時知道具體的目標,只需要在JavaBean物件中使用合適的註解進行型別,格式化標註即可。

註解型別有:

[email protected]
     有兩個互斥的屬性,style:Style.NUMBER 正常數字,Style.PERCENT 百分數,Style.CURRENCY 貨幣
     pattern:型別為String,可以進行自定義樣式比如“#,###”

[email protected] 可以對Date,Calendar,Long時間型別進行標註,有一個pattern屬性,可以賦值比如“yyyy-MM-dd hh:mm:ss"的格式。

public class Person {
	@NumberFormat(pattern="##,##") //注意.是小數的關鍵字,不能用.分割。
	private Integer id;
	
	@DateTimeFormat(pattern="YYYY-mm-dd")
	private Date birth;

4.資料校驗

使用JSR303進行校驗,JSR303是Java為Bean資料合法性校驗提供的標準框架,在JavaEE6.0中已經實現。
通過在JavaBean屬性上加上註解,即可為屬性提供校驗功能。註解有如下內容

@Null 必須為空
@NotNull 必須非空
@AssertTrue 必須為True
@AssertFalse 必須為False
@Min(value)  @Max(value) 這兩個註解的屬性必須是數字,且大於等於最小,小於等於最大
@DecimalMin(value) @DecimalMax(value) 同上
@Size(max,min)被註解的屬性必須在之間。
@Digits(Integer, fraction) 註解的屬性為數字,且在可接受範圍內
@Past被註解的屬性必須是過去時間,比如生日
@Future 必須是以後的時間。
@Pattern(value) 必須是符合指定的正則表示式
HibernateValidator的實現中,在JSR303基礎上還提供了下面的幾個註解:
@Email 有效的Email
@Length 字串必須在指定的長度內
@NotEmpty 非空
@Range 元素必須在有效範圍內。

5.配置資料校驗步驟

1)SpringMVC的配置檔案中需要加入<mvc:annotation-driven/>配置,這個配置用來裝配LocalValidatorFactoryBean。
2)由於Spring中沒有實現JSR303,所以需要加入其他實現的jar包
hibernate-validator-5.2.4.Final.jar
hibernate-validator-annotation-processor-5.2.4.Final.jar
hibernate-validator-cdi-5.2.4.Final.jar
lib/required/validation-api-1.1.0.Final.jar
lib/required/jboss-logging-3.2.1.Final.jar
lib/required/classmate-1.1.0.jar
3)在Person Bean的name屬性上新增@NotEmpty註解
4)在RequestMapping註解的方法引數上新增@Valid註解。
public String testValidator(@Valid Person person)
5)注意下面例子中,引數①要驗證的person,②驗證結果personValidateResult之間不能有其他引數。
	@RequestMapping(value="/test", method=RequestMethod.POST)
	public String testValidate(@Valid Person person, /*BindingResult error,*/ BindingResult personValidateResult){
		if(personValidateResult.getErrorCount() > 0){
			System.out.println("Error");
			for(FieldError fieldError:personValidateResult.getFieldErrors()){
				System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
				return "form";
			}
		}else{
			System.out.println(person);
		}
		return "success";
	}

6.在頁面上回顯錯誤資訊

只需要使用<form:errors path="指定屬性的錯誤資訊">即可在網頁中回顯。

7.定製錯誤資訊

每個屬性的資料繫結和資料校驗發生錯誤時,都會生成一個對應的FieldError物件。
當一個屬性校驗失敗後,校驗框架會為該屬性生成四個錯誤訊息程式碼。註解字首,ModelAttribute,屬性名即屬性型別名:以Person類中name屬性標註了@Pattern註解為例,會生成一下四個錯誤程式碼
  -Pattern.person.name //注意person是Person類定義的實際變數引數的名字
  -Pattern.name
  -Pattern.java.lang.String
  -Pattern
當使用SpringMVC進行錯誤顯示時,會檢視WEB上下文是否制定了國際化配置,有則用,無則顯示預設值。
另外三個特殊的資訊:
  [email protected]() 引數不存在的錯誤,用required.字首
  -資料繫結型別錯誤時,typeMismatch字首
  -methodInvocation:SpringMVC在呼叫處理方法時發生錯誤
完整的程式碼清單如下:
1.Person Bean的定義
package spring;

import java.util.Date;

import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;

public class Person {
	@NumberFormat(pattern="##,##") //注意.是小數的關鍵字,不能用.分割。
	private Integer id;
	
	@Past //表單校驗,生日必須發生在今天以前
	@DateTimeFormat(pattern="YYYY-mm-dd") //資料格式化
	private Date birth;
	
	@NotEmpty //表單校驗,名字不能為空
	private String name;

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
	public Person(Integer id, String name, Date birth) {
		super();
		this.id = id;
		this.name = name;
		this.birth = birth;
	}
	
	public Person(){}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", birth=" + birth + "]";
	}
}
2.配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	<context:component-scan base-package="spring"></context:component-scan>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="i18n"></property>
	</bean>
	
	<mvc:default-servlet-handler/>
	<mvc:annotation-driven></mvc:annotation-driven>
</beans>
3.i18n.properties
在配置檔案中指定了basename為i18n,則必須定義i18n.properties的配置檔案。由於是UTF-8的,漢字都會被轉碼
NotEmpty.person.name=\u4EBA\u7684\u540D\u5B57\u4E0D\u80FD\u4E3A\u7A7A //<span style="color:red;">人的名字不能為空</span>
Past.person.birth=\u51FA\u751F\u65E5\u671F\u6709\u95EE\u9898 //<span style="color: red; font-family: Arial, Helvetica, sans-serif; font-size: 12px;">出生日期有問題</span>
4.index.jsp
<body>
	<a href="/spring/test">Add New</a>
</body>
5.form.jsp
用<form:xxx>定義表單成員時,必須配置modelAttribute,或者使用預設的command。為了獲取這個資料,必須先經過下面@RequestMapping中先設定command,或者modelAttribute的資料,然後經過轉發跳轉到該頁面。
form:errors用來回顯錯誤資訊。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.Map,java.util.HashMap" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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 method="POST" action="/spring/test" modelAttribute="person">
		ID:<form:input path="id"/><font color="red"><form:errors path="id"/></font><br>
		Name:<form:input path="name"/><font color="red"><form:errors path="name"/></font><br>
		birth:<form:input path="birth"/><font color="red"><form:errors path="birth"/></font><br>
		<input type="submit" value="submit">
	</form:form>
</body>
</html>
6.控制器程式碼
package spring;
import java.util.Map;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class TestController {
	@RequestMapping(value="/test", method=RequestMethod.GET)
	public String testGet(Map<String, Object>map){
		Person person = new Person();
		map.put("person", person);
		return "form";
	}
	
	@RequestMapping(value="/test", method=RequestMethod.POST)
	public String testValidate(@Valid Person person, /*BindingResult error,*/ BindingResult personValidateResult){
		if(personValidateResult.getErrorCount() > 0){
			System.out.println("Error");
			for(FieldError fieldError:personValidateResult.getFieldErrors()){
				System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
				return "form";
			}
		}else{
			System.out.println(person);
		}
		return "success";
	}
}
<完>

相關推薦

SpringMVC-驗證

1.mvc:annotation-driven 實際開發時建議都配置該引數。 配置<mvc:annotation-driven/>後,SpringMVC會自動註冊RequestMappingHandlerMapping, RequestMappingHandle

SpringMVC+AJAX登入驗證問題

畢業設計,使用springMVC+AJAX(jquery)實現登入表單驗證問題,將遇到的問題記錄下來 1 controller層可以接收到前臺請求引數,但是success和error都不執行 無圖言叼 這是js <script type="text/javascript">

SpringMVC form標籤、伺服器驗證、錯誤資訊回顯

form標籤 應用場景:方便伺服器資料在form表單上的展示 使用方式:1.引入標籤庫   2.建立表單   例如:建立兩個實體類 @[email protected]@ToString public class User { private

使用ValidForm進行驗證,結合SpringMVC檢驗使用者名稱是否存在

由於最近在開發一個網站,需要進行表單驗證。以往都是用js進行驗證。雖然簡單,但是程式碼多,不方便,無法實現高效率的開發。因為在網上找到了一款很方便高效的js驗證框架:ValidForm。有關ValidForm的更多介紹,可前往官網:http://validform.rjbo

純H5+c3實現驗證

mail ida 網址 put 滿足 字段 address ini css3 客戶端驗證是網頁客戶端程序最常用的功能之一,我們之前使用了各種各樣的js庫來進行表單的驗證。HTML5其實早已為我們提供了表單驗證的功能。至於為啥沒有流行起來估計是兼容性的問題還有就是樣式太醜陋了

驗證

java pwd word 用戶註冊 -1 style 字符 text date <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></

JaveWeb 公司項目(4)----- Easyui的驗證

過程 -- 目前 要求 今天 和數 希望 小項目 web 前面三篇博文講述的是界面的搭建和數據的傳輸,可以看出目前我做的這個小項目已經有了一個大體的雛形,剩下的就是細節部分的打磨和一些友好的人機交互設計,今天做的是表單的驗證,作為初學者,著實花了一番功夫,所以寫一篇博文將這

jQuery基礎(常用插件 驗證,圖片放大鏡,自定義對象級,jQuery UI,面板折疊)

此外 cookie值 添加圖標 tor 列表 需要 droppable 使用 ddn 1.表單驗證插件——validate 該插件自帶包含必填、數字、URL在內容的驗證規則,即時顯示異常信息,此外,還允許自定義驗證規則,插件調用方法如下: $(form).vali

第一篇,js驗證模板

scrip put func wrong lur ctype lan lang 執行 下面是對於一個email的表單驗證的基本模板<!DOCTYPE html><html lang="en"><head> <meta char

一個驗證

wrong spa 插件 position ava char email格式 box eth <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/

angular js h5關於驗證的例子

checked tro mis scrip att sta error 自定義 account angular js表單驗證 <!DOCTYPE html><html><head lang="en"> <meta charse

Java Script 第10章 JavaScript驗證

cnblogs ges scrip isp asc ima javascrip lock 分享 Java Script 第10章 JavaScript表單驗證

驗證的設計

解決方案 正則 wan 光有 做了 我只 cnblogs 提示 重要   不說廢話,直接留幹貨。實現的效果:多條表單提交的時候,如果某個表單的輸入不和格式要求,則提示對應的錯誤信息,所有表單的內容合適,則提交到後臺。顯示代碼(這裏的dom的結構不唯一,我只是在我實際的項目中

SpringBoot驗證

mage 驗證 log image 技術分享 img 不能 spring blog 需求:年齡在18歲以下的女生不能註冊 處理器中的寫法: 實體類中的寫法: SpringBoot表單驗證

驗證 靠name獲取

res 獲取 ems let nbsp jquer 手機 ear sub 表單 靠name獲取 <form class="add-form" name="form" action="#" method="post" autocomplete="on">

jq中的驗證插件------jquery.validate

此外 郵箱 method 你們 ostc [0 ade 使用 js代碼 今天我們來說一下表單驗證,有人說我們在進行表單驗證的時候使用正則來驗證是非常麻煩的,現在我來給大家介紹一下表單驗證的插件:jquery.validate.min.js 它是與jquery一起結合

JavaScript驗證和正則表達式

sco 集合 innertext ner rep tell 一次 臨時 軟件 JavaScript表單驗證 分為四類:   1.非空驗證     常用於用戶名等   2.相等驗證     常用於驗證兩次輸入的密碼   3.範圍驗證     常用於年齡等  

jquery validation驗證插件2。

back nbsp $() static 輸入 run hand get () <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></t

JavaScript驗證

號碼 網址 處理 漢字 dsm 嵌套 15位 使用 修正 匹配中文字符的正則表達式: [u4e00-u9fa5] 評註:匹配中文還真是個頭疼的事。有了這個表達式就好辦了 匹配雙字節字符(包含漢字在內):[^x00-xff] 評註:能夠用來計算字符串的長度(一個雙字節字符長

SpringMVC上傳文件+單數據

使用 req pojo 提交表單 tps param servlet tip 表單 本次遇到的需求是:在用戶提交表單數據的時候,同時上傳文件。並且表單數據傳到後臺可以組成一個pojo controller層的方法定義如下: public Object apply(HttpS