📅  最后修改于: 2021-01-09 12:48:45             🧑  作者: Mango
Web容器创建FilterConfig的对象。该对象可用于从web.xml文件获取配置信息。
FilterConfig界面中有以下4种方法。
在此示例中,如果将param-value更改为no,则请求将被转发到servlet,否则过滤器将创建带有以下消息的响应:该页面正在处理中。让我们看一下FilterConfig的简单示例。在这里,我们创建了4个文件:
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() {}
}
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("
welcome to servlet
");
}
}
HelloServlet
HelloServlet
HelloServlet
/servlet1
f1
MyFilter
construction
no
f1
/servlet1