天天看點

【JSP開發】自己寫的過濾器Filter例子

目的是讓浏覽網站的使用者所接收到的資訊的編碼方式統一為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