1.数据库编码不一致导致乱码
解决方法: 首先查看数据库编码,输入:show variables like "%char%";
SET character_set_client='utf8';SET character_set_connection='utf8';SET character_set_results='utf8';
default-character-set=utf-8
2.jsp页面乱码问题
在myeclipse中jsp的默认编码为ISO-8859-8; 只需在页面头部修改为<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
3.jsp连接数据库存入中文乱码
在数据库连接时jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
4.在使用struts2可使用过滤器:
先变写一个过滤器package com.oumyye.util;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class CharacterEncodingFilter implements Filter{ protected String encoding = null; protected FilterConfig filterConfig = null; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (encoding != null) { request.setCharacterEncoding(encoding); response.setContentType("text/html; charset="+encoding); } chain.doFilter(request, response); } public void destroy() { this.encoding = null; this.filterConfig = null; }}
0001web CharacterEncodingFilter com.oumyye.util.CharacterEncodingFilter encoding UTF-8 CharacterEncodingFilter /* REQUEST FORWARD
5 处理单个字符串的中文乱码问题
String newname=new String(name.getBytes("iso-8859-1"),"utf-8"))
附:JSP中的编码设置1. pageEncoding:<%@ page pageEncoding=“UTF-8″%> 设置JSP编译成Servlet时使用的编码 2. contentType: <%@ page contentType=“text/html; charset=UTF-8″%> 对服务器响应进行重新编码,即jsp的输出流在浏览器中显示的编码 3. html页面charset:<META http-equiv=“Content-Type” content=“text/html; charset=UTF-8″> 网页的编码信息 ,说明页面制作所使用的编码 4. request.setCharacterEncoding() — 可用在servlet和jsp页面中 作用是设置对客户端请求进行重新编码的编码,即post方式提交的数据进行编码。 5. response.setCharacterEncoding() — 可用在servlet和jsp页面中 对服务器响应进行重新编码,即jsp的输出流在浏览器中显示的编码,与<%@ page contentType=“text/html;charset=UTF-8″%>一样 6. response.setContentType() — 可用在servlet和jsp页面中 对服务器响应进行重新编码,即jsp的输出流在浏览器中显示的编码,与<%@ page contentType=“text/html;charset=UTF-8″%>一样 7.response.setHeader(“Content-Type”,”text/html;charset=UTF-8″); — 可用在servlet和jsp页面中 与<META http-equiv=“Content-Type” content=“text/html; charset=UTF-8″>一样 转载自www.codeceo.com