数据库中用户名是中文时乱码,web程序无法查询

1。因为数据库编码默认是"iso-8859-1"而我的web项目编码是UTF-8.所以

//得到用户名和密码
    String u=request.getParameter("username");
    String p=request.getParameter("passwd");
    u=new String(u.getBytes("iso-8859-1"),"UTF-8");
    System.out.println("u="+u+"p="+p);

或者把它定义为一个工具类,用到的时候调用Tools.java

package com.lei.model;

public class Tools {
    //提供一个方法,将乱码转换成utf-8,gb2312,gbk
    public static String getNewString(String input) {
        String result="";
        try {
            result=new String(input.getBytes("iso-8859-1"),"UTF-8");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}

上面的就可以换成调用:u=Tools.getNewString(u);

2.修改tomcat的server.xml,据说不稳定,这里不做说明了

原文地址:https://www.cnblogs.com/Yogurshine/p/3018684.html