编写过滤器
public class ThePrintLogFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { String myName = filterConfig.getInitParameter("myName") ; System.out.println("myName:"+myName); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest ; HttpServletResponse response = (HttpServletResponse)servletResponse ; String name = request.getParameter("name") ; if (!name.equals("cicada")){ response.getWriter().print("User Error !"); return ; } chain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { System.out.println("ThePrintLogFilter destroy()"); } }web.xml配置文件
<!-- 过滤器相关配置 --> <filter> <filter-name>thePrintLogFilter</filter-name> <filter-class>com.node05.servlet.filter.ThePrintLogFilter</filter-class> <init-param> <param-name>myName</param-name> <param-value>cicada</param-value> </init-param> </filter> <filter-mapping> <filter-name>thePrintLogFilter</filter-name> <url-pattern>/filterServletImpl</url-pattern> </filter-mapping>测试接口
public class FilterServletImpl extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.getWriter().print("Hello:Filter"); } } 三、Interceptor拦截器Spring框架中的拦截器Interceptor类似于Servlet中的过滤器Filter,主要用于拦截用户请求并作相应的处理。例如通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。请求转发不执行拦截、过滤;重定向执行拦截和过滤。
四、源代码地址 GitHub·地址 https://github.com/cicadasmile/java-base-parent GitEE·地址 https://gitee.com/cicadasmile/java-base-parent