Spring MVC 主框架將ServletRequest 對象及處理方法的入參對象實例傳遞給DataBinder,DataBinder調用裝配在Spring Web上下文中的ConversionService組件進行數據類型轉換、數據格式化,將ServletRequest 中的消息填充到入參對象中,而後再調用Validator對已經綁定了請求消息數據的入參對象進行數據合法性校驗,並最終生成數據綁定結果BindingResult對象。BindingResult包含了已經完成數據綁定的入參對象,還包含相應的校驗錯誤對象,Spring MVC抽取BindingResult中的入參對象及校驗錯誤對象,將他們賦給處理方法相應的入參中。html
StringToUserConverter.java pacakage com.wanali.domain; import org.springframework.core.convert.converter.Converter; public class StringToUserConverter implements Converter<String,User>{ public user convert(String source){ User user = new User(); if(source!=null){ String[] items=source.split(":"); user.setUserName(items[0]); user.setPassWord(items[1]); user.setRealName(items[2]); } return user } }
接下來將其安裝到springmvc上下文中前端
spring-servlet.xmljava
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven conversion-service="convertionService"></mvc:annotation-driven> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.wanalidomain.StringToUserConverter" /> </list> </property> </bean>
----使用@initBinder和WebBindingInitializer裝配自定義編輯器 UserController.java
package com.wanali.web; import org.apache.catalina.User; import org.apache.catalina.startup.WebAnnotationSet; 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; [@Controller](https://my.oschina.net/u/1774615) @RequestMapping("/user") public class UserController { @InitBinder public void initBinder(WebDataBinder binder ){ binder.registerCustomEditor(User.class, new UserEditor()); } }
MyBindingInitializer.java :註冊全局的自定義編輯器web
package com.wanali.web; import org.apache.catalina.User; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.context.request.WebRequest; public class MyBindingInitializer implements WebBindingInitializer{ public void initBinder(WebDataBinder binder,WebRequest request){ binder.registerCustomEditor(User.class, new UserEditor()); } }
接下來,須要在web上下文中經過AnnotationHanderAdapter裝配MyBindingInitializer......spring
<bean class="org.springframework.web.servlet.nvc.annotation.AnnotationMethodHanderAdapter"> <property name="webBindingInitializer"> <bean class="com.wananli.web.MyBindingInitializer"/> </property> </bean>
數據格式化 註解驅動格式化實例apache
web.xmlspring-mvc
<span style="font-family: Courier New; font-size: 14px"><!-- 配置springmvc的前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></span>
編寫一個實體類 User.javamvc
import java.io.Serializable; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; public class User implements Serializable{ //日期類型 @DateTimeFormat(pattern="yyyy-MM-dd") private Date birthday; //正常數據類型 @NumberFormat(style=Style.NUMBER,pattern="#,###") private int total; //百分數類型 @NumberFormat(style=Style.PERCENT) private double discount; //貨幣類型 @NumberFormat(style=Style.CURRENCY) private double money; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } }
編寫一個controller UserController.javaapp
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.dj.pojo.User; @Controller public class UserController { /** * 動態跳轉頁面 * @param pagename * @return */ @RequestMapping(value="/{pagename}") public String index(@PathVariable String pagename){ return pagename; } /** * 跳轉到顯示格式化後數據的頁面 * @param user * @param model * @return */ @RequestMapping(value="/test",method=RequestMethod.POST) public String test(@ModelAttribute User user,Model model){ model.addAttribute("user",user); return "success"; } }
編寫一個測試表單頁面 register.jsp框架
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="test" method="post"> 日期類型:<input type="text" id="birthday" name="birthday"/><br> 整數類型:<input type="text" id="total" name="total"/><br> 百分數類型:<input type="text" id="discount" name="discount"/><br> 貨幣類型:<input type="text" id="money" name="money"/><br> <input type="submit" value="提交"/> </form> </body> </html>
格式化以後的格式 success.jsp
<form:form modelAttribute="user" method="post" action=""> 日期類型:<form:input path="birthday"/><br> 整數類型:<form:input path="total"/><br> 百分數類型:<form:input path="discount"/><br> 貨幣類型:<form:input path="money"/><br> </form:form> 配置文件 speingMVC-servlet.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 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-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- spring能夠自動去掃描base-package下面的包或者子包下面的java類 若是掃描到有spring相關注解的類,則吧這個類註冊爲spring的bean --> <context:component-scan base-package="com.dj.controller" /> <!-- 默認裝配 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 視圖解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前綴 --> <property name="prefix"> <value>/</value> </property> <!-- 後綴 --> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
<!-- 默認的註解映射的支持 --> <mvc:annotation-driven validator="validator" conversion-service="conversion-service" /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <!--不設置則默認爲classpath下的 ValidationMessages.properties --> <property name="validationMessageSource" ref="validatemessageSource"/> </bean> <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /> <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:validatemessages"/> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean>
ValidateController .java
package com.wanali.web; import java.security.NoSuchAlgorithmException; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.demo.web.models.ValidateModel; public class ValidateController { @Controller @RequestMapping(value = "/validate") public class ValidateController { @RequestMapping(value="/test", method = {RequestMethod.GET}) public String test(Model model){ if(!model.containsAttribute("contentModel")){ model.addAttribute("contentModel", new ValidateModel()); } return "validatetest"; } @RequestMapping(value="/test", method = {RequestMethod.POST}) public String test(Model model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) throws NoSuchAlgorithmException{ //若是有驗證錯誤 返回到form頁面 if(result.hasErrors()) return test(model); return "validatesuccess"; } } }
在註解驗證消息所在的文件即validatemessages.properties文件中添加如下內容:
name.not.empty=\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u3002 age.not.inrange=\u5E74\u9F84\u8D85\u51FA\u8303\u56F4\u3002 email.not.correct=\u90AE\u7BB1\u5730\u5740\u4E0D\u6B63\u786E\u3002 email.not.empty=\u7535\u5B50\u90AE\u4EF6\u4E0D\u80FD\u60DF\u6050\u3002
在views文件夾中添加validatetest.jsp和validatesuccess.jsp兩個視圖,內容分別以下
validatetest.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form:form modelAttribute="contentModel" method="post"> <form:errors path="*"></form:errors><br/><br/> name:<form:input path="name" /><br/> <form:errors path="name"></form:errors><br/> age:<form:input path="age" /><br/> <form:errors path="age"></form:errors><br/> email:<form:input path="email" /><br/> <form:errors path="email"></form:errors><br/> <input type="submit" value="Submit" /> </form:form> </body> </html>
validatesuccess.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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> 驗證成功! </body> </html>