天天看點

SpringMVC詳解四、自帶标簽庫及自定義參數轉換器1、SpringMVC标簽庫(*用的不多*)2、自定義參數轉換器WebDataBinder3、(conversionService )自定義String到java.util.Date類型轉換器4、(Validate)較驗器----參數的有效性驗證Validate----Hibernate5、(bindingResult)自定義錯誤資訊的回顯

1、SpringMVC标簽庫

2、自定義參數轉換器WebDataBinder

3、(conversionService )自定義String到java.util.Date類型轉換器

4、(Validate)較驗器----參數的有效性驗證Validate----Hibernate(JSR303)

5、(bindingResult)自定義錯誤資訊的回顯

SpringMVC詳解四、自帶标簽庫及自定義參數轉換器1、SpringMVC标簽庫(*用的不多*)2、自定義參數轉換器WebDataBinder3、(conversionService )自定義String到java.util.Date類型轉換器4、(Validate)較驗器----參數的有效性驗證Validate----Hibernate5、(bindingResult)自定義錯誤資訊的回顯

1、SpringMVC标簽庫(*用的不多*)

1、搭建SpringMVC開發環境

導入springmvc所需要的jar包

commons-logging-1.1.3.jar

log4j-1.2.17.jar

spring-aop-4.0.0.RELEASE.jar

spring-beans-4.0.0.RELEASE.jar

spring-context-4.0.0.RELEASE.jar

spring-core-4.0.0.RELEASE.jar

spring-expression-4.0.0.RELEASE.jar

spring-web-4.0.0.RELEASE.jar

spring-webmvc-4.0.0.RELEASE.jar

配置配置檔案:

log4j.properties

# Global logging configuration
log4j.rootLogger=INFO, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
           

Springmvc配置檔案:

<?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.0.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.0.xsd">

	<context:component-scan base-package="com.tcent"></context:component-scan>
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<mvc:annotation-driven></mvc:annotation-driven>
	<mvc:default-servlet-handler />

</beans>
           

web.xml中的配置内容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>tag</display-name>
	
	<!-- 解決中文亂碼的filter -->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 支援restful風格的filter -->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	
	<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>
           

2、建立對象模型Person對象

public class Person {
	private Integer id;
	private String name;
	private Date birthDate;
	private String email;
	private BigDecimal salary;
           

3、在webContent下建立jsp頁面

springMVC的标簽form标簽可以關聯Request域中bean對象

method="delete" 此時的method有crud的restful風格,可以增删改查

addPerson.jsp頁面:

<body>
		<!-- 
			springMVC的标簽form标簽可以關聯Request域中bean對象
			我們在隐含模型中儲存的key值。也一定要跟form:form标簽中的modelAttribute值對應上。
		 -->
		這裡是添加使用者頁面
		<form:form action="${ pageContext.request.contextPath }/addPerson" method="delete" 
			modelAttribute="person">
		name:<form:input path="name"/><br/>
<%-- 		birthDate:<form:input path="birthDate"/><br/> --%>
		email:<form:input path="email"/><br/>
		salary:<form:input path="salary"/><br/>	
		<input type="submit" />		
		</form:form>
	</body>
           

4、建立PersonController控制器

隐含模型中必須要有一個form标簽對應的pojo對象

@Controller
public class PersonController {

	@RequestMapping(value = "/toAddPerson")
	public String toAddPerson(Map<String, Object> map) {
		System.out.println("經過toAddPerson方法");
		// 隐含模型中必須要有一個form标簽對應的pojo對象
		map.put("person", new Person(12, "wzg168", null, "[email protected]",
				new BigDecimal(30000)));

		return "addPerson";
	}

