解决JSP页面中文乱码插入到数据库的问题

在JSP页面使用表单注册一个用户名的时候,查看到数据库里面的表中文显示乱码的情况有两种:

  1、JSP页面传进来的参数中文就是乱码,则是前台的问题,这个时候写一个过滤器就好了,可以写如下的一个过滤器

  

public class EncodingFilter implements Filter {
String encoding;
private static final String DEFAULT_CHARACTER_ENCODING = "UTF-8";
public EncodingFilter() {
}

public void destroy() {
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here

// pass the request along the filter chain
try {
if ((encoding!=null)&&(encoding.length()>0)) {
request.setCharacterEncoding(encoding);
//验证是否进入这个if语句
System.out.println("in filter and encoding :"+encoding);
}else {
request.setCharacterEncoding(DEFAULT_CHARACTER_ENCODING);
}
} catch (UnsupportedEncodingException e) {
request.setCharacterEncoding(DEFAULT_CHARACTER_ENCODING);
e.printStackTrace();
}
chain.doFilter(request, response);
}

public void init(FilterConfig fConfig) throws ServletException {
//获取配置文件中的encoding
encoding = fConfig.getInitParameter("encoding");
//确认web容器初始化的时候这个filter也已经初始化了
System.out.println(encoding);
}

}

注意这有一个关键的地方,你使用过滤器的话,表单的提交方式必须是post,如果还是get方式,则还是乱码的

或者有个笨办法

1. 在b.jsp中把String name=request.getParameter("name");修改为
String name=new String(request.getParameter("name").getBytes("ISO-8859-1"),"GB2312");
2. 这时再在页面上显示,则就是中文了。

这样也可以的

  2、第二种造成的方法就是数据库里面的字符集的问题,这个的问题不是比较专业的从事数据库的朋友,一般不太理解其中的原理,目前我只能参考别人的办法

具体就是服务器的字符集和客户端的字符集不一致,解决办法也可以百度一下,网上就有。

原文地址:https://www.cnblogs.com/zfy-220/p/4262053.html