標籤:jfinal
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:
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兩個類:
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解析提交的資料了,:
@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("測試");}
轉換部分會經常使用,可以提出來:
/** * 取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調用的指令碼:
$.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真是的很小巧。
本文出自 “兔子窩” 部落格,請務必保留此出處http://boytnt.blog.51cto.com/966121/1698113
在JFinal的Controller中接收json資料