{"id":18848,"date":"2013-11-11T16:00:31","date_gmt":"2013-11-11T14:00:31","guid":{"rendered":"http:\/\/www.javacodegeeks.com\/?p=18848"},"modified":"2013-11-11T13:02:09","modified_gmt":"2013-11-11T11:02:09","slug":"type-conversion-in-spring-2","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html","title":{"rendered":"Type Conversion in Spring"},"content":{"rendered":"<p>Here are few straight cases where we need type conversion:<br \/>\n<strong>Case #1.<\/strong> To help simplifying bean configurations, Spring supports conversion of property values to and from text values. Each property editor is designed for a property of certain type only. And to put them in use, we have to register them with Spring container.<br \/>\n<strong>Case #2.<\/strong> Also when using Spring MVC, controllers binds the form field values to properties of an object. Suppose the object is composed with another object, then the MVC controller cannot automatically assign values to the internal custom type object as all the values in the form are inputted as text values. Spring container will take of conversion of text values to primitive types but not to custom type objects. For this to be taken care, we have to initialize custom editors in the MVC flow.<\/p>\n<p>This article will discuss the various ways of implementing the converters for custom type objects. To elaborate more on these, let us consider the following use case. In the example, I would like to simulate play ground reservation system. So here are my domain objects:<\/p>\n<pre class=\" brush:java\">public class Reservation {\r\n\r\n\tpublic String playGround;\r\n\tpublic Date dateToReserve;\r\n\tpublic int hour;\r\n\tpublic Player captain;\r\n\tpublic SportType sportType;\r\n\r\n\tpublic Reservation(String playGround, Date date, int hour, Player captain, SportType sportType) {\r\n\t\tthis.playGround = playGround;\r\n\t\tthis.dateToReserve = date;\r\n\t\tthis.hour = hour;\r\n\t\tthis.captain = captain;\r\n\t\tthis.sportType = sportType;\r\n\t}\r\n\r\n\t\/**\r\n\t * Getters and Setters\r\n\t *\/\r\n}\r\n\r\npublic class Player {\r\n\r\n\tprivate String name;\r\n\tprivate String phone;\r\n\t\/**\r\n\t * Getters and Setters\r\n\t *\/\r\n\r\n}\r\n\r\npublic class SportType {\r\n\r\n\tpublic static final SportType TENNIS = new SportType(1, \"Tennis\");\r\n\tpublic static final SportType SOCCER = new SportType(2, \"Soccer\");\r\n\r\n\tprivate int id;\r\n\tprivate String name;\r\n\r\n\tpublic SportType(int id, String name) {\r\n\t\tthis.id = id;\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\tpublic static Iterable&lt;SportType&gt; list(){\r\n\t\treturn Arrays.asList(TENNIS, SOCCER);\r\n\t}\r\n\r\n\tpublic static SportType getSport(int id){\r\n\t\tfor(SportType sportType : list()){\r\n\t\t\tif(sportType.getId() == id){\r\n\t\t\t\treturn sportType;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t\/**\r\n\t * Getters and Setters\r\n\t *\/\r\n}<\/pre>\n<p><strong>Here is an example of Case #1:<\/strong> Suppose we want to define a reservation bean, here is how we do it:<\/p>\n<pre class=\" brush:xml\">&lt;bean id=\"dummyReservation\" class=\"com.pramati.model.Reservation\"&gt;\r\n\t&lt;property name=\"playGround\" value=\"Soccer Court #1\"\/&gt;\r\n\t&lt;property name=\"dateToReserve\" value=\"11-11-2011\"\/&gt;\r\n\t&lt;property name=\"hour\" value=\"15\"\/&gt;\r\n\t&lt;property name=\"captain\"&gt;\r\n\t\t&lt;bean class=\"com.pramati.model.Player\"&gt;\r\n\t\t\t&lt;property name=\"name\" value=\"Prasanth\"\/&gt;\r\n\t\t\t&lt;property name=\"phone\" value=\"92131233124\"\/&gt;\r\n\t\t&lt;\/bean&gt;\r\n\t&lt;\/property&gt;\r\n\t&lt;property name=\"sportType\"&gt;\r\n\t\t&lt;property name=\"id\" value=\"1\"\/&gt;\r\n\t\t&lt;property name=\"name\" value=\"TENNIS\"\/&gt;\r\n\t&lt;\/property&gt;\r\n&lt;\/bean&gt;<\/pre>\n<p>This bean definition is pretty verbose. It could have been more presentable if the definition looks somewhat like this:<\/p>\n<pre class=\" brush:xml\">&lt;bean id=\"dummyReservation\" class=\"com.pramati.model.Reservation\"&gt;\r\n\t&lt;property name=\"playGround\" value=\"Soccer Court #1\"\/&gt;\r\n\t&lt;property name=\"dateToReserve\" value=\"11-11-2011\"\/&gt;\r\n\t&lt;property name=\"hour\" value=\"15\"\/&gt;\r\n\t&lt;property name=\"captain\" value=\"Prasanth,92131233124\"\/&gt;\r\n\t&lt;property name=\"sportType\" value=\"1,TENNIS\"\/&gt;\r\n&lt;\/bean&gt;<\/pre>\n<p>For this to work, we should tell Spring to use the custom converters in the process of defining a bean.<\/p>\n<p><strong>Here is an example of Case #2:<\/strong> Suppose I have a JSP in my application which allows user to reserve the playground for a particular time of a day.<\/p>\n<pre class=\" brush:xml\">&lt;%@ page language=\"java\" contentType=\"text\/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%&gt;\r\n&lt;%@ taglib prefix=\"form\" uri=\"http:\/\/www.springframework.org\/tags\/form\"%&gt;\r\n&lt;!DOCTYPE html PUBLIC \"-\/\/W3C\/\/DTD HTML 4.01 Transitional\/\/EN\" \"http:\/\/www.w3.org\/TR\/html4\/loose.dtd\"&gt;\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;meta http-equiv=\"Content-Type\" content=\"text\/html; charset=ISO-8859-1\"&gt;\r\n&lt;title&gt;Reservation Form&lt;\/title&gt;\r\n&lt;style type=\"text\/css\"&gt;\r\n.error {\r\n\tcolor: #ff0000;\r\n\tfont-weight: bold;\r\n}\r\n&lt;\/style&gt;\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n\t&lt;form:form method=\"post\" modelAttribute=\"reservation\"&gt;\r\n\t\t&lt;table&gt;\r\n\t\t\t&lt;tr&gt;\r\n\t\t\t\t&lt;th&gt;Court Name&lt;\/th&gt;\r\n\t\t\t\t&lt;td&gt;&lt;form:input path=\"courtName\" \/&gt;&lt;\/td&gt;\r\n\t\t\t&lt;\/tr&gt;\r\n\t\t\t&lt;tr&gt;\r\n\t\t\t\t&lt;th&gt;Reservation Date&lt;\/th&gt;\r\n\t\t\t\t&lt;td&gt;&lt;form:input path=\"date\" \/&gt;&lt;\/td&gt;\r\n\t\t\t&lt;\/tr&gt;\r\n\t\t\t&lt;tr&gt;\r\n\t\t\t\t&lt;th&gt;Hour&lt;\/th&gt;\r\n\t\t\t\t&lt;td&gt;&lt;form:input path=\"hour\" \/&gt;&lt;\/td&gt;\r\n\t\t\t&lt;\/tr&gt;\r\n\t\t\t&lt;tr&gt;\r\n\t\t\t\t&lt;th&gt;Player Name&lt;\/th&gt;\r\n\t\t\t\t&lt;td&gt;&lt;form:input path=\"player.name\" \/&gt;&lt;\/td&gt;\r\n\t\t\t&lt;\/tr&gt;\r\n\t\t\t&lt;tr&gt;\r\n\t\t\t\t&lt;th&gt;Player Contact Number&lt;\/th&gt;\r\n\t\t\t\t&lt;td&gt;&lt;form:input path=\"player.phone\" \/&gt;&lt;\/td&gt;\r\n\t\t\t&lt;\/tr&gt;\r\n\t\t\t&lt;tr&gt;\r\n\t\t\t\t&lt;th&gt;Sport Type&lt;\/th&gt;\r\n\t\t\t\t&lt;td&gt;&lt;form:select path=\"sportType\" items=\"${sportTypes}\"\r\n\t\t\t\t\t\titemLabel=\"name\" itemValue=\"id\" \/&gt;&lt;\/td&gt;\r\n\t\t\t&lt;\/tr&gt;\r\n\t\t\t&lt;tr&gt;\r\n\t\t\t\t&lt;td colspan=\"3\"&gt;&lt;input type=\"submit\" name=\"Submit\" \/&gt;&lt;\/td&gt;\r\n\t\t\t&lt;\/tr&gt;\r\n\t\t&lt;\/table&gt;\r\n\t&lt;\/form:form&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p>And here is the corresponding MVC controller:<\/p>\n<pre class=\" brush:java\">@Controller\r\n@RequestMapping\r\n@SessionAttributes(\"reservation\")\r\npublic class ReservationFormController {\r\n\r\n\t@Autowired\r\n\tprivate ReservationService reservationService;\r\n\r\n\t@ModelAttribute(\"sportTypes\")\r\n\tpublic Iterable&lt;SportType&gt; getSportTypes(){\r\n\t\treturn SportType.list();\r\n\t}\r\n\r\n\t@RequestMapping(value=\"\/reservationForm\/{captainName}\", method=RequestMethod.GET)\r\n\tpublic String initForm(Model model, @PathVariable String captainName){\r\n\t\tReservation reservation = new Reservation();\r\n\t\treservation.setPlayer(new Player(captainName, null));\r\n\t\treservation.setSportType(SportType.TENNIS);\r\n\t\tmodel.addAttribute(\"reservation\", reservation);\r\n\t\treturn \"reservationForm\";\r\n\t}\r\n\r\n\t@RequestMapping(value=\"\/reservationForm\/{captainName}\",method=RequestMethod.POST)\r\n\tpublic String reserve(@Valid Reservation reservation, BindingResult bindingResult, SessionStatus sessionStatus){\r\n\t\tvalidator.validate(reservation, bindingResult);\r\n\t\tif(bindingResult.hasErrors()){\r\n\t\t\treturn \"\/reservationForm\";\r\n\t\t} else{\r\n\t\t\treservationService.make(reservation);\r\n\t\t\tsessionStatus.setComplete();\r\n\t\t\treturn \"redirect:..\/reservationSuccess\";\r\n\t\t}\r\n\t}\r\n}<\/pre>\n<p>Now as you see, in the JSP we are tying the form fields to a Reservation object(modelAttribute=\u201dreservation\u201d). This object is kept in the model by the controller(in initForm() method) which gets passed to the view. Now when we submit the form, Spring throws a validation message saying that the field values can\u2019t be converted to types, Player and SportType. For this to work, we have to define the custom converters and inject them into the Spring MVC flow.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p>Now the question is how to define the custom converters? Spring provides two ways of supporting these custom converters:<\/p>\n<ul>\n<li><strong>Solution #1:<\/strong> Use PropertyEditors<\/li>\n<li><strong>Solution #2:<\/strong> Use Converters<\/li>\n<\/ul>\n<h2>Using PropertyEditor:<\/h2>\n<p>PropertyEditorSupport, implements PropertyEditor interface, is a support class to help build PropertyEditors.<\/p>\n<pre class=\" brush:java\">public class SportTypeEditorSupport extends PropertyEditorSupport {\r\n\r\n\t\/**\r\n     * Sets the property value by parsing a given String.  May raise\r\n     * java.lang.IllegalArgumentException if either the String is\r\n     * badly formatted or if this kind of property can't be expressed\r\n     * as text.\r\n     *\r\n     * @param text  The string to be parsed.\r\n     *\/\r\n\t@Override\r\n\tpublic void setAsText(String text) throws IllegalArgumentException {\r\n\t\ttry{\r\n\t\t\tSportType sportType = SportType.getSport(Integer.parseInt(text));\r\n\t\t\tsetValue(sportType);\/\/ setValue stores the custom type Object into a instance variable in PropertyEditorSupport.\r\n\t\t}\r\n\t\tcatch(NumberFormatException nfe){\r\n\t\t\tthrow new RuntimeException(nfe.getMessage());\r\n\t\t}\r\n\t}\r\n\r\n\t \/**\r\n     * Gets the property value as a string suitable for presentation\r\n     * to a human to edit.\r\n     *\r\n     * @return The property value as a string suitable for presentation\r\n     *       to a human to edit.\r\n     * &lt;p&gt;   Returns \"null\" is the value can't be expressed as a string.\r\n     * &lt;p&gt;   If a non-null value is returned, then the PropertyEditor should\r\n     *\t     be prepared to parse that string back in setAsText().\r\n     *\/\r\n\t@Override\r\n\tpublic String getAsText() {\r\n\t\tSportType sportType = (SportType)getValue();\r\n\t\treturn Integer.toString(sportType.getId());\r\n\t}\r\n}<\/pre>\n<p>Now register the custom editor in PropertyEditorRegistry. PropertyEditorRegistrar registers custom editors in PropertyEditorRegistry. Here is how you do it:<\/p>\n<pre class=\" brush:java\">import java.text.SimpleDateFormat;\r\nimport java.util.Date;\r\n\r\nimport org.springframework.beans.PropertyEditorRegistrar;\r\nimport org.springframework.beans.PropertyEditorRegistry;\r\nimport org.springframework.beans.propertyeditors.CustomDateEditor;\r\n\r\nimport com.pramati.model.SportType;\r\n\r\npublic class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {\r\n\t@Override\r\n\tpublic void registerCustomEditors(PropertyEditorRegistry registry) {\r\n\t\tregistry.registerCustomEditor(Date.class, new CustomDateEditor(\r\n\t\t\t\tnew SimpleDateFormat(\"dd-MM-yyyy\"), true));\r\n\t\tregistry.registerCustomEditor(SportType.class, new SportTypeEditorSupport());\r\n\t}\r\n}<\/pre>\n<p>The CustomEditorConfigurer is implemented as a bean factory post processor for you to register your custom property editors before any of the beans get instantiated. To do this, we associate PropertyEditorRegistry with CustomEditorConfigurer.<\/p>\n<pre class=\" brush:xml\">&lt;bean id=\"customPropertyEditorRegistrar\" class=\"com.pramati.spring.mvc.CustomPropertyEditorRegistrar\"\/&gt;\r\n\r\n&lt;bean class=\"org.springframework.beans.factory.config.CustomEditorConfigurer\"&gt;\r\n\t&lt;property name=\"propertyEditorRegistrars\"&gt;\r\n\t\t&lt;list&gt;\r\n\t\t\t&lt;ref bean=\"customPropertyEditorRegistrar\"\/&gt;\r\n\t\t&lt;\/list&gt;\r\n\t&lt;\/property&gt;\r\n&lt;\/bean&gt;<\/pre>\n<p>Now when Spring container sees this:<\/p>\n<pre class=\" brush:xml\">&lt;property name=\"captain\" value=\"Prasanth,92131233124\"\/&gt;<\/pre>\n<p>Spring automatically converts the value specified to Player object. But this configuration is not enough for Spring MVC flow. Controllers would still complain about incompatible types as it expects a Player object where as it gets a String. For the form field value to be interpreted as custom type object, we have to make few MVC configuration changes.<\/p>\n<pre class=\" brush:java\">import org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.core.convert.ConversionService;\r\nimport org.springframework.validation.Validator;\r\nimport org.springframework.web.bind.WebDataBinder;\r\nimport org.springframework.web.bind.support.WebBindingInitializer;\r\nimport org.springframework.web.context.request.WebRequest;\r\n\r\npublic class CustomWebBindingInitializer implements WebBindingInitializer {\r\n\t@Autowired\r\n\tprivate CustomPropertyEditorRegistrar customPropertyEditorRegistrar;\r\n\r\n\t@Override\r\n\tpublic void initBinder(WebDataBinder binder, WebRequest request) {\r\n\t\tcustomPropertyEditorRegistrar.registerCustomEditors(binder);\r\n\t}\r\n}<\/pre>\n<p>Now remove and define the necessary beans manually as we need to inject WebBindingInitializer into RequestMappingHandlerAdapter<\/p>\n<pre class=\" brush:xml\">&lt;bean class=\"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping\"\/&gt;\r\n\r\n&lt;bean class=\"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter\"&gt;\r\n\t&lt;property name=\"webBindingInitializer\"&gt;\r\n\t\t&lt;bean class=\"com.pramati.spring.mvc.CustomWebBindingInitializer\"\/&gt;\r\n\t&lt;\/property&gt;\r\n&lt;\/bean&gt;<\/pre>\n<p>Now controller automatically converts the String to the necessary custom type object. Note that we have to make separate configuration changes for simplifying bean configuration and type conversion of form fields in Spring MVC. Also it is worth pointing that when extending PropertyEditorSupport, we store the custom type object into the instance variable and hence using PropertyEditors is not thread safe. To overcome these problems, Spring 3.0 has introduced the concept of Converters and Formatters.<\/p>\n<h2>Using Converters:<\/h2>\n<p>Converter components are used for converting one type to another type and also to provide a cleaner separation by forcing to place all such conversion related code in one single place. Spring already supports built-in converters for the commonly used types and the framework is extensible enough for writing custom converters as well. Spring Formatters come into picture to format the data according to the display where it is rendered. It\u2019s always worthwhile to see the exhaustive list of pre-built converters before even thinking of writing a custom converter that suits for a particular business need. For seeing the list of prebuilt converters, see the package org.springframework.core.convert.support<\/p>\n<p>Coming back to our use case, let us implement String to SportType converter:<\/p>\n<pre class=\" brush:java\">import org.springframework.core.convert.ConversionFailedException;\r\nimport org.springframework.core.convert.TypeDescriptor;\r\nimport org.springframework.core.convert.converter.Converter;\r\nimport com.pramati.model.SportType;\r\n\r\npublic class StringToSportTypeConverter implements Converter&lt;String, SportType&gt; {\r\n\r\n\t@Override\r\n\tpublic SportType convert(String sportIdStr) {\r\n\t\tint sportId = -1;\r\n\t\ttry{\r\n\t\t\tsportId = Integer.parseInt(sportIdStr);\r\n\t\t} catch (NumberFormatException e) {\r\n\t\t\tthrow new ConversionFailedException(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(SportType.class), sportIdStr, null);\r\n\t\t}\r\n\r\n\t\tSportType sportType = SportType.getSport(sportId);\r\n\t\treturn sportType;\r\n\t}\r\n\r\n}<\/pre>\n<p>Now register this with ConversionService and link it with SpringMVC flow:<\/p>\n<pre class=\" brush:xml\">&lt;mvc:annotation-driven conversion-service=\"conversionService\"\/&gt;\r\n\r\n&lt;bean id=\"conversionService\" class=\"org.springframework.context.support.ConversionServiceFactoryBean\" &gt;\r\n\t&lt;property name=\"converters\"&gt;\r\n\t\t&lt;set&gt;\r\n\t\t\t&lt;bean class=\"com.pramati.type.converters.StringToSportTypeConverter\"\/&gt;\r\n\t\t\t&lt;bean class=\"com.pramati.type.converters.StringToDateConverter\"\/&gt;\r\n\t\t\t&lt;bean class=\"com.pramati.type.converters.StringToPlayerConverter\"\/&gt;\r\n\t\t&lt;\/set&gt;\r\n\t&lt;\/property&gt;\r\n&lt;\/bean&gt;<\/pre>\n<p>If you are using custom bean declarations instead of \u2039mvc:annotation-driven\/\u203a, here is the way to do it:<\/p>\n<pre class=\" brush:java\">import org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.core.convert.ConversionService;\r\nimport org.springframework.validation.Validator;\r\nimport org.springframework.web.bind.WebDataBinder;\r\nimport org.springframework.web.bind.support.WebBindingInitializer;\r\nimport org.springframework.web.context.request.WebRequest;\r\n\r\npublic class CustomWebBindingInitializer implements WebBindingInitializer {\r\n\r\n\t@Autowired\r\n\tprivate ConversionService conversionService;\r\n\r\n\t@Override\r\n\tpublic void initBinder(WebDataBinder binder, WebRequest request) {\r\n\t\tbinder.setConversionService(conversionService);\r\n\t}\r\n\r\n}<\/pre>\n<p>Now inject WebBindingInitializer into RequestMappingHandlerAdapter.<\/p>\n<pre class=\" brush:xml\">&lt;bean class=\"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping\"\/&gt;\r\n&lt;bean class=\"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter\"&gt;\r\n\t&lt;property name=\"webBindingInitializer\"&gt;\r\n\t\t&lt;bean class=\"com.pramati.spring.mvc.CustomWebBindingInitializer\"\/&gt;\r\n\t&lt;\/property&gt;\r\n&lt;\/bean&gt;<\/pre>\n<p>Registering ConversionService alone will take care of simplifying bean configuration(Case #1). For Case #2 to work, we have to register ConversionService with the Spring MVC flow. And note that this way of doing type conversion is also thread safe.<\/p>\n<p>Also instead of making Converters\/PropertEditors available to all the controllers in the application, we can enable them on a per-controller-basis. Here is how you do it. Remove the above specified generic configuration and introduce @InitBinder in the controller class like this:<\/p>\n<pre class=\" brush:java\">@Controller\r\n@RequestMapping\r\n@SessionAttributes(\"reservation\")\r\npublic class ReservationFormController {\r\n\r\n\tprivate ReservationService reservationService;\r\n\tprivate ReservationValidator validator;\r\n\r\n\t@Autowired\r\n\tpublic ReservationFormController(ReservationService reservationService, ReservationValidator validator){\r\n\t\tthis.reservationService = reservationService;\r\n\t\tthis.validator = validator;\r\n\t}\r\n\r\n\t@Autowired\r\n\tprivate ConversionService conversionService;\r\n\t@InitBinder\r\n\tprotected void initBinder(ServletRequestDataBinder binder) {\r\n\t\tbinder.setConversionService(conversionService);\r\n\t}\r\n\r\n\t\/*@InitBinder\r\n\tprotected void initBinder(ServletRequestDataBinder binder) {\r\n\t\tbinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(\"dd-MM-yyyy\"), true));\r\n\t\tbinder.registerCustomEditor(SportType.class, new SportTypeEditorSupport(reservationService));\r\n\t}*\/\r\n\r\n\t\/*@Autowired\r\n\tprivate PropertyEditorRegistrar propertyEditorRegistrar;\r\n\t@InitBinder\r\n\tprotected void initBinder(ServletRequestDataBinder binder) {\r\n\t\tpropertyEditorRegistrar.registerCustomEditors(binder);\r\n\t}*\/\r\n\r\n\t@ModelAttribute(\"sportTypes\")\r\n\tpublic Iterable&lt;SportType&gt; getSportTypes(){\r\n\t\treturn SportType.list();\r\n\t}\r\n\r\n\t@RequestMapping(value=\"\/reservationForm\/{userName}\", method=RequestMethod.GET)\r\n\tpublic String initForm(Model model, @PathVariable String userName){\r\n\t\tReservation reservation = new Reservation();\r\n\t\treservation.setPlayer(new Player(userName, null));\r\n\t\treservation.setSportType(SportType.TENNIS);\r\n\t\tmodel.addAttribute(\"reservation\", reservation);\r\n\t\treturn \"reservationForm\";\r\n\t}\r\n\r\n\t@RequestMapping(value=\"\/reservationForm\/{userName}\",method=RequestMethod.POST)\r\n\tpublic String reserve(@Valid Reservation reservation, BindingResult bindingResult, SessionStatus sessionStatus){\r\n\t\tvalidator.validate(reservation, bindingResult);\r\n\t\tif(bindingResult.hasErrors()){\r\n\t\t\treturn \"\/reservationForm\";\r\n\t\t} else{\r\n\t\t\treservationService.make(reservation);\r\n\t\t\tsessionStatus.setComplete();\r\n\t\t\treturn \"redirect:..\/reservationSuccess\";\r\n\t\t}\r\n\t}\r\n\r\n\t@RequestMapping(\"\/reservationSuccess\")\r\n\tpublic void success(){\r\n\r\n\t}\r\n}<\/pre>\n<p>So if you see the above code, you would have noticed the commented code where we have used PropertyEditors instead of converters. And hence this feature of enabling type converters on a controller basis is available in both the implementations.<br \/>\n&nbsp;<\/p>\n<div style=\"border: 1px solid #D8D8D8; background: #FAFAFA; width: 100%; padding-left: 5px;\"><b><i>Reference: <\/i><\/b><a href=\"http:\/\/prasanthnath.wordpress.com\/2013\/08\/23\/type-conversion-in-spring\/\">Type Conversion in Spring<\/a> from our <a href=\"http:\/\/www.javacodegeeks.com\/jcg\">JCG partner<\/a> Prasanth Gullapalli at the <a href=\"http:\/\/prasanthnath.wordpress.com\/\">prasanthnath<\/a> blog.<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Here are few straight cases where we need type conversion: Case #1. To help simplifying bean configurations, Spring supports conversion of property values to and from text values. Each property editor is designed for a property of certain type only. And to put them in use, we have to register them with Spring container. Case &hellip;<\/p>\n","protected":false},"author":512,"featured_media":240,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[30],"class_list":["post-18848","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-enterprise-java","tag-spring"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Type Conversion in Spring<\/title>\n<meta name=\"description\" content=\"Here are few straight cases where we need type conversion: Case #1. To help simplifying bean configurations, Spring supports conversion of property values\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Type Conversion in Spring\" \/>\n<meta property=\"og:description\" content=\"Here are few straight cases where we need type conversion: Case #1. To help simplifying bean configurations, Spring supports conversion of property values\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/prasanthnath.g\" \/>\n<meta property=\"article:published_time\" content=\"2013-11-11T14:00:31+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Prasanth Gullapalli\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prasanth Gullapalli\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"12 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html\"},\"author\":{\"name\":\"Prasanth Gullapalli\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/1eae1300536490be5d9c39b3e6b5eb0a\"},\"headline\":\"Type Conversion in Spring\",\"datePublished\":\"2013-11-11T14:00:31+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html\"},\"wordCount\":905,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"keywords\":[\"Spring\"],\"articleSection\":[\"Enterprise Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html\",\"name\":\"Type Conversion in Spring\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"datePublished\":\"2013-11-11T14:00:31+00:00\",\"description\":\"Here are few straight cases where we need type conversion: Case #1. To help simplifying bean configurations, Spring supports conversion of property values\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"spring-interview-questions-answers\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/11\\\/type-conversion-in-spring-2.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Enterprise Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\\\/enterprise-java\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Type Conversion in Spring\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/1eae1300536490be5d9c39b3e6b5eb0a\",\"name\":\"Prasanth Gullapalli\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/c5d5a8464005751039a7642e5205c773902f251b4537242090e9e8c400cc884a?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/c5d5a8464005751039a7642e5205c773902f251b4537242090e9e8c400cc884a?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/c5d5a8464005751039a7642e5205c773902f251b4537242090e9e8c400cc884a?s=96&d=mm&r=g\",\"caption\":\"Prasanth Gullapalli\"},\"description\":\"Prasanth is passionated about technology and specializes in application development in distributed environments. He has always been fascinated by the new technologies and emerging trends in software development.\",\"sameAs\":[\"http:\\\/\\\/prasanthnath.wordpress.com\\\/\",\"https:\\\/\\\/www.facebook.com\\\/prasanthnath.g\",\"http:\\\/\\\/www.linkedin.com\\\/in\\\/prasanthnath\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/prasanth-gullapalli\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Type Conversion in Spring","description":"Here are few straight cases where we need type conversion: Case #1. To help simplifying bean configurations, Spring supports conversion of property values","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html","og_locale":"en_US","og_type":"article","og_title":"Type Conversion in Spring","og_description":"Here are few straight cases where we need type conversion: Case #1. To help simplifying bean configurations, Spring supports conversion of property values","og_url":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_author":"https:\/\/www.facebook.com\/prasanthnath.g","article_published_time":"2013-11-11T14:00:31+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","type":"image\/jpeg"}],"author":"Prasanth Gullapalli","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Prasanth Gullapalli","Est. reading time":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html"},"author":{"name":"Prasanth Gullapalli","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/1eae1300536490be5d9c39b3e6b5eb0a"},"headline":"Type Conversion in Spring","datePublished":"2013-11-11T14:00:31+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html"},"wordCount":905,"commentCount":2,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","keywords":["Spring"],"articleSection":["Enterprise Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html","url":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html","name":"Type Conversion in Spring","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","datePublished":"2013-11-11T14:00:31+00:00","description":"Here are few straight cases where we need type conversion: Case #1. To help simplifying bean configurations, Spring supports conversion of property values","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","width":150,"height":150,"caption":"spring-interview-questions-answers"},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/2013\/11\/type-conversion-in-spring-2.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java","item":"https:\/\/www.javacodegeeks.com\/category\/java"},{"@type":"ListItem","position":3,"name":"Enterprise Java","item":"https:\/\/www.javacodegeeks.com\/category\/java\/enterprise-java"},{"@type":"ListItem","position":4,"name":"Type Conversion in Spring"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/1eae1300536490be5d9c39b3e6b5eb0a","name":"Prasanth Gullapalli","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/c5d5a8464005751039a7642e5205c773902f251b4537242090e9e8c400cc884a?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/c5d5a8464005751039a7642e5205c773902f251b4537242090e9e8c400cc884a?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c5d5a8464005751039a7642e5205c773902f251b4537242090e9e8c400cc884a?s=96&d=mm&r=g","caption":"Prasanth Gullapalli"},"description":"Prasanth is passionated about technology and specializes in application development in distributed environments. He has always been fascinated by the new technologies and emerging trends in software development.","sameAs":["http:\/\/prasanthnath.wordpress.com\/","https:\/\/www.facebook.com\/prasanthnath.g","http:\/\/www.linkedin.com\/in\/prasanthnath"],"url":"https:\/\/www.javacodegeeks.com\/author\/prasanth-gullapalli"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/18848","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/512"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=18848"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/18848\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/240"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=18848"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=18848"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=18848"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}