目的是让浏览网站的用户所接收到的信息的编码方式统一为utf-8,防止乱码的产生
1.没加过滤器之前:
拿jsp工程(名叫web)中的两个servlet做实验
chineseservlet.java:
resultservlet.java
在web.xml中配置:
启动服务器,在地址栏上输入:http://localhost:8080/web/chin,得到:
?????????the word get is?:?????
出现乱码,说明没有指定编码。
解决办法:
两边servlet同时设置(这里以utf-8为编码标准):
request.setcharacterencoding("utf-8");
response.setcharacterencoding("utf-8");
需要显示的时候:
string text=(string)request.getattribute("data")+"是传过来的那句话";
system.out.println(text);
outputstream out =response.getoutputstream();
out.write("<html>".getbytes());
//用html技术中meta标签模拟了一个http响应头,来控制浏览器的行为
out.write("<meta http-equiv='content-type' content='text/html;charset=utf-8'>".getbytes());
out.write(text.getbytes("utf-8"));
out.write("</html>".getbytes());
或者直接:
response.setcontenttype("text/html;charset=utf-8");
以上方法很臃肿,而且非常不简介,无法应对多个界面,所以要使用过滤器来统一设置编码。
2.加过滤器之后:
resultservlet .java:
过滤器:
传过去的那句话是(the word get is):我的中国心
没有发生乱码,说明过滤成功!!
转载请注明出处:http://blog.csdn.net/acmman/article/details/44100531