如何解决在Servlet向数据库写记录时中文乱码?
来源:百度知道 编辑:UC知道 时间:2024/06/28 05:41:29
这是我写的转码的Bean:
public class Chinese {
public Chinese(){}
public static String toChinese(String srcStr){//此方法解决中文乱码
String str=null;
try{
byte[] b=srcStr.getBytes("ISO-8859-1");//用ISO-8859-1转换成字节数组
str=new String(b);
}
catch(Exception e){
e.printStackTrace();
}
return str;
}
}
这是向数据库写入的Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
request.setCharacterEncoding("GB2312");
OwnersBean own
1.在你的jsp页面开始的位置确保写入:
<%@ page contentType="text/html; charset=GBK" %>
2.用post提交
3.用这个转换方法再试试看
public String transform(String s)
{
String emp = null;
try {
emp = new String(s.getBytes("iso-8859-1"));
} catch (UnsupportedEncodingException e) {
System.out.println("中文处理异常:" + e.getMessage());
}
return emp;
}
4.如果还不行的话,尝试将request.setCharacterEncoding("GB2312");此句注释掉.
数据库本身的编码方式有没有设置成GB2312?
可以用filter过滤器对所有的servlet进行过滤,在过滤器里处理字符编码,对所有的字符都是用utf-8
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException,ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
httpRequest.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}
我的解决办法是在DOPOST()或者是DOGET()的开始的地方加上
request.setCharacterEncoding("GBK");