Servlet/JSP乱码
JSP代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>测试服务器返回中文乱码</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <form action="solveMessyCode" method="post"> <input name="parm" id="parm" type="text" width="120" /><br /> <input type="submit" value=" 提交 " /> </form> </body> </html>
web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <servlet-name>solveJSPMessageCode</servlet-name> <servlet-class>com.slt.servlet.SolveJSPMessyCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>solveJSPMessageCode</servlet-name> <url-pattern>/solveMessyCode</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
Servlet类
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SolveJSPMessyCodeServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String parm = request.getParameter("parm"); System.out.println("页面传来的参数:" + parm); String result = "返回的参数:" + parm; response.setContentType("text/html;charset=utf-8"); response.getWriter().println(result); } }
注意:也可以使用Filter,道理是一样的。