Servle过滤器详解
-
Servlet过滤器的基本原理:
在Servlet作为过滤器使用时,它可以对客户的请求进行处理。处理完成后,它会交给下一个过滤器处理,这样,客户的请求在过滤链里逐个处理,直到请求发送到目标为止。例如,实现用户操作的某个功能,得过滤当前非登录用户的操作,还得过滤处理编码方式,一般是先处理统一编码方式,这两项工作可以在由两个过滤器组成的过滤链里进行处理,过滤链顾名思义就是多个过滤器顺序执行,执行完过滤编码方式后执行非登录过滤。当过滤链处理成功后,把提交的数据发送到最终目标;如果过滤器处理不成功,将把视图派发到指定的错误页面。
-
过滤器生命周期的四个阶段:
2、初始化:实例化完成之后,马上进行初始化工作。Web容器回调init()方法。
3、过滤:请求路径匹配过滤器的URL映射时。Web容器回调doFilter()方法——主要的工作方法。
4、销毁: Web容器在卸载Web应用程序前,Web容器回调destroy()方法。
-
Servlet过滤器开发步骤:
2、过滤器的xml配置。
-
Filter接口:
public void init(FilterConfig config) throws ServletException;//初始化
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException;//过滤
public void destroy();//销毁
-
FilterConfig接口:
public String getFilterName();//获取过滤器名
public ServletContext getServletContext();//获取servlet上下文
public String getInitParameter(String name);//获取参数值
public Enumeration getInitParameterNames();//获取参数值组
-
FilterChain接口:
此接口用于调用过滤链中的下一个过滤器,如果不调用此方法,之后的过滤器就不会有效。
-
字符集过滤器、Session过滤器、资源过滤器详细代码:
SetCharacterEncodingFilter.java:
package com.tjcyjd.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;
/**
* 字符集编码过滤器
*
* @author yjd
*
*/
public class SetCharacterEncodingFilter implements Filter {
public SetCharacterEncodingFilter() {
System.out.println("回调字符集过滤器的无参构造方法!");
}
private String charset; // 编码方式
private boolean flag; // 标识是否启用过滤器
public void destroy() {
// 销毁过滤器
System.out.println("销毁字符集过滤器!");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (flag && null != charset) { // 过滤器设为启用且字符编码不为空
// 设置编码方式
request.setCharacterEncoding(charset);
response.setCharacterEncoding(charset);
System.out.println("成功使用了字符集过滤器");
} else {
System.out.println("没有启用字符集过滤器");
}
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
// 初始化过滤器
this.charset = config.getInitParameter("charset");
this.flag = "true".equals(config.getInitParameter("flag"));
System.out.println("设置的字符集编码方式为:" + charset + " 是否启用:" + flag);
}
}
SessionFilger.java:
package com.tjcyjd.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;
/**
* session过滤器
*
* @author yjd
*
*/
public class SessionFilter implements Filter {
public SessionFilter() {
System.out.println("回调Session过滤器的无参构造方法!");
}
private boolean flag; // 标识是否启用过滤器
public void destroy() {
// 销毁过滤器
System.out.println("销毁Session过滤器!");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (flag) { // 过滤器设为启用
System.out.println("成功使用了Session过滤器");
} else {
System.out.println("没有启用Session过滤器");
}
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
// 初始化过滤器
this.flag = "true".equals(config.getInitParameter("flag"));
System.out.println("设置Session过滤器是否启用:" + flag);
}
}
ResourceFilter.java:
package com.tjcyjd.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;
/**
* Resource过滤器
*
* @author yjd
*
*/
public class ResourceFilter implements Filter {
public ResourceFilter() {
System.out.println("回调Resource过滤器的无参构造方法!");
}
private boolean flag; // 标识是否启用过滤器
public void destroy() {
// 销毁过滤器
System.out.println("销毁Resource过滤器!");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (flag) { // 过滤器设为启用
System.out.println("成功使用了Resource过滤器");
} else {
System.out.println("没有启用Resource过滤器");
}
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
// 初始化过滤器
this.flag = "true".equals(config.getInitParameter("flag"));
System.out.println("设置Resource过滤器是否启用:" + flag);
}
}
控制器类FilterTest.java:
package com.tjcyjd.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FilterTest extends HttpServlet {
private static final long serialVersionUID = -4431292272342933498L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("你看行不行??");
out.flush();
out.close();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
配置文件web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http:///xml/ns/j2ee"
xmlns:xsi="http:///2001/XMLSchema-instance"
xsi:schemaLocation="http:///xml/ns/j2ee
http:///xml/ns/j2ee/web-app_2_4.xsd">
<!-- 配置字符集过滤器-->
<filter>
<filter-name>myCharsetFilter</filter-name>
<filter-class>com.tjcyjd.filter.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>flag</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- 配置session过滤器-->
<filter>
<filter-name>mySessionFilter</filter-name>
<filter-class>com.tjcyjd.filter.SessionFilter</filter-class>
<init-param>
<param-name>flag</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- 配置resource过滤器-->
<filter>
<filter-name>myResourceFilter</filter-name>
<filter-class>com.tjcyjd.filter.ResourceFilter</filter-class>
<init-param>
<param-name>flag</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- 过滤器映射文件-->
<filter-mapping>
<filter-name>myCharsetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>mySessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>myResourceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置servlet-->
<servlet>
<servlet-name>filterTest</servlet-name>
<servlet-class>com.tjcyjd.controller.FilterTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>filterTest</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
部署项目启动后,控制台打印的信息:
回调Session过滤器的无参构造方法!
设置Session过滤器是否启用:true
回调Resource过滤器的无参构造方法!
设置Resource过滤器是否启用:true
回调字符集过滤器的无参构造方法!
设置的字符集编码方式为:UTF-8 是否启用:true
请求访问http://localhost:8080/2012-00001-filter/test时,过滤器执行信息如下:
成功使用了字符集过滤器
成功使用了Session过滤器
成功使用了Resource过滤器
可见,执行顺序和配置文件配置的映射顺序有关系,配置在前的先执行。
停止服务器控制台信息如下:
销毁Session过滤器!
销毁Resource过滤器!
销毁字符集过滤器!
从上面看出,init()和destroy()方法是和过滤器映射逆序执行的,估计类似栈吧,先把所有的过滤器放到栈里,先进后出,这样的理解不知道对不对。
-
五个常用过滤器(转):
此接口用于调用过滤链中的下一个过滤器,如果不调用此方法,之后的过滤器就不会有效。
1、使用浏览器不缓存页面的过滤器:
ForceNoCacheFilter.java
package filter;
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 {
}
}
2、检查用户是否登录的过滤器:
CheckLoginFilter.java
package filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
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;
import javax.servlet.http.HttpSession;
/**
* 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面
*
*
* 配置参数
*
*
* 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());
}
}
}
}
3、字符集编码过滤器:
CharacterEncodingFilter.java
package filter;
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");
}
}
4、资源保护过滤器:
SecurityFilter.java
package filter;
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; //
/**
* 资源保护过滤器
*/
public class SecurityFilter implements Filter {
// the login page uri
private static final String LOGIN_PAGE_URI = "login.jsf";
// a set of restricted resources
private Set restrictedResources;
public void init(FilterConfig filterConfig) throws ServletException {
this.restrictedResources = new HashSet();
this.restrictedResources.add("/createProduct.jsp");
this.restrictedResources.add("/editProduct.jsp");
this.restrictedResources.add("/productList.jsp");
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
String contextPath = ((HttpServletRequest) req).getContextPath();
String requestUri = ((HttpServletRequest) req).getRequestURI();
if (this.contains(requestUri, contextPath)
&& !this.authorize((HttpServletRequest) req)) {
((HttpServletRequest) req).getRequestDispatcher(LOGIN_PAGE_URI)
.forward(req, res);
} else {
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; }
*/
return true;
}
}
5、限制用户浏览权限:
RightFilter.java
package 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;
public class RightFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest sreq, ServletResponse sres,
FilterChain arg2) throws IOException, ServletException {
// 获取uri地址
HttpServletRequest request = (HttpServletRequest) sreq;
String uri = request.getRequestURI();
String ctx = request.getContextPath();
uri = uri.substring(ctx.length());
// 判断admin级别网页的浏览权限
if (uri.startsWith("/admin")) {
if (request.getSession().getAttribute("admin") == null) {
request.setAttribute("message", "您没有这个权限");
request.getRequestDispatcher("/login.jsp").forward(sreq, sres);
return;
}
}
// 判断manage级别网页的浏览权限
if (uri.startsWith("/manage")) {
// 这里省去
}
}
// 下面还可以添加其他的用户权限,省去。
public void init(FilterConfig arg0) throws ServletException {
}
}