You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌入式Jetty服务器出现UTF-8字符问题,附Servlet代码片段

Hey there, let's break down this UTF-8 character issue you're facing with your embedded Jetty server. From the code snippet you shared and common pitfalls I've seen with Jetty and Servlet POST handling, here's what's likely going wrong and how to fix it:

1. Why This Happens

UTF-8 issues in Jetty almost always boil down to missing encoding configurations at one or more layers:

  • Default Parameter Encoding Mismatch: By default, Jetty (and most Servlet containers) uses ISO-8859-1 for parsing request parameters via getParameterMap(), which mangles UTF-8 characters like non-English text or special symbols.
  • Unspecified Request Body Encoding: If you're reading raw request body content later in your code, using the default InputStreamReader (which relies on system encoding instead of UTF-8) will cause garbled text.
  • Missing Global Jetty Configuration: Embedded Jetty doesn't inherit container-wide encoding settings like a deployed WAR would—you have to explicitly set these in your server setup code.

2. Step-by-Step Fixes

Fix 1: Set Request Parameter Encoding First

You must set the request's character encoding before calling getParameterMap()—this tells Jetty to parse POST parameters as UTF-8:

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Critical: Set encoding BEFORE accessing parameters
    req.setCharacterEncoding("UTF-8");
    
    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);
    // Rest of your code...
}

Note: This only applies to POST parameters. For GET parameters, you'll need to configure Jetty's connector (see Fix 3 below).

Fix 2: Read Request Body with UTF-8

If you're reading the raw request body (like the requestBody variable in your snippet), explicitly use UTF-8 when creating the reader:

// Correct way to read request body as UTF-8
String requestBody = new BufferedReader(
    new InputStreamReader(req.getInputStream(), StandardCharsets.UTF_8)
).lines().collect(Collectors.joining("\n"));

Avoid using the default InputStreamReader constructor—it uses your system's default encoding, which is rarely UTF-8.

Fix 3: Configure Global Jetty Encoding Settings

Add these configurations when setting up your embedded Jetty server to enforce UTF-8 across all requests and responses:

Server server = new Server();

// Configure HTTP connector with UTF-8
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setRequestHeaderEncoding("UTF-8");
httpConfig.setResponseHeaderEncoding("UTF-8");
httpConfig.setQueryEncoding("UTF-8"); // For GET request parameters

HttpConnectionFactory httpConnFactory = new HttpConnectionFactory(httpConfig);
ServerConnector connector = new ServerConnector(server, httpConnFactory);
connector.setPort(8080);
server.addConnector(connector);

// Configure servlet context to use UTF-8 by default
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setInitParameter("org.eclipse.jetty.servlet.defaultEncoding", "UTF-8");
server.setHandler(context);

// Register your servlet
context.addServlet(new ServletHolder(YourServletClass.class), "/your-endpoint");

server.start();
server.join();

Fix 4: Set Response Encoding

Don't forget to ensure your response uses UTF-8 too, so clients receive properly encoded text:

resp.setCharacterEncoding("UTF-8");
// Adjust content type based on your response (e.g., application/json, text/html)
resp.setContentType("application/x-www-form-urlencoded; charset=UTF-8");

3. Quick Validation Check

Make sure the client sending the request includes charset=UTF-8 in the Content-Type header, like:

Content-Type: application/x-www-form-urlencoded; charset=UTF-8

Or for JSON payloads:

Content-Type: application/json; charset=UTF-8

This ensures the client and server agree on the encoding being used.

内容的提问来源于stack exchange,提问作者Vikram Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:52:44