JSP 開發(fā)中過濾器filter設(shè)置編碼格式的實現(xiàn)方法
JSP 開發(fā)中過濾器filter設(shè)置編碼格式的實現(xiàn)方法
我們知道為了避免提交數(shù)據(jù)的亂碼問題,需要在每次使用請求之前設(shè)置編碼格式。在你復制粘貼了無數(shù)次request.setCharacterEncoding("gb2312");后,有沒有想要一勞永逸的方法呢?能不能一次性修改所有請求的編碼呢? 用Filter吧,它的名字是過濾器,
代碼如下:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SetCharacterEncodingFilter implements Filter { //要實現(xiàn)Filter接口
//存儲編碼格式信息
private String encode = null;
public void destroy(){
}
public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain)
throws IOException,ServletException{
//轉(zhuǎn)換
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
/*
* 判斷在web.xml文件中是否配置了編碼格式的信息
* 如果為空,則設(shè)置編碼格式為配置文件中的編碼格式
* 否則編碼格式設(shè)置為GBK
*/
if(this.encode != null && !this.encode.equals("")){
request.setCharacterEncoding(this.encode);
response.setCharacterEncoding(this.encode);
}else{
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
}
/*
* 使用doFilter方法調(diào)用鏈中的下一個過濾器或目標資源(servlet或JSP頁面)。
* chain.doFilter處理過濾器的其余部分(如果有的話),最終處理請求的servlet或JSP頁面。
*/
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException{
//獲取在web.xml文件中配置了的編碼格式的信息
this.encode = config.getInitParameter("encode");
}
}
在web.xml文件中的配置信息如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 過濾器配置信息 -->
<filter>
<filter-name>SetCharacterEncodingFilter</filter-name>
<!-- 過濾器設(shè)置編碼文件 -->
<filter-class>
ssh.dlc.chp1.filter.SetCharacterEncodingFilter
</filter-class>
<init-param>
<!--
init-param元素定義了過濾器的初始化參數(shù)
-->
<description>給參數(shù)和值設(shè)置名稱和編碼類型</description>
<param-name>encode</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<!--
filter-mapping告訴容器所有與模式向匹配的請求都應(yīng)該允許通過訪問控制過濾器。
所有以.do結(jié)尾的訪問都先通過過濾器文件過濾
-->
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
</web-app>
以上就是過濾器filter設(shè)置編碼格式的方法,如有疑問請留言或者到本站社區(qū)交流討論,大家共同進步,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
動態(tài)jsp頁面轉(zhuǎn)PDF輸出到頁面的實現(xiàn)方法
最近遇到了很多坑,今天小編抽點時間給大家介紹下動態(tài)jsp頁面轉(zhuǎn)PDF輸出到頁面的實現(xiàn)方法,感興趣的朋友一起看看吧2016-10-10
Servlet動態(tài)網(wǎng)頁技術(shù)詳解
Servlet動態(tài)網(wǎng)頁技術(shù)詳解,需要的朋友可以參考一下2013-03-03

