一个转编码的有关问题servlet
一个转编码的问题servlet
昨晚做了一个登陆servlet代码是
加上String newName=new String(name.toString().getBytes(),"utf-8");是为了转码的保险,但是登陆不成功
后台显示
用户名为:张三密码为:111111
密码或用户名错误,用户名为:????密码为:111111
去掉
String newName=new String(name.toString().getBytes(),"utf-8")
后name取值正常,这个是为什么?求解
------解决思路----------------------
------解决思路----------------------
这种问题最好是统一jsp,.java,与数据库的编码方式。
------解决思路----------------------
我发现字符编码与系统平台默认的编码方式不一致时,控制台打印的就是乱码。(我不知道原因)
你用System.out.println(System.getProperty("file.encoding"));看一下你的平台默认的编码方式是不是不是UTF-8。
------解决思路----------------------
用过滤器控制就可以了.
昨晚做了一个登陆servlet代码是
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
UserDaoImp ud=new UserDaoImp();
String name=request.getParameter("username");
String pwd=request.getParameter("password");
System.out.println("用户名为:"+name+"密码为:"+pwd);
String newName=new String(name.toString().getBytes(),"utf-8");
boolean flag=ud.login(newName, pwd);
if(flag==true){
request.getRequestDispatcher("/ShowServlet").forward(request, response);
}else{
System.out.println("密码或用户名错误,用户名为:"+newName+"密码为:"+pwd);
}
}
加上String newName=new String(name.toString().getBytes(),"utf-8");是为了转码的保险,但是登陆不成功
后台显示
用户名为:张三密码为:111111
密码或用户名错误,用户名为:????密码为:111111
去掉
String newName=new String(name.toString().getBytes(),"utf-8")
后name取值正常,这个是为什么?求解
------解决思路----------------------
String name="张三";
//获取默认编码
System.out.println(System.getProperty("file.encoding"));
//.getBytes()这样不带参数默认是以平台的默认编码进行编码
String newName=new String(name.toString().getBytes(),"utf-8");
//.getBytes("你的编码")这里是UTF-8,这样才会是正确,其实这里根本不需要转码
System.out.println(newName);
------解决思路----------------------
这种问题最好是统一jsp,.java,与数据库的编码方式。
------解决思路----------------------
public static void main(String[] args) {
System.out.println(System.getProperty("file.encoding"));
//UTF-8 ---系统默认的编码方式
String str = "汉字";
System.out.println(str);
//汉字 ---
try {
String str_gbk = new String(str.getBytes("UTF-8"),"GBK");
//同String str_gbk = new String(str.getBytes(),"GBK System.out.println(str_gbk);
//姹夊瓧 ---将编码方式转换GBK后,控制台打印为乱码 String str_utf8 = new String(str_gbk.getBytes("GBK"),"UTF-8");
System.out.println(str_utf8);
//汉字 ---将UTF-8转换为GBK再转换为UTF-8,控制台显示没有问题 } catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
我发现字符编码与系统平台默认的编码方式不一致时,控制台打印的就是乱码。(我不知道原因)
你用System.out.println(System.getProperty("file.encoding"));看一下你的平台默认的编码方式是不是不是UTF-8。
------解决思路----------------------
用过滤器控制就可以了.