	@RequestMapping(value = "/addPerson")
	public String addPerson(Person person) {
		System.out.println("添加使用者【" + person + "】到資料庫");
		return "redirect:/index.jsp";
	}

}
           

2、自定義參數轉換器WebDataBinder

2.1、WebDataBinder類介紹

在SpringMVC中有WebDataBinder類。這個類專門用來負責将請求參數類型轉換。以及請求參數資料驗證,錯誤資訊綁定等功能。

在WebDataBinder類中有三個元件分别處理三種不同的功能。

(1)、conversionService 負責處理參數類型轉換。把請求的參數轉換成為Controller中的方法參數值。

converters接口:在ConversionService元件中需要各種類型轉換器,在conversionService元件中需要依賴于各種轉換器類去實作轉換工作。

(2)、validators 負責驗證傳入的參數值是否合法。

(3)、bindingResult 負責接收驗證後的錯誤資訊。

下圖展示了WebDataBinder、ConversionService、Converter的關系。

SpringMVC詳解四、自帶标簽庫及自定義參數轉換器1、SpringMVC标簽庫(*用的不多*)2、自定義參數轉換器WebDataBinder3、(conversionService )自定義String到java.util.Date類型轉換器4、(Validate)較驗器----參數的有效性驗證Validate----Hibernate5、(bindingResult)自定義錯誤資訊的回顯

如果我們要自定義請求參數的類型轉換器。需要實作org.springframework.core.convert.converter.Converter<S,T>接口。

然後注入到ConversionService元件中。最後再将ConversionService注入到WebDataBinder中。建立ConversionService元件,需要配置:

org.springframework.format.support.FormattingConversionServiceFactoryBean對象。

3、(conversionService )自定義String到java.util.Date類型轉換器

方法一:String到java.util.Date轉換

/**
 * 自定義 String轉換成為java.util.Date類
 *
 */
public class MyStringToDateConverter implements Converter<String, Date> {
	// 字元串和日期類型互相轉換的工具類
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	/**
	 * convert就是轉換器工作時調用的轉換方法<br/>
	 * 參數source就是用戶端傳遞過來的值。
	 */
	@Override
	public Date convert(String source) {
		// 以下情況上null,無法轉換
		if (source == null) {
			return null;
		}
		if (source != null && "".equals(source.trim())) {
			return null;
		}
		
		try {
			// 将日期 字元串轉換成為 java.util.Date類型
			return sdf.parse(source);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("Invalid Date value '" + source + "'");
		}
	}

}
           

在springmvc配置檔案中做如下的配置:

<!-- 配置FormattingConversionServiceFactoryBean去建立ConversionService元件,用于類型轉換 -->
	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<!-- 将自己定義的各種Converter轉換器。注入到ConversionService中 -->
		<property name="converters">
			<set>
				<bean class="com.tcent.converter.MyStringToDateConverter" />
			</set>
		</property>
	</bean>
	
