大家好,又见面了,我是你们的朋友全栈君。
过滤器的作用:用于过滤请求,在请求发出前后,做一些检查或操作,配置及使用步骤如下:
1.要配置Filter,首先建立一个Java类,实现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;
public class CommonFilter implements Filter{ private String name; @Override public void destroy() { // TODO Auto-generated method stub }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub System.out.println(“name==”+name); chain.doFilter(request, response); }
@Override public void init(FilterConfig FConfig) throws ServletException { // TODO Auto-generated method stub
//获取web.xml文件中的初始化参数 name = FConfig.getInitParameter(“name”); System.out.println(“caonima=”+name); }
2.在web.xml中注册该过滤器
<!– 过滤器配置 –> <filter> <display-name>通用过滤器</display-name> <filter-name>CommonFilter</filter-name> <filter-class>com.haiyan.filter.CommonFilter</filter-class> <init-param> <param-name>name</param-name> <param-value>张三</param-value> </init-param> </filter> <filter-mapping> <filter-name>CommonFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping>
3.测试使用:
启动项目,打印出结果:(因为在web.xml中我将请求路径设置为*,表示任何请求都过滤,所以项目启动,访问首页的时候,过滤器发挥了作用)
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/128672.html原文链接:https://javaforall.cn