在jfinal的Controller中接受json数据
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) { //异常处理
}
});