Spring MVC Data Transformation

Source: Internet
Author: User

Example: Encapsulates a string and an object.
such as: Data zhangsan:1234 in Username:password format. We encapsulate this data as a user object. The following are implemented using the property editor and the converter, respectively.

1, you define the property editor A, write a property editor to inherit PropertyEditorSupport
 PackageCn.framelife.mvc.converter;ImportJava.beans.PropertyEditorSupport;ImportCn.framelife.mvc.entity.User; Public  class usereditor extends propertyeditorsupport {     Public void Setastext(String text)throwsillegalargumentexception {System.out.println ("Setastext"); User User =NewUser ();if(Text! =NULL) {string[] items = Text.split (":"); User.setusername (items[0]); User.setpassword (items[1]);    } setValue (user); }}
B, controller scope editor

Register with the controller and use the editor:

/** * @InitBinder Annotations bind the editor to the current controller */    @InitBinder     Public void Initbinder(Webdatabinder Binder) {//Register your own defined editorBinder.registercustomeditor (User.class,NewUsereditor ()); }/** * The first parameter user is a model data, the receiving page of the username with password * The second parameter converteruser through @requestparam annotations. Transfer the other parameters of the page to Usereditor to a user object * /    @RequestMapping("Create") PublicModelandviewCreateUser(User user,@Requestparam("Other") User converteruser) {System.out.println (User.getusername () +"--"+user.getpassword ()); System.out.println (Converteruser.getusername () +"--"+converteruser.getpassword ()); Modelandview view =NewModelandview (); View.setviewname ("/success");returnView }
C, Global-scope editor

Implement the Webbindinginitializer interface and register the property editor in the implementation class:

 PackageCn.framelife.mvc.converter;ImportOrg.springframework.web.bind.WebDataBinder;ImportOrg.springframework.web.bind.support.WebBindingInitializer;ImportOrg.springframework.web.context.request.WebRequest;ImportCn.framelife.mvc.entity.User; Public  class Mybindinginitializer implements Webbindinginitializer {     Public void Initbinder(Webdatabinder binder, WebRequest request) {//Register your own defined property editor. Here you can register multiple property editorsBinder.registercustomeditor (User.class,NewUsereditor ()); }}

To configure the Webbindinginitializer implementation class:

 <!--Configure global-scope property editor-->  Span class= "Hljs-tag" ><bean  class  = "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"  >  <property  name
      = "Webbindinginitializer" ;  <bean  class  = " Cn.framelife.mvc.converter.MyBindingInitializer ";  </ bean ;  </property
       >,  </bean ;   

Use the Property Editor:
is the same as in controller scope

    /**     * 第一个參数user是一个模型数据,接收页面的username用password     * 第二个參数converterUser通过@RequestParam注解,把页面的other參数交由UserEditor转成一个User对象      */    @RequestMapping("create")    publiccreateUser(User user,@RequestParam("other")User converterUser){        System.out.println(user.getUsername()+"--"+user.getPassword());        System.out.println(converterUser.getUsername()+"--"+converterUser.getPassword());        new ModelAndView();        view.setViewName("/success");        return view;    }
2, converter A, write a converter class inheritance converter
Package Cn.framelife.mvc.converter;import Org.springframework.core.convert.converter.converter;import Cn.framelife.mvc.entity.User;/** * converter<s Source Type/t target type > * * * Public  class stringtouserconverter implements Converter<String,  User> {     PublicUser convert (String source) {User user =NewUser ();if(Source! =NULL) {string[] items = Source.split (":"); User.setusername (items[0]); User.setpassword (items[1]); }returnUser }}
B, configuration (mvc-servlet.xml)
    <!--Assembly Converters --      <bean id= "conversionservice"class=" Org.springframework.context.support.ConversionServiceFactoryBean ">                 < property name="Converters">            <list>                <!--Here you can configure several of your own defined converters--                <Bean class="Cn.framelife.mvc.converter.StringToUserConverter"></Bean>            </list>        </Property >    </Bean>     <!--assemble your own defined converters--    <mvc:annotation-driven conversion-service="Conversionservice"/>
C, the Controller's processing method to receive page data
    /**     * 第一个參数user是一个模型数据,接收页面的username用password     * 第二个參数converterUser通过@RequestParam注解,把页面的other參数交由转换器StringTouserConverter转成一个User对象      */    @RequestMapping("create")    publiccreateUser(User user,@RequestParam("other")User converterUser){        System.out.println(user.getUsername()+"--"+user.getPassword());        System.out.println(converterUser.getUsername()+"--"+converterUser.getPassword());        new ModelAndView();        view.setViewName("/success");        return view;    }
3. Attention

Assuming that the controller scope's property editor, the global-scope property editor, and the converter exist at the same time, Spring MVC will look for the appropriate type of editor to handle in the following order of precedence:
Query the Controller Scope Property editor
Query Converters
Querying the global Scope property editor

4. Data Format 4.1 Spring built-in format converter

4.2 Use of annotation-driven formatting

A, start the annotation drive formatting function
Before we configured ourselves to define the converter. The Beanconversionservicefactorybean is used.

org.springframework.context.support.ConversionServiceFactoryBean

Change into

org.springframework.format.support.FormattingConversionServiceFactoryBean

The Formattingconversionservicefactorybean is able to register its own defined converters. You can also register your own defined annotation-driven format converter to enable the project to support annotation-driven formatting.

    <bean id= "conversionservice"class=" Org.springframework.format.support.FormattingConversionServiceFactoryBean ">                 < property name="Converters">            <list>                <!--This is the converter that was previously configured for its own definition--                <Bean class="Cn.framelife.mvc.converter.StringToUserConverter"></Bean>            </list>        </Property >    </Bean>

B, page

<form Action="User/create.abc" method="POST"> User name:<input type="text" name="username"><br/>Password<input type="text" name="password"><br/>Birthday:<input type="text" name="Birthday"><br/>Wages:<input type="text" name="Salary"><br/>Other:<input type="text" name="Other"><br/>        <input type="Submit"> </form>

C. Using formatted annotations in entity classes

 Public  class User implements Java. io. Serializable {    PrivateInteger ID;PrivateString username;PrivateString password;//Converts a string such as 1999-09-09 into a Date object    @DateTimeFormat(Pattern ="Yyyy-mm-dd")PrivateDate birthday;//Convert a string such as 5,500.00 to a long type of data    @NumberFormat(Pattern ="#,###.##")Private LongSalary Public Long getsalary() {returnSalary } Public void setsalary(LongSalary) { This. salary = salary; } PublicDateGetbirthday() {returnBirthday } Public void Setbirthday(Date birthday) { This. Birthday = Birthday; } PublicIntegergetId() {returnId } Public void setId(Integer ID) { This. id = ID; } PublicStringGetUserName() {returnUsername } Public void Setusername(String username) { This. Username = Username; } PublicStringGetPassword() {returnPassword } Public void SetPassword(String password) { This. Password = password; }}

D. Processing in Controler

    @RequestMapping("create")    publiccreateUser(User user){        System.out.println(user.getBirthday()+"=="+user.getSalary());        new ModelAndView();        view.setViewName("/success");        return view;    }

Spring MVC Data Transformation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.