Java Servlet无法显示变音符号(Umlaut)该如何解决?
Hey there! I see you're having trouble getting umlauts (like ä, ö, ü) to display correctly in your Java Servlet. Let's break down the fixes step by step:
1. Set Request Character Encoding First
The main issue here is that you're not configuring the character encoding for incoming request parameters. By default, most servlet containers use ISO-8859-1 for request data, which will mangle UTF-8 characters like umlauts.
Add this line BEFORE you retrieve any parameters from the request:
request.setCharacterEncoding("UTF-8");
2. Strengthen Response Encoding Settings
You already set the response content type with UTF-8, which is great. To make it more robust, explicitly set the response character encoding too (some containers infer this from setContentType, but explicit configuration avoids edge cases):
response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8");
3. Updated doPost Method with Umlaut Example
Here's your modified code with all fixes applied, plus a sample umlaut-rich sentence to test display:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set request encoding FIRST request.setCharacterEncoding("UTF-8"); // Configure response encodings response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String myname = request.getParameter("benutzer"); String mypass = request.getParameter("pass"); PrintWriter myaus = response.getWriter(); // Display submitted credentials myaus.println("Deine Benutzername und pass ist : " + myname + " :: " + mypass); // Add a test sentence with umlauts myaus.println("<br><p>Heute esse ich ein leckeres Käsespätzle mit frischem Kraut!</p>"); }
Extra Tips
- If your HTML form uses POST (which it does here), add
accept-charset="UTF-8"to the<form>tag to ensure the browser sends data in UTF-8:<form method="post" accept-charset="UTF-8"> <!-- Your form fields here --> </form> - If you ever use GET requests later, you'll need to modify your servlet container's config (e.g., Tomcat's
server.xml) to addURIEncoding="UTF-8"to the Connector element, but this isn't needed for your current POST setup.
That should get your umlauts displaying perfectly!
内容的提问来源于stack exchange,提问作者sunita

