FilterConfig的对象由Web容器创建。这个对象可用于获取web.xml文件中的配置信息。
FilterConfig接口的方法
FilterConfig接口中有以下4个方法。
public void init(FilterConfig config): init()方法仅在初始化过滤器时被调用(只调用一次)。public String getInitParameter(String parameterName): 返回指定参数名称的参数值。public java.util.Enumeration getInitParameterNames(): 返回包含所有参数名称的枚举。public ServletContext getServletContext(): 返回ServletContext对象。
FilterConfig示例在此示例中,如果将web.xml的中的construction参数值为no,则请求将转发到servlet,如果将参数值设置为:yes,则过滤器将使用消息创建响应:”此页面正在处理中“。下面来看看FilterConfig的简单例子。
打开Eclipse,创建一个动态Web项目:FilterConfig,其完整的目录结构如下所示 -
以下是这个项目中的几个主要的代码文件。在这里创建了4个文件:
index.html - 应用程序入口MyFilter.java - 过滤器实现HelloServlet.java - 一个简单的Servletweb.xml - 项目部署配置文件
下面是这几个文件的具体代码。
文件:index.html -
文件:MyFilter.java -
package com.zaixian;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MyFilter implements Filter {
FilterConfig config;
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
req.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
String s = config.getInitParameter("construction");
if (s.equals("yes")) {
out.print("此页面正在处理中");
} else {
chain.doFilter(req, resp);// sends request to next resource
}
}
public void destroy() {
}
}
文件:HelloServlet.java -
package com.zaixian;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print("
welcome to servlet
");
}
}
文件:web.xml -
xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
在编写上面代码后,部署此Web应用程序(在项目名称上点击右键->”Run On Server…”),打开浏览器访问URL: http://localhost:8080/FilterConfig/ ,如果没有错误,应该会看到以下结果 -
点击页面中的链接,应该会看到以下结果 -
上一篇:
Servlet身份验证过滤器
下一篇:
Servlet过滤器示例