In Java Web development, form and ajax submit data Model conversion
In Java Web development, form and ajax submit data Model conversion problems
I recently learned about MongoDB databases. As a java developer, I need to develop a small web program to test it. In html, I use ajax to submit data, because I want to simulate various types of data, basic data types, arrays, and objects. However, we finally found a difference: Form and ajax submit data. In HttpServletRequest, the parameter names vary.
Data Type |
Form |
Ajax |
Basic Data |
Para = value |
Para = value |
Array |
Para [] = {"aaa", "bbb "} |
Para [] [] = {"aaa", "bbb "} |
Object |
Obj. sex = female (same as basic data, only obj .) |
Obj [sex] = female |
Object Array |
Obj [0]. sex |
Obj [0] [sex] = female |
Form submission. The preceding parameter method must be defined in the name attribute of input. springmvc data binding is commonly used. ajax submission uses the attributes 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);});
The above is an ajax commit.
Solution
The difference was discovered, and there was no starting point. However, at the time of submission, it is sometimes difficult to obtain and parse data, that is, the framework such as spring can provide perfect support, but we should still understand the principle. So I am not going to see the principles of spring. I will be dizzy.
To completely solve this problem, I wrote a class and used recursion. Next, let's analyze it.
First, you need a method to get T through parameters, as shown below:
Public static
T getModel (Map
Map, Class
Clazz) {Map
JsonMap = new HashMap
(); For (String key: map. keySet () {String [] values = map. get (key); // $. ajax submits data: {arr: ['aaa', 'bbb ']}. Here the key is arr [] [] if (key. endsWith ([]) key = key. substring (0, key. length ()-2); parseKey (key, values, clazz, jsonMap);} return JSON. parseObject (JSON. toJSONString (jsonMap), clazz );}
There are two points in this method:
1. ajax submits an array [] [], and a key consistency must be removed.
2. Convert Map to T object. Here we use fastjson for conversion (converting Map to json and then converting json back to T, because direct conversion is difficult)
ParseKey Method
Private static void parseKey (String key, String [] values, Class
Clazz, Map
JsonMap) {if (hasSubClass (key) {// array or object String field = key. substring (0, key. indexOf ([); String classField =; if (key. contains (.)) {// set. convert to [] to operate key = key. replace (]., pattern ). replace (., pattern); key = key +];} if (key. indexOf (pattern )! = Key. lastIndexOf (pattern) {// The array object classField = 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, new ArrayList
> ();} List
> List = (List) jsonMap. get (field); int I = Integer. parseInt (key. substring (field. length () + 1, field. length () + 2) + 1; for (int j = 0; j <I; j ++) {try {list. get (j); continue;} catch (Exception e) {list. add (j, new HashMap
() ;}} 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 object try {load (key, values, clazz, jsonMap);} catch (Exception e) {e. printStackTrace ();}}}
This method is mainly based on the parameter rules, then judge the data type, and then perform the corresponding conversion. recursion is used in this method. We should know the reason, so I will not say much.
Last
The general idea is this: to judge the parameter + reflection; reflection is to ensure data accuracy.