1、Filter过滤器
过滤器、用来过滤网站的数据
- 处理中文乱码
- 登陆验证
2、使用Filter过滤器
实现Filter接口,重写对应的方法即可
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
//初始化:Web服务器启动,就已经开始初始化了,随时等待过滤对象出现
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter开始");
}
//chain : 链
/*
* 1.过滤器中的所有代码,在过滤特定请求的时候都会执行
* 2.必须要让过滤器继续执行
* chain。doFilter();
* */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("CharacterEncodingFilter执行前...");
chain.doFilter(request,response); //让我们的程序继续进行,不过不写 程序到这就就被拦截停止
System.out.println("CharacterEncodingFilter执行后....");
}
//销毁:web服务器关闭时会销毁
@Override
public void destroy() {
System.out.println("CharacterEncodingFilter销毁");
}
}
在web.xml中配置Filter
<filter>
<filter-name>showfilter</filter-name>
<filter-class>com.lantian.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>showfilter</filter-name>
<!-- 只要是 /servlet的任何请求,都会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
3、Filter实现权限拦截
用户登录之后才能进入主页!注销登录后无法进去
1、用户登录之后,向Session中放入用户的数据
2、进入主页的时候要判断用户是否已经登陆;要求:使用过滤器实现
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
Object user_session = request.getSession().getAttribute("USER_SESSION");
if(user_session==null){
response.sendRedirect("/error.jsp");
}
filterChain.doFilter(servletRequest, servletResponse);
}