小巧,但在中文语境下,还是要注意的。
以下是关键语句,注意转码的先后顺序,这源于GET是HTTP服务器处理,而POST是WEB容器处理:
String name = request.getParameter("nameGet");
name = new String(name.getBytes("ISO-8859-1"), "gb2312");================================
request.setCharacterEncoding("gb2312");
String name = request.getParameter("namePost");
package cc.openhome;import java.io.IOException;import java.io.BufferedReader;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/encoding")public class EncodingServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("nameGet"); name = new String(name.getBytes("ISO-8859-1"), "gb2312"); System.out.println("GET: " + name); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("gb2312"); String name = request.getParameter("namePost"); System.out.println("POST: " + name); String body = readBody(request); System.out.println("Body: " + body); } private String readBody(HttpServletRequest request) throws IOException{ BufferedReader reader = request.getReader(); String input = null; String requestBody = ""; while((input = reader.readLine()) != null) { requestBody += input; } return requestBody; }}