Filter
过滤器:用来过滤网站数据
- 乱码问题
- 登录验证…
实现对乱码的过滤
@WebServlet("/show")
public class ShowServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setCharacterEncoding("UTF-8");
// resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("你好,下午");
}
}
@WebFilter("/show/*")
//@WebFilter("/show")效果一样
public class filter implements Filter {
@Override
//初始化 web服务器启动时进行初始化
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter初始化...");
}
/*
chain:链
过滤中的所有代码,在过滤特定请求时都会执行
必须要让过滤器继续通行
*/
@Override
//doFilter()处理拦截,再通过filterChain.doFilter()来放行
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html;charset=UTF-8");
System.out.println("doFilter执行前...");
filterChain.doFilter(servletRequest, servletResponse);//让我们的请求继续,如果不写程序到这里结束
System.out.println("doFilter执行后...");
}
@Override
//销毁 web服务器关闭时进行销毁
public void destroy() {
System.out.println("filter销毁...");
}
}