目录
1.1.写一个类实现(implements)Filter(过滤器类,Filter来自 Filter - javax,servlet接口中)。
1.2.重写三个方法
- @Override
- public void destroy() {
- System.out.println("过滤器被销毁!");
- }
-
- @Override
- public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
- throws IOException, ServletException {
- System.out.println("请求被过滤器拦截!");
- }
-
- @Override
- public void init(FilterConfig arg0) throws ServletException {
- // 启动Tomcat服务
- System.out.println("过滤器初始化/过滤器被创建!");
- }
3.1.配置过滤单个请求
@WebFilter("/index.jsp")
3.2.配置过滤多个请求
- @WebFilter(
- filterName = "loginFilter",// 配置过滤器的名字,相当于<filter-name>loginFilterfilter-name>
- urlPatterns = {"/login.jsp","/index.jsp"},// 配置过滤多个页面
- // 配置初始化参数
- initParams = {
- @WebInitParam(name = "name",value = "张三"),
- @WebInitParam(name = "sex",value = "男")
- }
- )
- // 在初始化方法里面获取配置的初始化参数
- @Override
- public void init(FilterConfig arg0) throws ServletException {
- // 启动Tomcat服务
- System.out.println("过滤器初始化/过滤器被创建!");
-
- // 获取配置的初始化参数
- String name = arg0.getInitParameter("name");
- String sex = arg0.getInitParameter("sex");
- System.out.println("name = " + name);
- System.out.println("sex = " + sex);
-
- }
1.转换参数arg0和arg1(要使用request和response里面的方法)
HttpServletRequest req = (HttpServletRequest)arg0;
HttpServletResponse resp = (HttpServletResponse)arg1;
2.设置编码
req.setCharacterEncoding("utf-8");
resp.setContentType("html/text;charset=utf-8");
3.使用arg2.doFilter(arg0, arg1),可以让被过滤器拦截的页面继续正常运行。
- public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
- throws IOException, ServletException {
- System.out.println("请求被过滤器拦截!");
-
- // 转换参数arg0和arg1
- HttpServletRequest req = (HttpServletRequest)arg0;
- HttpServletResponse resp = (HttpServletResponse)arg1;
-
- // 设置编码
- resp.setContentType("html/text;charset=utf-8");
-
-
- // 放行/继续前进
- arg2.doFilter(arg0, arg1);
- }
完