(1)Filter與struts2x攔截器差別:Filter:當程式請求servlet,jsp時,Filter會進行攔截。程式将先經過filter後,才到達目标的servlet,jsp;常用于系統權限管理(即使用者通路某些頁面之前,進行Filter權限檢查)struts2x攔截器:隻是在程式通路Action之前進行攔截。常用于記錄系統記錄檔,或添加額外功能。 (2)Filter簡介:Filter的三個方法:init(),destroy(),doFilter(); 三個執行個體如下:(1)-------<利用filter進行中文字元處理>------------
1)
在web.xml中的配置:
<filter>
<filter-name>encoding</filter-name>
<filter-class>
org.lxh.myzngt.filter.EncodingFilter
</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>gbk</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>
private String[] doNotFilterURL;public void init(FilterConfig filterConfig) throws ServletException {
String params = filterConfig.getInitParameter("doNotFilterURL");
if (params != null) {
String urls[] = params.split(",");
doNotFilterURL = new String[urls.length];
for (int i = 0, size = urls.length; i < size; i++) {
doNotFilterURL[i] = urls[i];
}
}
}
HttpServletRequest req = (HttpServletRequest) request;
String requestPath = req.getRequestURI(); //如:demo/login.action
String contextRoot = req.getContextPath(); //如:demo int length = contextRoot.length();
String path = requestPath.substring(length); //如:/login.action
if (path != null && path.length() != 0) {
path = path.trim();
}
if (Constants.FIRST_LOGIN_URL.getStringValue().equals(path)) {
return true;
}
//擷取請求的位址,比對不需要過濾的URL的數組doNotFilterURL。
boolean doNotFilter = false;
if (doNotFilterURL != null) {
for (String url : doNotFilterURL) { if (url != null && path.contains(url.trim())) {
doNotFilter = true;
break;
}
}
} //對不屬于不用過濾的,查詢資料表,看使用者是否有權通路。若沒,則傳回提示使用者無限通路頁面。若有,則直接通過。