2

我有一个 Solr 4.0,它在 Postgres db 中索引数据(包含多语言字符)。当我通过内置的 Jetty 向 Solr 发出直接请求时,我得到了 JSON 格式的正确响应。Tomcat 7 下运行着一个 Servlet,它负责处理对公共 API 的请求。此 API 通过 HTTP 获取请求,对执行请求的权限进行某种检查,然后使用 solrj 向 Solr 发出请求,然后以 JSON 格式发送响应。问题是当我通过 Servlet 请求 Solr 时,我总是得到很多 ????????? 应有国际字符的地方的符号。DB 中的所有数据都是 UTF-8 编码,Tomcat server.xml 中的 URIEncoding 参数也是 UTF-8。这是我在 Servlet 中编写响应的方式:

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException
{
    PrintWriter writer = res.getWriter();
    String encoding = req.getCharacterEncoding();
    if(null == encoding)
    {
        req.setCharacterEncoding("UTF-8");
    }
    else
    {
        req.setCharacterEncoding(encoding);
    }   
    res.setContentType("application/json; charset=UTF-8");
    res.setCharacterEncoding("UTF-8");
    String key = req.getParameter(P_KEY);
    if (ps.isPartnerKey(key))
    {
        if (req.getMethod().equals(M_GET))
        {
            String query = req.getParameter(P_QUERY);
            String solr_json = SolrService.getInstance().query(query);
            //parse JSON for id's and get images
            if (solr_json != null)
            {
                writer.println(solr_json);
            }
        }
        if (req.getMethod().equals(M_POST))
        {
            String id = req.getParameter(P_ID);
            String field = req.getParameter(P_FIELD);
            String value = req.getParameter(P_VALUE);
            SolrService.getInstance().partialUpdate(id, field, value);
            fs.add(id, field, value, ps.getPartnerId(key));
        }
    }
    else
    {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
    writer.close();
}

这就是我从 Solr 获取数据的方式:

 public String query(String query)
{
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.set("q", query!=null ? query : "*:*");
    solrQuery.set("wt", "json");
    String response = "";
    try
    {
        QueryResponse res = solr.query(solrQuery);
        response = res.getResults().toString();
        log.debug(response);
    }
    catch (SolrServerException e)
    {
        e.printStackTrace();
    }
    return response;
}

Am I doing wrong something? What is the problem may be?

4

1 回答 1

2

You are calling getWriter to early. Call it after setting the character encoding.

于 2012-12-18T06:56:42.467 回答