过滤器基本知识
这是源代码,并没有对操作进行任何的限制
1 2 3 4 5 6 7 8
| @WebServlet("/demo01.hi") public class Test extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("demo01 is ing"); req.getRequestDispatcher("fruit/demo01.html").forward(req,resp); } }
|
下面进行限制,进行过滤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @WebFilter("/demo01.hi") public class Demo01Filter implements Filter {
@Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); }
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("我要放行给servlet"); filterChain.doFilter(servletRequest,servletResponse);
System.out.println("我要放行给浏览器"); }
@Override public void destroy() { Filter.super.destroy(); } }
|
同时servlet也可以进行通配符设置等等,和servlet相同
过滤器链
在servlet之前,可以含有多个过滤器对其进行检查过滤,最终交给servlet执行。而过滤器链的运行是按照他的全类名顺序进行运行,但是如果在配置文件中进行了过滤器的定义,那么就是按照定义的顺序进行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.zss.filter;
import javax.servlet.*; import java.io.IOException;
public class filter01 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); }
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("我是01"); filterChain.doFilter(servletRequest,servletResponse); System.out.println("01走了"); }
@Override public void destroy() { Filter.super.destroy(); } }
|
在前面的小项目中在过滤器中设置编码
1 2 3 4 5 6 7
| @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
filterChain.doFilter(servletRequest,servletResponse); }
|