Jfinal获取前台json格式数据

参考文章https://blog.csdn.net/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上的数据获取却很容易

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值