网页设计网站维护,网址在线生成二维码,学校网站用什么模板好,专业的医疗行业网站模板spring 类型转换器以下是一些需要类型转换的简单情况#xff1a; 情况1。 为了帮助简化bean配置#xff0c;Spring支持属性值与文本值之间的转换。 每个属性编辑器仅设计用于某些类型的属性。 为了使用它们#xff0c;我们必须在Spring容器中注册它们。 案例2。 同样… spring 类型转换器 以下是一些需要类型转换的简单情况 情况1。 为了帮助简化bean配置Spring支持属性值与文本值之间的转换。 每个属性编辑器仅设计用于某些类型的属性。 为了使用它们我们必须在Spring容器中注册它们。 案例2。 同样在使用Spring MVC时控制器会将表单字段值绑定到对象的属性。 假设对象是由另一个对象组成的则MVC控制器无法自动将值分配给内部自定义类型对象因为表单中的所有值都作为文本值输入。 Spring容器将把文本值转换为原始类型而不转换为自定义类型对象。 为此我们必须在MVC流中初始化自定义编辑器。 本文将讨论实现自定义类型对象的转换器的各种方法。 为了详细说明这些让我们考虑以下用例。 在该示例中我想模拟游戏场地预订系统。 所以这是我的领域对象 public class Reservation {public String playGround;public Date dateToReserve;public int hour;public Player captain;public SportType sportType;public Reservation(String playGround, Date date, int hour, Player captain, SportType sportType) {this.playGround playGround;this.dateToReserve date;this.hour hour;this.captain captain;this.sportType sportType;}/*** Getters and Setters*/
}public class Player {private String name;private String phone;/*** Getters and Setters*/}public class SportType {public static final SportType TENNIS new SportType(1, Tennis);public static final SportType SOCCER new SportType(2, Soccer);private int id;private String name;public SportType(int id, String name) {this.id id;this.name name;}public static IterableSportType list(){return Arrays.asList(TENNIS, SOCCER);}public static SportType getSport(int id){for(SportType sportType : list()){if(sportType.getId() id){return sportType;}}return null;}/*** Getters and Setters*/
} 这是案例1的示例假设我们要定义一个预留bean这是我们的方法 bean iddummyReservation classcom.pramati.model.Reservationproperty nameplayGround valueSoccer Court #1/property namedateToReserve value11-11-2011/property namehour value15/property namecaptainbean classcom.pramati.model.Playerproperty namename valuePrasanth/property namephone value92131233124//bean/propertyproperty namesportTypeproperty nameid value1/property namename valueTENNIS//property
/bean 这个bean的定义很冗长。 如果定义看起来像这样它本来可以表现得更好 bean iddummyReservation classcom.pramati.model.Reservationproperty nameplayGround valueSoccer Court #1/property namedateToReserve value11-11-2011/property namehour value15/property namecaptain valuePrasanth,92131233124/property namesportType value1,TENNIS/
/bean 为此我们应该告诉Spring在定义bean的过程中使用自定义转换器。 这是案例2的示例假设我的应用程序中有一个JSP它允许用户在一天的特定时间预订游乐场。 % page languagejava contentTypetext/html; charsetISO-8859-1 pageEncodingISO-8859-1%
% taglib prefixform urihttp://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-equivContent-Type contenttext/html; charsetISO-8859-1
titleReservation Form/title
style typetext/css
.error {color: #ff0000;font-weight: bold;
}
/style
/head
bodyform:form methodpost modelAttributereservationtabletrthCourt Name/thtdform:input pathcourtName //td/trtrthReservation Date/thtdform:input pathdate //td/trtrthHour/thtdform:input pathhour //td/trtrthPlayer Name/thtdform:input pathplayer.name //td/trtrthPlayer Contact Number/thtdform:input pathplayer.phone //td/trtrthSport Type/thtdform:select pathsportType items${sportTypes}itemLabelname itemValueid //td/trtrtd colspan3input typesubmit nameSubmit //td/tr/table/form:form
/body
/html 这是对应的MVC控制器 Controller
RequestMapping
SessionAttributes(reservation)
public class ReservationFormController {Autowiredprivate ReservationService reservationService;ModelAttribute(sportTypes)public IterableSportType getSportTypes(){return SportType.list();}RequestMapping(value/reservationForm/{captainName}, methodRequestMethod.GET)public String initForm(Model model, PathVariable String captainName){Reservation reservation new Reservation();reservation.setPlayer(new Player(captainName, null));reservation.setSportType(SportType.TENNIS);model.addAttribute(reservation, reservation);return reservationForm;}RequestMapping(value/reservationForm/{captainName},methodRequestMethod.POST)public String reserve(Valid Reservation reservation, BindingResult bindingResult, SessionStatus sessionStatus){validator.validate(reservation, bindingResult);if(bindingResult.hasErrors()){return /reservationForm;} else{reservationService.make(reservation);sessionStatus.setComplete();return redirect:../reservationSuccess;}}
} 现在您可以看到在JSP中我们将表单字段绑定到Reservation对象modelAttribute “ reservation”。 该对象由传递给视图的控制器在initForm方法中保留在模型中。 现在当我们提交表单时Spring会引发一条验证消息指出无法将字段值转换为类型Player和SportType。 为此我们必须定义自定义转换器并将其注入Spring MVC流中。 现在的问题是如何定义自定义转换器 Spring提供了两种支持这些自定义转换器的方式 解决方案1使用PropertyEditors 解决方案2使用转换器 使用PropertyEditor PropertyEditorSupport实现PropertyEditor接口是用于帮助构建PropertyEditor的支持类。 public class SportTypeEditorSupport extends PropertyEditorSupport {/*** Sets the property value by parsing a given String. May raise* java.lang.IllegalArgumentException if either the String is* badly formatted or if this kind of property cant be expressed* as text.** param text The string to be parsed.*/Overridepublic void setAsText(String text) throws IllegalArgumentException {try{SportType sportType SportType.getSport(Integer.parseInt(text));setValue(sportType);// setValue stores the custom type Object into a instance variable in PropertyEditorSupport.}catch(NumberFormatException nfe){throw new RuntimeException(nfe.getMessage());}}/*** Gets the property value as a string suitable for presentation* to a human to edit.** return The property value as a string suitable for presentation* to a human to edit.* p Returns null is the value cant be expressed as a string.* p If a non-null value is returned, then the PropertyEditor should* be prepared to parse that string back in setAsText().*/Overridepublic String getAsText() {SportType sportType (SportType)getValue();return Integer.toString(sportType.getId());}
} 现在在PropertyEditorRegistry中注册自定义编辑器。 PropertyEditorRegistrar在PropertyEditorRegistry中注册自定义编辑器。 这是您的操作方式 import java.text.SimpleDateFormat;
import java.util.Date;import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor;import com.pramati.model.SportType;public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {Overridepublic void registerCustomEditors(PropertyEditorRegistry registry) {registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(dd-MM-yyyy), true));registry.registerCustomEditor(SportType.class, new SportTypeEditorSupport());}
} CustomEditorConfigurer被实现为Bean工厂后处理器您可以在实例化任何Bean之前注册自定义属性编辑器。 为此我们将PropertyEditorRegistry与CustomEditorConfigurer关联。 bean idcustomPropertyEditorRegistrar classcom.pramati.spring.mvc.CustomPropertyEditorRegistrar/bean classorg.springframework.beans.factory.config.CustomEditorConfigurerproperty namepropertyEditorRegistrarslistref beancustomPropertyEditorRegistrar//list/property
/bean 现在当Spring容器看到此信息时 property namecaptain valuePrasanth,92131233124/ Spring自动将指定的值转换为Player对象。 但是此配置对于Spring MVC流还不够。 控制器仍然会抱怨类型不兼容因为它期望一个Player对象在获取String的地方。 为了将表单字段值解释为自定义类型对象我们必须进行很少的MVC配置更改。 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;public class CustomWebBindingInitializer implements WebBindingInitializer {Autowiredprivate CustomPropertyEditorRegistrar customPropertyEditorRegistrar;Overridepublic void initBinder(WebDataBinder binder, WebRequest request) {customPropertyEditorRegistrar.registerCustomEditors(binder);}
} 现在手动删除并定义必要的bean因为我们需要将WebBindingInitializer注入RequestMappingHandlerAdapter bean classorg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping/bean classorg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapterproperty namewebBindingInitializerbean classcom.pramati.spring.mvc.CustomWebBindingInitializer//property
/bean 现在控制器会自动将String转换为必要的自定义类型对象。 请注意我们必须进行单独的配置更改以简化Spring MVC中的bean配置和表单字段的类型转换。 同样值得指出的是在扩展PropertyEditorSupport时我们将自定义类型对象存储在实例变量中因此使用PropertyEditors并不是线程安全的。 为了克服这些问题Spring 3.0引入了转换器和格式化程序的概念。 使用转换器 转换器组件用于将一种类型转换为另一种类型并通过强制将所有此类与转换相关的代码放在一个位置来提供更清晰的分隔。 Spring已经支持常用类型的内置转换器并且该框架可扩展性足以编写自定义转换器。 Spring Formatters进入图片以根据呈现数据的显示来格式化数据。 在考虑编写适合特定业务需求的自定义转换器之前总是有必要先查看详尽的预制转换器列表。 有关查看预建转换器的列表请参见org.springframework.core.convert.support软件包。 回到我们的用例让我们实现String到SportType转换器 import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import com.pramati.model.SportType;public class StringToSportTypeConverter implements ConverterString, SportType {Overridepublic SportType convert(String sportIdStr) {int sportId -1;try{sportId Integer.parseInt(sportIdStr);} catch (NumberFormatException e) {throw new ConversionFailedException(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(SportType.class), sportIdStr, null);}SportType sportType SportType.getSport(sportId);return sportType;}} 现在在ConversionService中注册它并将其与SpringMVC流链接 mvc:annotation-driven conversion-serviceconversionService/bean idconversionService classorg.springframework.context.support.ConversionServiceFactoryBean property nameconverterssetbean classcom.pramati.type.converters.StringToSportTypeConverter/bean classcom.pramati.type.converters.StringToDateConverter/bean classcom.pramati.type.converters.StringToPlayerConverter//set/property
/bean 如果您使用的是自定义bean声明而不是‹mvcannotation-driven /›则可以使用以下方法 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;public class CustomWebBindingInitializer implements WebBindingInitializer {Autowiredprivate ConversionService conversionService;Overridepublic void initBinder(WebDataBinder binder, WebRequest request) {binder.setConversionService(conversionService);}} 现在将WebBindingInitializer注入RequestMappingHandlerAdapter。 bean classorg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping/
bean classorg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapterproperty namewebBindingInitializerbean classcom.pramati.spring.mvc.CustomWebBindingInitializer//property
/bean 单独注册ConversionService将有助于简化bean配置案例1。 为了使案例2正常工作我们必须在Spring MVC流中注册ConversionService。 请注意这种类型转换方式也是线程安全的。 同样除了使Converters / PropertEditor对应用程序中的所有控制器都可用之外我们还可以基于每个控制器启用它们。 这是您的操作方式。 删除上面指定的通用配置并在控制器类中引入InitBinder如下所示 Controller
RequestMapping
SessionAttributes(reservation)
public class ReservationFormController {private ReservationService reservationService;private ReservationValidator validator;Autowiredpublic ReservationFormController(ReservationService reservationService, ReservationValidator validator){this.reservationService reservationService;this.validator validator;}Autowiredprivate ConversionService conversionService;InitBinderprotected void initBinder(ServletRequestDataBinder binder) {binder.setConversionService(conversionService);}/*InitBinderprotected void initBinder(ServletRequestDataBinder binder) {binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(dd-MM-yyyy), true));binder.registerCustomEditor(SportType.class, new SportTypeEditorSupport(reservationService));}*//*Autowiredprivate PropertyEditorRegistrar propertyEditorRegistrar;InitBinderprotected void initBinder(ServletRequestDataBinder binder) {propertyEditorRegistrar.registerCustomEditors(binder);}*/ModelAttribute(sportTypes)public IterableSportType getSportTypes(){return SportType.list();}RequestMapping(value/reservationForm/{userName}, methodRequestMethod.GET)public String initForm(Model model, PathVariable String userName){Reservation reservation new Reservation();reservation.setPlayer(new Player(userName, null));reservation.setSportType(SportType.TENNIS);model.addAttribute(reservation, reservation);return reservationForm;}RequestMapping(value/reservationForm/{userName},methodRequestMethod.POST)public String reserve(Valid Reservation reservation, BindingResult bindingResult, SessionStatus sessionStatus){validator.validate(reservation, bindingResult);if(bindingResult.hasErrors()){return /reservationForm;} else{reservationService.make(reservation);sessionStatus.setComplete();return redirect:../reservationSuccess;}}RequestMapping(/reservationSuccess)public void success(){}
} 因此如果您看到上面的代码您会注意到在使用PropertyEditor而不是转换器的地方注释的代码。 因此在两种实现方式中都可以使用基于控制器启用类型转换器的功能。 参考 prasanthnath博客上的JCG合作伙伴 Prasanth Gullapalli 在Spring中进行了类型转换 。 翻译自: https://www.javacodegeeks.com/2013/11/type-conversion-in-spring-2.htmlspring 类型转换器