本菜猫在学习Servlet表单数据,并打算实现第一个例子,
菜鸟教程
却遇到了乱码:
参考了网上大佬们的方法后,对request和response的编码做了如下修改:
然鹅,乱码仍然存在。。。
又看到了另一篇blog,去修改tomcat配置:
It still didn’t work…
于是本菜猫就debug了一下,发现title都已经乱码啦,猜测跟request和response应该无关耶
改改编译器里文件的编码试试:
我改成了GBK
明显看到,现在title不乱码了,但是站点名还是乱:
最后发现是这行代码在搞鬼:
String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), StandardCharsets.UTF_8);
猜测是因为之前(图一,二)设置了编码为UTF-8,所以用ISO-8859-1来getBytes不匹配,于是将它改成UTF-8:
String name = new String(request.getParameter("name").getBytes("UTF-8"), StandardCharsets.UTF_8);
YES!!!!!!!!!!!!!!!!!!!
后来发现,原来直接输出就可以。。
String name = new String(request.getParameter("name"));
分享一个我很喜欢的老师说过的话:
Remember every time you feel like giving up is a time for you to
improve.