servlet-filter的一个例子

Filter的意思是可以在Servlet实例进行实质性的处理之前,起到“过滤”的作用.

一个Filter可以过滤一个或多个Servlet,Filter必须实现javax.Servlet.Filter接口,并且必须定义以下三个方法:init(),destory(),doFilter().

下面的例子演示记录客户端主机信息的Filter:

程序代码:
/**
* 该实例演示记录客户端主机信息的Filter
* www.javatx.cn
*/

package cn.javatx;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
* @author ljfan
*
*/

public class logFilter implements Filter {
private ServletContext context;

/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/

public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
context = arg0.getServletContext();
}

/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/

public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
context.log("[" + arg0.getRemoteHost() + "] request: " +((HttpServletRequest)arg0).getRequestURI());
arg2.doFilter(arg0, arg1);
context.log("[" + arg0.getRemoteHost() + "] done");
}

/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/

public void destroy() {
// TODO Auto-generated method stub
context = null;
}

}


当前web应用的web.xml配置为:

程序代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


<filter>
<filter-name>logFilter</filter-name>
<filter-class>cn.javatx.logFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>logFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>


最后用myeclipse插件自动部署到tomcat路径下,启动tomcat,在浏览器中输入
http://localhost:8080/Filter/ (Filter为此web应用名称)

可以在tomcat 目录的log目录下的localhost.2006-01-02.log看到以下消息:

2006-1-2 16:25:51 org.apache.catalina.core.ApplicationContext log
信息: [127.0.0.1] request: /Filter/
2006-1-2 16:25:51 org.apache.catalina.core.ApplicationContext log
信息: [127.0.0.1] done

这表明logFilter已经被server调用成功.
当然在实际应用中filter还有其他用处,象登陆验证,编码转化等.

你可能感兴趣的:(tomcat,xml,Web,servlet,MyEclipse)