在jsp文件中:
<%@page import="java.net.URLEncoder"%> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <a href="/WebProject/GetEncodingServlet?name=<%=URLEncoder.encode("中国", "utf-8") %>">get乱码问题</a> </body> </html>
java文件:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //req.setCharacterEncoding("utf-8"); String name = req.getParameter("name"); byte data[] = name.getBytes("iso-8859-1"); String encodingName = new String(data,"utf-8"); System.out.println("encodingName="+encodingName); System.out.println("name="+name); }
get乱码:
String name = new String(request.getParameter("input").getBytes("ISO-8859-1"),"utf-8");
post乱码:
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");