	<!-- 靜态資源的支援 -->
	<mvc:default-servlet-handler/>
	<!-- springmvc注解驅動 -->
	<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
           

最後再将ConversionService注入到WebDataBinder中:通過mvc的注解驅動

<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
           

3.1、@DateTimeFormat注解類型轉換器

方法二:String到java.util.Date轉換

我們也可以像上面。在類的Date類型的屬性上标上注解。就可以自動将String類型轉換成為Date資料

pattern屬性表示 日期的格式。最完成的格式是:yyyy-MM-dd hh:mm:ss

yyyy表示年份必須是4位

MM 表示月份必須是2位

dd 表示日期必須是2位

hh 表示小時,必須是2位

mm 表示分鐘,必須是2位

ss 表示秒鐘,必須是2位

SpringMVC詳解四、自帶标簽庫及自定義參數轉換器1、SpringMVC标簽庫(*用的不多*)2、自定義參數轉換器WebDataBinder3、(conversionService )自定義String到java.util.Date類型轉換器4、(Validate)較驗器----參數的有效性驗證Validate----Hibernate5、(bindingResult)自定義錯誤資訊的回顯

4、(Validate)較驗器----參數的有效性驗證Validate----Hibernate

在JavaEE6.0中,定義了很多的驗證規範。這些規範統稱為:JSR303驗證規範。

而這些規範的實作。我們使用現在業内比較認可的Hibernate-Validate驗證

@AssertTrue 用于boolean字段,該字段隻能為true  
@AssertFalse 該字段的值隻能為false
@CreditCardNumber 對信用卡号進行一個大緻的驗證
@DecimalMax 隻能小于或等于該值
@DecimalMin 隻能大于或等于該值
@Digits(integer=,fraction=) 檢查是否是一種數字的整數、分數,小數位數的數字
@Email 檢查是否是一個有效的email位址
@Future 檢查該字段的日期是否是屬于将來的日期
@Length(min=,max=) 檢查所屬的字段的長度是否在min和max之間,隻能用于字元串
@Max 該字段的值隻能小于或等于該值
@Min 該字段的值隻能大于或等于該值
@NotNull 不能為null
@NotBlank 不能為空,檢查時會将空格忽略
@NotEmpty 不能為空,這裡的空是指空字元串
@Null 檢查該字段為空
@Past 檢查該字段的日期是在過去
@Pattern(regex=,flag=) 被注釋的元素必須符合指定的正規表達式
@Range(min=,max=,message=) 被注釋的元素必須在合适的範圍内
@Size(min=, max=) 檢查該字段的size是否在min和max之間,可以是字元串、數組、集合、Map等
@URL(protocol=,host,port) 檢查是否是一個有效的URL,如果提供了protocol,host等,則該URL還需滿足提供的條件

使用Hiberante的驗證器較驗資料分以下步驟:

1、導入Hibernate驗證的jar包

classmate-0.8.0.jar

hibernate-validator-5.0.0.CR2.jar

hibernate-validator-annotation-processor-5.0.0.CR2.jar

jboss-logging-3.1.1.GA.jar

validation-api-1.1.0.CR1.jar

2、在實體bean對象的屬性上使用較驗的注解

public class Person {
	private Integer id;
	/**
	 * @NotNull表示驗證目前name屬性不能為null值<br/>
	 * @Length(min = 5, max = 12)表示驗證name屬性最小5位,最大12位
	 */
	@NotNull
	@Length(min = 5, max = 12)
	private String name;
	/**
	 * @Past 表示日期的值必須是過去的時間
	 */
	@Past
	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private Date birthDate;
	/**
	 * @Email 表示目前email屬性必須是合法的郵箱格式
	 */
	@Email
	private String email;
	/**
	 * @Max(value = 100) 表示目前salary的值不能大于100
	 */
	@Max(value = 100)
	private BigDecimal salary;
           

3、在Controller的方法參數上,給需要驗證的bean對象。添加驗證注解@Valid,以及在驗證對象後跟一個BindingResult 對象用于接收驗證的錯誤資訊

/**
	 * @Valid Person [email protected]表示要驗證目前這個person對象的資料<br/>
	 * BindingResult personBindingResult用來接收前面一個pojo對象驗證的錯誤資訊。
	 */
	@RequestMapping(value = "/addPerson")
	public String addPerson(@Valid Person person,
			BindingResult personBindingResult) {
		// 判斷輸入的資料是否有錯誤,
		if (personBindingResult.hasErrors()) {
			System.out.println("*********************************************");
			System.out.println( personBindingResult.getAllErrors() );
			System.out.println("*********************************************");
			return "addPerson";
		}
		System.out.println("添加使用者【" + person + "】到資料庫");
		return "redirect:/index.jsp";
	}
           

4、在SpringMVC的form表單字段後,使用<form:errors path="字段名" />輸出對應字段的錯誤資訊

<body>
		<!-- 
			springMVC的标簽form标簽可以關聯Request域中bean對象
			我們在隐含模型中儲存的key值。也一定要跟form:form标簽中的modelAttribute值對應上。
		 -->
		這裡是添加使用者頁面
		<form:form action="${ pageContext.request.contextPath }/addPerson" method="delete" 
			modelAttribute="person">
		name:<form:input path="name"/><form:errors path="name" /><br/>
		birthDate:<form:input path="birthDate"/><form:errors path="birthDate" /><br/>
		email:<form:input path="email"/><form:errors path="email" /><br/>
		salary:<form:input path="salary"/><form:errors path="salary" /><br/>	
		<input type="submit" />		
		</form:form>
	</body>
           

5、(bindingResult)自定義錯誤資訊的回顯

5.1、錯誤消息規則:

這是校驗錯誤的key規則:

格式1: Pattern.bean.property

說明: 校驗格式.隐含模型包.屬性名

示例:Email.person.email------------person對象的email屬性驗證Email格式失敗

格式2: Pattern.property

說明: 校驗格式.屬性名

示例:Email.email-----------任何對象的email屬性驗證Email格式失敗

格式3: Pattern.javaType

說明: 校驗格式.字段資料類型

示例:Email.java.lang.String-----------任何String類型的屬性驗證Email格式失敗

key4: Pattern

說明: 校驗格式

示例:Email-----------校驗Email格式失敗

參數轉換失敗的key規則:

格式1: typeMismatch.bean.property

說明: 類型不比對.隐含模型名.屬性名

示例:typeMismatch.person.birthDate-----------person對象的birthDate屬性轉換失敗

格式2: typeMismatch.property

說明: 類型不比對.屬性名

示例:typeMismach.birthDate-----------任何對象的birthDate屬性轉換失敗

格式3: typeMismatch.javaType

說明: 類型不比對.字段資料類型

示例:typeMismach.java.util.Date ----------- Java.util.Date類型轉換失敗

格式4: typeMismatch

說明: 類型不比對

示例:typeMismach-----------字段類型轉換失敗

5.2、在源碼目錄下配置錯誤資訊的屬性配置檔案

SpringMVC詳解四、自帶标簽庫及自定義參數轉換器1、SpringMVC标簽庫(*用的不多*)2、自定義參數轉換器WebDataBinder3、(conversionService )自定義String到java.util.Date類型轉換器4、(Validate)較驗器----參數的有效性驗證Validate----Hibernate5、(bindingResult)自定義錯誤資訊的回顯

validate.properties屬性配置檔案的内容如下:

Email.person.email=\u81EA\u5B9A\u4E49-\u90AE\u7BB1\u683C\u5F0F\u4E0D\u5408\u6CD5
NotNull=\u81EA\u5B9A\u4E49-\u503C\u4E0D\u80FD\u4E3A\u7A7A
Length.name=\u81EA\u5B9A\u4E49-\u957F\u5EA6\u5FC5\u987B\u4E3A 5 \u5230 12 \u4F4D
Past=\u81EA\u5B9A\u4E49-\u65F6\u95F4\u5FC5\u987B\u662F\u8FC7\u53BB\u7684\u65F6\u95F4
Max=\u81EA\u5B9A\u4E49-\u503C\u4E0D\u80FD\u5927\u4E8E 100
typeMismatch=\u81EA\u5B9A\u4E49-\u4E0D\u8981\u968F\u4FBF\u8F93\u5165
           

輸入的漢字會立刻轉換成16進制(有點小神秘~_`~)

占位符的使用:

{0}表示第一個傳入的參數。 {0}第一個參數固定是驗證的屬性名

Length.name=\u81EA\u5B9A\u4E49-\u957F\u5EA6\u5FC5\u987B\u4E3A {0} \u5230 12 \u4F4D
Max=\u81EA\u5B9A\u4E49-\u503C\u4E0D\u80FD\u5927\u4E8E {0}
           

5.3、在Spring中配置如下:

<!-- 告訴Spring容器,去加載自定義的錯誤資訊 -->
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="validate" />
	</bean>
           

 SpringMVC詳解三、Restful風格及基于Restful的CRUD

Jar包下載下傳

繼續閱讀