- Filter过滤器接口:
- Filter接口实现类需要由开发人员编写,Http服务器不提供;
- Filter接口在Http服务器调用资源文件之前,对Http服务器进行拦截过滤;
- 作用:
- 1)拦截Http服务器,帮助Http服务器检测当前请求合法性;
- 2)拦截Http服务器,对当前请求进行增强操作;
- Filter接口实现类开发步骤:
- 1>创建1个Java类,实现Filter接口;
- 2>重写Filter接口中的doFilter()方法; ```java package com.jiangzhiyan.filter;
import javax.servlet.*; import java.io.IOException;
public class OneFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //1.拦截请求对象得到请求包参数信息 Integer age = Integer.valueOf(servletRequest.getParameter(“age”)); //2.帮助Http服务器判定本次请求合法性 if (age<18 || age>=70){ //如果不合法,过滤器代替Http服务器拒绝本次请求 servletResponse.setContentType(“text/html;charset=utf-8”); servletResponse.getWriter().println(“
年龄不合法,无法访问!
- 3>web.xml文件中将Filter接口实现类注册到Http服务器;
```xml
<!--注册过滤器实现类-->
<filter> <!--1.将过滤器实现类路径交给TomCat-->
<filter-name>oneFilter</filter-name>
<filter-class>com.jiangzhiyan.filter.OneFilter</filter-class>
</filter>
<filter-mapping> <!--2.通知TomCat在调用何种资源文件时需要被拦截-->
<filter-name>oneFilter</filter-name>
<url-pattern>/pic.png</url-pattern>
</filter-mapping>
- 拦截地址的4种格式:
<!--1.拦截具体的某个文件-->
<url-pattern>/img/pic.png</url-pattern>
<!--2.拦截某个(img)文件夹下所有文件-->
<url-pattern>/img/*</url-pattern>
<!--3.拦截所有文件夹下的某种类型文件-->
<url-pattern>*.png</url-pattern>
<!--4.拦截所有文件夹下的所有文件-->
<url-pattern>/*</url-pattern>
- 过滤器对拦截的请求进行增强操作: ```java package com.jiangzhiyan.filter;
import javax.servlet.*; import java.io.IOException;
public class OneFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //设置请求对象编码字符集(针对Post请求) servletRequest.setCharacterEncoding(“utf-8”); //放行 filterChain.doFilter(servletRequest,servletResponse); } }
- 防止用户恶意访问:必须通过登录验证才给访问者派发Session对象,否则Session为null,无法访问其他资源.
```java
package com.jiangzhiyan.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class OneFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//ServletRequest接口中没有getSession()方法,强转为HttpServletRequest类型(子接口)
HttpServletRequest request = (HttpServletRequest)servletRequest;
//获取访问地址的uri
String uri = request.getRequestURI();
//如果uri访问的是login相关资源,或欢迎页面,直接放行
if (uri.contains("login") || uri.contains("Login") || "/005web/".equals(uri)){
filterChain.doFilter(servletRequest,servletResponse);
return;
}
//获取对话作用域对象session
HttpSession session = request.getSession(false);
//如果session为null,则代表为非法访问
if (session == null){
request.getRequestDispatcher("userLoginFail.html").forward(servletRequest,servletResponse);
return;
}else {
filterChain.doFilter(servletRequest,servletResponse);
}
}
}