JSP使用JSON传递数据,注意避免中文乱码

JSP传递数据时不方便使用Java中的对象类型,一般使用JSON来传递对象。

在使用JSON时,前端js如下,注意指定dataType:

var htmlobj=
$.ajax({
url:"chat.do",type:"POST",
data:{sayingContent:$("#textarea").val()},
dataType:"json",
success: function(data){$("#said").append(data.content);}
});

后台要引入如下jar包。

然后使用如下方式保存JSON:

Map map = new HashMap();
map.put("content", request.getParameter("sayingContent"));
JSONObject json = JSONObject.fromObject(map);

后台访问时,代码如下:

json.getString("content")

返回数据时,要注意设置数据格式,以保证JSON的数据不会成为乱码:

response.setContentType("text/html; charset=utf-8"); 
response.getWriter().print(json);

最后,区分一下response.getWriter()的write()和print()方法的区别:

(1 )write():仅支持输出字符类型数据,字符、字符数组、字符串等;
(2) print():可以将各种类型(包括Object)的数据通过默认编码转换成bytes字节形式,这些字节都通过write(int c)方法被输出。

一个完整样例如下:

protected void doPost(HttpServletRequest request,HttpServletResponse response){
        Map map = new HashMap();
        map.put("content", request.getParameter("sayingContent"));
        JSONObject json = JSONObject.fromObject(map);
        try {
            response.setContentType("text/html; charset=utf-8"); 
            response.getWriter().print(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 后台JSON的扩展阅读:

JSON存取:http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/23/3096001.html

JSON乱码:http://www.iteye.com/problems/87358

原文地址:https://www.cnblogs.com/dhuhank/p/4444835.html