对于乱码问题,从jsp到mysql数据库之间的每一个步骤都要保证编码一致,包括数据库,连接数据库,jsp页面,浏览器,浏览器-jsp-antion之间传值时的编码即过滤器
这里以gbk编码为例。
1数据库:
1)创建gbk编码的数据库:GBK: create database dbname DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;
(UTF8: CREATE DATABASE `test2` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;)
2)设置连接数据库的编码:
这里用了datasource:jdbcUrl="jdbc:mysql://localhost/sshblog?useUnicode=true&characterEncoding=gbk"
接着可以通过show create table tablename;查看表的编码是否为gbk;
2.浏览器,jsp页面:
<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="gbk"%>
<% request.setCharacterEncoding("gbk"); %>
(虽然你的jsp页面设置了gbk,但是浏览器没有设置,需要设置浏览器编码方式,注意浏览器的编码方式设置成utf-8,因为浏览器没有gbk格式)3.设置一个过滤器package org.jb.common.filter; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.FilterChain; import java.io.IOException; public class SetCharacterEncodingFilter implements Filter { protected FilterConfig filterConfig; protected String encodingName; protected boolean enable; public SetCharacterEncodingFilter() { this.encodingName = "GBK"; this.enable = false; } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("GBK"); chain.doFilter(request, response); } public void destroy() { } } web.xml配置加 <filter> <filter-name>encodefilter</filter-name> <filter-class>org.jb.common.filter.SetCharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encodefilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>成功,所以说对于乱码问题要从头到尾都编码一致,包括数据库,连接数据库,jsp页面,浏览器,浏览器-jsp-antion之间传值时的
编码即过滤器。