Web容器创建FilterConfig的对象。该对象可用于从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的示例
在此示例中, 如果将param-value更改为no, 则请求将被转发到servlet, 否则过滤器将创建带有以下消息的响应:该页面正在处理中。让我们看一下FilterConfig的简单示例。在这里, 我们创建了4个文件:
- index.html
- MyFilter.java
- HelloServlet.java
- web.xml
index.html
<a href="servlet1">click here</a>
MyFilter.java
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 {
PrintWriter out=resp.getWriter();
String s=config.getInitParameter("construction");
if(s.equals("yes")){
out.print("This page is under construction");
}
else{
chain.doFilter(req, resp);//sends request to next resource
}
}
public void destroy() {}
}
HelloServlet.java
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.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<br>welcome to servlet<br>");
}
}
web.xml
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
<init-param>
<param-name>construction</param-name>
<param-value>no</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
下载此示例(使用Myeclipse IDE开发)
下载此示例(使用Eclipse IDE开发)
下载此示例(使用Netbeans IDE开发)
评论前必须登录!
注册