【发布时间】:2015-01-23 08:22:22
【问题描述】:
我有一个带有 JQgrid(版本 4.1.2)的 JSP / Servlet 页面。在此网格中,当有任何重音字符时,它不会显示这些字符。网格以 JSON 格式获取其输入。
我确认重音字符已写入响应对象。使用萤火虫我看到网格收到的 JSON 响应没有重音字符。请求头信息为
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type text/html; charset=UTF-8
Cookie XXXX
Host XXXX
Referer http://XXXXXXXX
User-Agent Mozilla/5.0 (Windows NT 5.2; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
X-Requested-With XMLHttpRequest
而响应头是
Content-Type text/html
Date Tue, 25 Nov 2014 10:42:29 GMT
Server Apache-Coyote/1.1
Transfer-Encoding chunked
我还将响应标头的 Content-Type 设置为 application/json,但接收到的 JSON 字符串也没有显示重音字符。
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
当我用谷歌搜索这个问题时,有人提到使用autoencode:true 和ajaxGridOptions: { contentType: 'text/html; charset=UTF-8' } 和formatter:null。还提到添加<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">。我还加了<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
但仍然没有显示重音字符。谁能告诉我我错过了什么?
测试代码:
Servlet JQGridDemo 代码
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@SuppressWarnings("serial")
public class JQGridDemo extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
String page = "1";
String totalPages = "2";
String totalCount = "15";
String[] rowId = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12", "13", "14", "15" };
String[] InvNo = { "101", "102", "103", "104", "105", "106", "107",
"108", "109", "110", "111", "112", "113", "114", "115" };
String[] DateRec = { "03/30/12", "03/31/12", "04/01/12",
"04/02/12", "04/03/12", "04/04/12", "04/05/12",
"04/06/12", "04/07/12", "04/08/12", "04/09/12",
"04/10/12", "04/11/12", "04/12/12", "04/13/12" };
String[] AmountRec = { "11000", "12000", "13000", "14000", "15000",
"16000", "17000", "18000", "19000", "20000", "21000", "22000",
"23000", "24000", "25000" };
String[] TaxRec = { "1000", "1000", "1000", "1000", "1000", "1000",
"1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000",
"1000" };
String[] TotalRec = { "12000", "13000", "14000", "15000", "16000",
"17000", "18000", "19000", "20000", "21000", "22000", "23000",
"24000", "25000", "26000" };
String[] NotesRec = { "Mineta San José", "Invoice 2", "Invoice 3",
"Invoice 4", "Mineta San José", "Invoice 6", "Invoice 7",
"Invoice 8", "Invoice 9", "Invoice 10", "Invoice 11",
"Invoice 12", "Invoice 13", "Invoice 14", "Invoice 15" };
response.setContentType("application/json; charset=UTF-8");
response.setCharacterEncoding("utf-8");
try {
if (action.equals("fetchDataJSON")){
response.setContentType("text/json; charset=UTF-8");
JSONArray cellarray = new JSONArray();
JSONObject responsedata = new JSONObject();
responsedata.put("page", page);
responsedata.put("total", totalPages);
responsedata.put("records", totalCount);
for(int record = 0; record < rowId.length; record++){
JSONArray cell = new JSONArray();
JSONObject cellobj = new JSONObject();
cellobj.put("id", record + "");
cell.add(InvNo[record]);
cell.add(DateRec[record]);
cell.add(AmountRec[record]);
cell.add(TaxRec[record]);
cell.add(TotalRec[record]);
cell.add(NotesRec[record]);
cellobj.put("cell", cell);
cellarray.add(cellobj);
/*cellobj.clear();
cell.clear();*/
}
responsedata.put("rows", cellarray);
out.write(responsedata.toString());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
out.close();
}
}
// Process the doGet request
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
// Process the doPost request
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
Test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="application/json; charset=UTF-8">
<title>Home</title>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url:'<%=request.getContextPath()%>/JQGridDemo?q=1&action=fetchDataJSON',
datatype: 'JSON',
autoencode:true,
mtype: 'GET',
colNames:['Inv No','Date', 'Amount','Tax','Total','Notes'],
colModel :[
{name:'invid',index:'invid',width:55,
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false}},
{name:'invdate', index:'invdate', width:160,
sortable:false,editable:true,hidden:false,
editrules :{edithidden:false,required:false,date:true},
editoptions :{dataInit:function(element){$(element).datepicker(
{dateFormat:'mm/dd/yy'});}},
formatoptions: {newformat:'m/d/Y'},
formoptions:{elmprefix:' '}},
{name:'amount',index:'amount',width:80,align:'right',
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false},
formoptions:{elmprefix:'*'}},
{name:'tax',index:'tax',width:80,align:'right',
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false}},
{name:'total',index:'total',width:80,align:'right',
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false}},
{name:'note', index:'note', width:150,
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false},
autoencode: false}
],
pager: '#pager1',
rowNum:5,
height:'auto',
loadonce:true,
width:'100%',
gridview: true,
autowidth:true,
shrinkToFit:false,
rowList:[5,10,15,20,25,30],
sortname: 'invid',
sortorder: 'asc',
viewrecords: true,
editurl:'<%=request.getContextPath()%>/JQGridDemo?q=1&action=editDataJSON',
caption: 'My first grid',
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
$("#list").jqGrid('navGrid',"#pager1",{add:true,edit:true,del:true,search:true,refresh:true,
beforeRefresh: function(){
$("#list").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid', [{page:1}]);
}},
{},{},{},{
closeAfterSearch: true,
modal: true
});
});
</script>
</head>
<body>
<table id="list">
</table>
<div id="pager1"></div>
</body>
我已经用json-lib-2.4-jdk15.jar 和json-simple.jar JSON 库测试了这段代码。 JQGrid 中不显示重音字符
【问题讨论】:
-
您自己写道:“使用 firebug 我看到网格收到的 JSON 响应没有重音字符。”所以你遇到的问题不取决于jqGrid。它位于返回 JSON 数据的 服务器代码 中。您应该发布有关代码的更多详细信息。它应该包括
response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); response.getWriter().write(pureJsonData);之类的内容或其他内容,具体取决于服务器上使用的技术。 -
在进一步分析控制台选项卡中重音字符未正确显示但在网络选项卡中正确显示字符的萤火虫。我还调试了服务器代码,发现在将数据写入响应对象之前,重音字符会正确显示。一旦它被发送到 UI 并在 UI 中接收,字符就会丢失。我还在 tomcats server.xml 文件中添加了
URIEncoding="UTF-8" useBodyEncodingForURI = "true"。然后字符也没有显示。 -
您应该在网络浏览器中打开包含 jqGid 的 HTML 页面并检查其标题部分。您应该在代码中附加以
<!DOCTYPE html ...开头直到</head>的信息。头部必须包含<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />或一些紧密的行,其确切语法取决于您使用的<!DOCTYPE html ...>。 -
@Oleg:在我的 JSP 页面中,我有以下代码行<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>之后这一行<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">和 In<head>标签<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -
您使用
out.write和很奇怪的System.out.println("cellarray = " + cellarray);而不是先设置ContentType和CharacterEncoding的response,通过response.getWriter()获取编写器并使用它来编写结果。 (见我的第一条评论)。我想强调的是,您不能在 JSON 响应中附加一些调试数据,例如System.out.println("cellarray = " + cellarray);。无论如何,我建议您将loadError回调添加到 jqGrid(请参阅 the old answer)
标签: json jsp servlets utf-8 jqgrid