JSP、Servlet乱码处理方法集合

来源:互联网 发布:13.3寸mac玩cf分辨率 编辑:程序博客网 时间:2024/05/24 03:59
1、页面编码和内容编码一致:<%@ page contentType="text/html; charset=UTF-8" language="java" errorPage="" pageEncoding="UTF-8" %>2、获取参数时设置编码:request.setCharacterEncoding("UTF-8");3、给URL上的中文参数进行编码,在获取参数的时候再次转码:中文编码:URLEncoder.encode("中文", "UTF-8")获取转码:String  str = URLDecoder.decode(str, "UTF-8");4、获取参数时直接给带中文的参数编码:String str = new String("".getBytes("ISO8859_1"), "UTF-8");5、修改tomcat的编码配置server.xml:< Connector port ="8080" maxHttpHeaderSize ="8192" maxThreads ="150"  minSpareThreads ="25" maxSpareThreads ="75" enableLookups ="false  redirectPort ="8443"  acceptCount ="100" connectionTimeout ="20000"  disableUploadTimeout ="true" URIEncoding ="UTF-8" /> 6、数据库连接时的编码配置:url=jdbc:mysql://127.0.0.1:3307/ybt?useUnicode=true&characterEncoding=UTF-87、在servlet里面,forward中文乱码时,输出/输入流的编码定义应该在方法的最前面(小学妹出现的问题,分享的帖子)public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {    response.setCharacterEncoding("UTF-8"); // 先指定输出流的编码response.setContentType("text/html;charset=UTF-8");    PrintWriter out = response.getWriter(); // 再拿到输出对象    RequestDispatcher requestDispatcher = request.getRequestDispatcher("/test/test2.jsp");    requestDispatcher.forward(request, response);}8、ajax的参数是中文的时候要进行编码,后台获取再解码ajax编码:encodeURIComponent(value);ajax的data是中文如果乱码的话在后台传过来之前编码,然后在js中解码:decodeURIComponent(value);