Model transformation of form and Ajax submission data in Javaweb development

Source: Internet
Author: User

Model transformation of form and Ajax submission data in Javaweb development

Recently learning the MongoDB database, as Java development, I certainly need to do a small Web application to test. In HTML I take AJAX submissions because I want to emulate various types of data, underlying data types, arrays, objects, and so on. Eventually, however, a different place was found: form and Ajax commit data, altogether parameter names differ in HttpServletRequest.

Data Type form Ajax
Basic data Para=value Para=value
Array para[]={"AAA", "BBB"} para[][]={"AAA", "BBB"}
Object Obj.sex= (as with the basic data, just use obj.) obj[sex]= Women
Object array Obj[0].sex obj[0][sex]= Women

The form submission, above the parameter method, needs to be defined in input's name attribute, commonly used is SPRINGMVC data binding; Ajax commits, parameters are derived from the properties of the object submitted by data.

$.ajax ({type:"POST", DataType:"JSON"Url:"${ctx}/api/manage/save", data: {test: [' AaB ',' BBB ',' CCC '], table:' TableName ', fields: [{' field ':' F ',' type ':' t ',' desc ':' d '},                {' field ':' F1 ',' type ':' T1 ',' desc ':' D1 ']}). Success ( function(data) {alert (data.msg);});

As above, it is an AJAX submission.

Solve

Found the difference, the beginning is nothing. But at the time of submission, getting the data and parsing is sometimes a bit of a hassle, that is, the framework of spring can be perfectly supported, but it should be understood. So I'm not going to see the spring principle, I'm going to faint.
In order to solve this problem completely, I wrote a class by myself, using recursive method. Down to analyze the next

    1. First you need a way to get t through the parameters, as follows
public  static  <T> T getmodel  (map<string, string[]> Map, Class<t> clazz) {map<string, object> jsonmap = new  HashMap<String, Ob    Ject> (); for  (String Key:map.keySet ())        {string[] values = Map.get (key);        //$.ajax submit data:{arr:[' AAA ', ' BBB ']}, here key is arr[][]  if  (Key.endswith ( "[]" )) key = Key.substring (0 , K        Ey.length ()-2 );    Parsekey (key, values, Clazz, jsonmap); } return  json.parseobject (json.tojsonstring (Jsonmap), clazz);}  

There are two points in this method:
1, Ajax commit array [], need to remove a hold key consistency
2. Convert map to T object, here is conversion by Fastjson (now convert map to JSON, then json back to T, because direct conversion is a bit difficult)

Parsekey method

Private Static void Parsekey(String key, string[] values, class<?> clazz, map<string, object> Jsonmap) {if(Hassubclass (key)) {//objects for arrays or objectsString field = key.substring (0, Key.indexof ("[")); String Classfield ="";if(Key.contains (".")) {//Convert. Unification in form to [] to operateKey = Key.replace ("].", pattern). Replace (".", pattern); Key = key +"]"; }if(Key.indexof (pattern)! = Key.lastindexof (pattern)) {//May be an array objectClassfield = key.substring (Key.indexof (pattern) +2, Key.length ()). Replacefirst ("]",""); }Else{Classfield = key.substring (Key.indexof (pattern) +2, Key.length ()-1); }if(jsonmap.get (field) = =NULL) {Jsonmap.put (field,NewArraylist<map<string, object>> ()); } list<map<string, object>> list = (list) jsonmap.get (field);inti = Integer.parseint (key.substring (field.length () +1, Field.length () +2)) +1; for(intj =0; J < I; J + +) {Try{List.get (j);Continue; }Catch(Exception e) {List.add (J,NewHashmap<string, object> ()); }} class<?> Subclass =NULL;Try{Parameterizedtype cl = (parameterizedtype) clazz. Getdeclaredfield (field). Getgenerictype ()            ; Subclass = (class<?>) cl.getactualtypearguments () [0]; Parsekey (Classfield, values, subclass, List.get (i-1)); }Catch(Nosuchfieldexception e)        {E.printstacktrace (); }Catch(SecurityException e)        {E.printstacktrace (); }    }Else{//Basic data or objects        Try{Load (key, values, Clazz, jsonmap); }Catch(Exception e)        {E.printstacktrace (); }    }}

This method is mainly based on the parameters of the rules, and then determine the type of data, and then the corresponding conversion, the inside with recursion, reason everyone should know, I will not say more.

At last

This is probably the way of thinking: judging parameters + reflections, reflecting the accuracy of the data.
Final version: Download

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Model transformation of form and Ajax submission data in Javaweb development

Related Article

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.