JFinal中接收URL中的參數或者model中的參數是很方便的,可是對於web2.0的網站來講,常常會以json方式提交比較複雜的數據,好比一個查詢,包含了各類過濾條件和排序分頁,前端腳本可能提交的數據是這樣的:
前端
{ "type":1, "key":"keyword", "paging":{ "size":50, "index":0 }, "sort":{ "field":"time", "type":"desc" } }
像SpringMVC就提供了@RequestBody將數據綁定到json對象上,可是jFinal不支持,須要本身從POST中讀取並解析這個json數據,先定義一個與請求同結構的Java對象,好比起名叫QueryRequest:
java
packagecom.demo; import com.demo.Paging; import com.demo.Sort; public class QueryRequest { private int type; private String key; private Paging paging; private Sort sort; public int getType() { return type; } public void setType(int type) { this.type = type; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Paging getPaging() { return paging; } public void setPaging(Paging paging) { this.paging = paging; } public Sort getSort(){ return sort; } public void setSort(Sort sort){ this.sort = sort; } }
其中用到了Paging和Sort兩個類:web
package com.demo; public class Paging { private int size; private int index; public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
package com.demo; public class Sort { private String field; private String type; public String getField() { return field; } public void setField(String field) { this.field = field; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
而後在Controller裏就從request中讀取json字符串,而後調用fastjson解析提交的數據了,:ajax
@Before(POST.class) public void getData(){ try{ //從requst中讀取json字符串 StringBuilder json = new StringBuilder(); BufferedReader reader = this.getRequest().getReader(); String line = null; while((line = reader.readLine()) != null){ json.append(line); } reader.close(); //調用fastjson解析出對象 QueryRequest request = JSONObject.parseObject(json.toString(), QueryRequest.class); //而後就能夠使用request獲得請求的全部數據了 //下略 //....... } catch(Exception ex){ //異常處理,略 } renderText("測試"); }
轉換部分會常用,能夠提出來:
json
/** * 取Request中的數據對象 * @param valueType * @return * @throws Exception */ protected <T> T getRequestObject(Class<T> valueType) throws Exception { StringBuilder json = new StringBuilder(); BufferedReader reader = this.getRequest().getReader(); String line = null; while((line = reader.readLine()) != null){ json.append(line); } reader.close(); return JSONObject.parseObject(json.toString(), valueType); }
使用的時候一句就好了:
緩存
QueryRequest requst = getRequestObject(QueryRequest.class);
另外附上前端ajax調用的腳本:app
$.ajax({ "url": "/home/getDate", //路徑 "cache": false, //不緩存 "async": true, //異步 "type": "POST", //POST方式提交 "dataType": "json", //json格式,重要 "contentType": "application/json", //json格式 "data": {}, //要提交的數據對象 success: function (json) { //成功處理 }, error: function (x, e) { //異常處理 } });
PS:很喜歡jFinal,相比於SpringMVC龐大的體積,jFinal真是的很小巧。異步
PPS:使用的是jFinal-2.0,配合fastjson-1.2.3,以前用fastjson-1.2.4時會有問題。async