嵌入式jetty服务器导致UTF-8字符出现问题

时间:2018-04-12 16:07:30

标签: jetty embedded-jetty

来自servlet文件的代码

 @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    try {
      Map map = req.getParameterMap();
      HashMap<String, Object> paramsMap = new HashMap<String, Object>(map);
      String action = HTTPUtil.getInstance().getPropertyFromHttpRequest(PARAM_ACTION, paramsMap, false);
      String service = HTTPUtil.getInstance().getPropertyFromHttpRequest(PARAM_SERVICE_NAME, paramsMap, false);
     String requestBody = (String)IOUtils.toString(req.getInputStream());

 ....

requestBody中的一个字段呈现为“Brad?”而不是requestBody中的“Brad's”。理想情况下,“Brad's”应该已经呈现。这导致不正确的数据存储在DB中。

这就是jetty服务器的启动方式:

server = new Server(new QueuedThreadPool(10));
ServerConnector connector = new ServerConnector(server);
connector.setPort(getPort());
server.addConnector(connector);
HandlerCollection handlerCollection = getHandlers();
server.setHandler(handlerCollection);
server.setStopAtShutdown(true);
server.setStopTimeout(1000);
server.start();

getHandlers()返回HandlerCollection创建为:

HandlerCollection handlers = new HandlerCollection(true);
ServletContextHandler handler = new ServletContextHandler();
handler.getContextPath();
handler.addServlet(new ServletHolder(new TestServlet(), "/test");
handlers.addHandler(handler);

Jetty版本9.2.11.v20150529

curl -X POST \
  'http://master92.XYZ.com:7777/health?test=10&action=10' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json; charset=utf-8' \
  -d '{"name":"ABA …"}'

请求正文显示为

{“name”:“ABA?”转储到日志或控制台时

1 个答案:

答案 0 :(得分:0)

使用-Dfile.encoding = UTF-8选项解决了该问题。