一、使浏览器不缓存页面的过滤器
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 用于的使 Browser 不缓存页面的过滤器
*/
public class ForceNoCacheFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
((HttpServletResponse) response).setHeader("Cache-Control","no-cache");
((HttpServletResponse) response).setHeader("Pragma","no-cache");
((HttpServletResponse) response).setDateHeader ("Expires", -1);
filterChain.doFilter(request, response);
}
public void destroy() { }
public void init(FilterConfig filterConfig) throws ServletException { }
}
二、检测用户是否登陆的过滤器
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.IOException;
/**
* 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面
* 配置参数
* checkSessionKey 需检查的在 Session 中保存的关键字
* redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath
* notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath
*/
public class CheckLoginFilter implements Filter {
protected FilterConfig filterConfig = null;
private String redirectURL = null;
private List notCheckURLList = new ArrayList();
private String sessionKey = null;
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession();
if(sessionKey == null) {
filterChain.doFilter(request, response);
return;
}
if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null) {
response.sendRedirect(request.getContextPath() + redirectURL);
return;
}
filterChain.doFilter(servletRequest, servletResponse);
}
public void destroy() {
notCheckURLList.clear();
}
private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
return notCheckURLList.contains(uri);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
redirectURL = filterConfig.getInitParameter("redirectURL");
sessionKey = filterConfig.getInitParameter("checkSessionKey");
String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");
if(notCheckURLListStr != null) {
StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");
notCheckURLList.clear();
while(st.hasMoreTokens()) {
notCheckURLList.add(st.nextToken());
}
}
}
}
三、字符编码的过滤器
import javax.servlet.*;
import java.io.IOException;
/**
* 用于设置 HTTP 请求字符编码的过滤器,通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题
*/
public class CharacterEncodingFilter implements Filter {
protected FilterConfig filterConfig = null;
protected String encoding = "";
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if(encoding != null)
servletRequest.setCharacterEncoding(encoding);
filterChain.doFilter(servletRequest, servletResponse);
}
public void destroy() {
filterConfig = null;
encoding = null;
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
}
}
四、资源保护过滤器
package catalog.view.util;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class SecurityFilter implements Filter {
//the login page uri
private static final String LOGIN_PAGE_URI = "login.jsf";
//the logger object
private Log logger = LogFactory.getLog(this.getClass());
//a set of restricted resources
private Set restrictedResources;
/**
* Initializes the Filter.
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.restrictedResources = new HashSet();
this.restrictedResources.add("/createProduct.jsf");
this.restrictedResources.add("/editProduct.jsf");
this.restrictedResources.add("/productList.jsf");
}
/**
* Standard doFilter object.
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
this.logger.debug("doFilter");
String contextPath = ((HttpServletRequest)req).getContextPath();
String requestUri = ((HttpServletRequest)req).getRequestURI();
this.logger.debug("contextPath = " + contextPath);
this.logger.debug("requestUri = " + requestUri);
if (this.contains(requestUri, contextPath) && !this.authorize((HttpServletRequest)req)) {
this.logger.debug("authorization failed");
((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req, res);
} else {
this.logger.debug("authorization succeeded");
chain.doFilter(req, res);
}
}
public void destroy() {}
private boolean contains(String value, String contextPath) {
Iterator ite = this.restrictedResources.iterator();
while (ite.hasNext()) {
String restrictedResource = (String)ite.next();
if ((contextPath + restrictedResource).equalsIgnoreCase(value)) {
return true;
}
}
return false;
}
private boolean authorize(HttpServletRequest req) {
//处理用户登录
/* UserBean user = (UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN);
if (user != null && user.getLoggedIn()) {
//user logged in
return true;
} else {
return false;
}*/
}
}
Servlet过滤器是一个Web应用组件,和Servlet类似,也需要在Web应用配置文件中进行配置:首先是过滤器的Web应用定义包含在<filter>…</filer>元素中,其次是Web应用的过滤器映射配置文件<filter-mapping>…</filter-mapping>
过滤器的应用很广泛,在这里介绍利用过滤器进行中文转码。一般在JavaWeb应用中,当利用request.getParameter(String str)方法获取从表单或是页面传过来的中文参数都会是一个乱码。通常会采用如下的转码方式在Servlet或是JSP中进行转码设置:
(1)request.setCharacterEncoding("gb2312");
(2)String username = request.getParameter("username");
username = new String(username.getBytes("ISO-8859-1"), "GB2312");
假设:一个表单有多数据传到Servlet或是JSP,那么就可能在这些Servlet或是JSP中写下多个request.setCharacterEncoding("gb2312")或是多个类似于String username = request.getParameter("username");
username = new String(username.getBytes("ISO-8859-1"), "GB2312");这样子肯定加大代码工作量。
针对上面的一些常见的问题,下面利用过滤器进行中文转码就可以迎刃而解。配置Filter的步骤如下:
(1)现在web.xml文件中配置如下信息
- <filter>
- <filter-name>CharactsetConversion</filter-name>
- <filter-class>com.gxa.edu.servlet.CharactsetConversion</filter-class>
- <init-param>
- <param-name>flag</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>charcode</param-name>
- <param-value>gb2312</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <!-- 配置需要过滤的URL,这里主要是对所有的文件进行过滤 -->
- <filter-name>CharactsetConversion</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
当配置好web.xml文件后,就创建一个过滤器类,名称CharactsetConversion,该类必须实现Filter接口,同时Filter接口提供了3个方法
(1)void doFilter(ServletRequest req,ServletResponse res,FilterChain filterChain)
(2)void init(FilterConfig filterConfig)
(3)void destroy()
(2)创建一个CharactsetConversion.java文件,该文件了实现Filter接口
- package com.gxa.edu.servlet;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- public class CharactsetConversion implements Filter{
- private FilterConfig filterConfig = null;
- private boolean flag = true;
- private String charcode = "gb2312";
- public void init(FilterConfig filterConfig) {
- this.filterConfig = filterConfig;
- String temp = this.filterConfig.getInitParameter("flag");
- String str = this.filterConfig.getInitParameter("charcode");
- if(temp != null){
- if(temp.equals("true")){
- this.flag = true;
- }else if(temp.equals("false")){
- this.flag = false;
- }else{
- this.flag = true;
- }
- }
- if(str != null){
- this.charcode = str;
- }
- }
- public void doFilter(ServletRequest request,ServletResponse response,FilterChain filterChain) {
- try {
- if (flag) {
- String c = request.getCharacterEncoding();
- if (c == null) {
- request.setCharacterEncoding(charcode);
- } else if (!c.equals(this.charcode)) {
- request.setCharacterEncoding(charcode);
- }
- }
- filterChain.doFilter(request, response);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void destroy() {
- this.filterConfig = null;
- }
- }
过滤器配置
1。如果要映射过滤应用程序中所有资源:
<filter>
<filter-name>loggerfilter</filter-name>
<filter-class>myfilter.LoggerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loggerfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.过滤指定的类型文件资源
<filter>
<filter-name>loggerfilter</filter-name>
<filter-class>myfilter.LoggerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loggerfilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
其中<url-pattern>*.html</url-pattern>要过滤jsp那么就改*.html为*.jsp,但是注意没有“/”斜杠
如果要同时过滤多种类型资源:
<filter>
<filter-name>loggerfilter</filter-name>
<filter-class>myfilter.LoggerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loggerfilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>loggerfilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
3.过滤指定的目录
<filter>
<filter-name>loggerfilter</filter-name>
<filter-class>myfilter.LoggerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loggerfilter</filter-name>
<url-pattern>/folder_name/*</url-pattern>
</filter-mapping>
4.过滤指定的servlet
<filter>
<filter-name>loggerfilter</filter-name>
<filter-class>myfilter.LoggerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loggerfilter</filter-name>
<servlet-name>loggerservlet</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>loggerservlet</servlet-name>
<servlet-class>myfilter.LoggerServlet</servlet-class>
</servlet>
5.过滤指定文件
<filter>
<filter-name>loggerfilter</filter-name>
<filter-class>myfilter.LoggerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loggerfilter</filter-name>
<url-pattern>/simplefilter.html</url-pattern>
</filter-mapping>
以上都要注意是否有斜杠“/”