Spring MVC之处理方法的数据绑定

  1. 数据绑定流程 Spring MVC 通过反射机制对目标处理方法的入参签名进行分析,将请求消息绑定到处理方法的入参中。数据绑定的核心部件是DataBinder,如下所示 输入图片说明

Spring MVC 主框架将ServletRequest 对象及处理方法的入参对象实例传递给DataBinder,DataBinder调用装配在Spring Web上下文中的ConversionService组件进行数据类型转换、数据格式化,将ServletRequest 中的消息填充到入参对象中,然后再调用Validator对已经绑定了请求消息数据的入参对象进行数据合法性校验,并最终生成数据绑定结果BindingResult对象。BindingResult包含了已经完成数据绑定的入参对象,还包含相应的校验错误对象,Spring MVC抽取BindingResult中的入参对象及校验错误对象,将他们赋给处理方法相应的入参中。

  1. 数据转换 Spring MVC中使用Convertion Service 假设处理方法有一个User类型的入参,我们希望将一个请求参数字符串直接转换韩为User对象,该字符串的格式为<userName>:<password>:<realName>
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.xml

<?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 :注册全局的自定义编辑器


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......

<bean class="org.springframework.web.servlet.nvc.annotation.AnnotationMethodHanderAdapter">
    <property name="webBindingInitializer">
        <bean class="com.wananli.web.MyBindingInitializer"/>
    </property>
</bean>
  1. 数据格式化 注解驱动格式化实例

    web.xml



<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.java



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.java

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>
  1. 数据校验 bean.xml


<!-- 默认的注解映射的支持 -->  
    <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>

转载于:https://my.oschina.net/u/3778090/blog/1619113

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值