参考文章https://blog.youkuaiyun.com/whz110/article/details/84770680
参考上面的文章的话,最后在封装数据的时候会报错,下面代码为解决问题之后的代码:
前台页面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-2.1.3.min.js" />
<script>
$(function(){
});
</script>
</head>
<body>
<input type="button" onclick="test()"/>
</body>
<script>
function test() {
console.debug(123)
$.ajax({
"url": "/news/testJson", //路径
"cache": false, //不缓存
"async": true, //异步
"type": "POST", //POST方式提交
"dataType": "json", //json格式,重要
"contentType": "application/json", //json格式
"data": {"key":"keyword","type":"1","page":"13"},
success: function (json) { //成功处理
},
error: function (x, e) {
}
})
}
</script>
</html>
准备一个实体类来封装前台的参数
public class Query {
private int type;
private String key;
private String page;
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
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;
}
@Override
public String toString() {
return "QueryRequest{" +
"type=" + type +
", key='" + key + '\'' +
", page='" + page + '\'' +
'}';
}
}
接下来就是我们的Controller类
public class NewsController extends Controller {
public void testJson(){
try{
//从requst中读取json字符串
StringBuilder json = new StringBuilder();
BufferedReader reader = this.getRequest().getReader();
String line = null;
while((line = reader.readLine()) != null){
System.out.println(line);
json.append(line);//注意:这里的数据格式是 key=keyword&type=1,不能直接使用FastJson解析
}
String s = "{" + json.toString().replace("&", "\",").replace("=", ":\"") + "\"}";//完成字符串拼接,得到json格式的字符串
Query request = JSONObject.parseObject(s, Query.class);
//下略
System.out.println(request);
//.......
}
catch(Exception ex){
//异常处理,略
ex.printStackTrace();
}
}
}
总结:Jfinal对于json格式数据的处理确实不如springMVC来得简单,但是对于表单数据或者url上的数据获取却很容易