JQGrid没有显示重音字符

时间:2014-11-25 11:01:33

标签: json jsp servlets utf-8 jqgrid

我有一个带有JQgrid的JSP / Servlet页面(版本4.1.2)。在此网格中,当有任何重音字符时,它不会显示这些字符。网格以JSON格式获取输入。

我确认重音字符被写入响应对象。使用firebug我看到网格收到的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:trueajaxGridOptions: { 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.jarjson-simple.jar JSON库测试了此代码。重音字符未显示在JQGrid

1 个答案:

答案 0 :(得分:0)

正如@Oleg所说,问题不在于JSON数据的编写方式,也不在JQGrid中。但问题在于使用响应编写器对象的方式。在我的代码中,我获取了一次Response PrintWriter对象,然后在我的代码中根据请求的对象使用它。我正在设置ContentType&amp;发送数据前CharacterEncoding。但这不是正确的方法。 ContentType&amp;必须在获取之前设置Response PrintWriter对象上的CharacterEncoding。一旦我这样做了,重音字符就会在JQGrid中正确显示。

相关问题