嵌入式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-1for parsing request parameters viagetParameterMap(), 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

