java web 过滤器跟拦截器的区别和使用

2020-06-06 科技 146阅读

java web 过滤器跟拦截器的区别和使用分别介绍如下:

1、过滤器的使用

Filter主要对客户端的请求和服务器的响应进行过滤,使用场景:

  • 客户端的请求到达服务器,服务器真正开始处理这个请求之前,要经过Filter的过滤

  • 服务器真正的处理完这个请求,生成响应之后,要经过Filter的过滤,才能将响应发送给客户端

作用:可以通过Filter技术,对web服务器管理的所有web资源,例如JSP、Servlet、静态图片文件或静态 html文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。

  • 配置Filter

同开发Servlet一样,写完了类,接下来就是配置了,我们需要在web.xml文件中配置Filter。具体的配置和Servlet配置如出一辙。


   log
   com.jellythink.practise.LogFilter


   log
   /*
   REQUEST

上面配置中比较重要的就是url-pattern和dispatcher了。

过滤类:

public class LogFilter implements Filter
{
   private FilterConfig config;
   public void init(FilterConfig config)
   {
       this.config = config;
   }
   public void destroy()
   {
       this.config = null;
   }
   // 这个方法是Filter的核心方法
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
   throws IOException, ServletException
   {
       // 对用户的请求进行处理
       ServletContext context = this.config.getServletContext();
       long begin = System.currentTimeMillis();
       // 输出过滤信息
       System.out.println("开始过滤...");
       HttpServletRequest hRequest = (HttpServletRequest)request;
       System.out.println("Filter已经截获到用户请求的地址:" + hRequest.getServletPath());
       // 处理完以后,将请求交给下一个Filter或者Servlet处理
       chain.doFilter(request, response);
       // 对服务器的响应进行处理
       long end = System.currentTimeMillis();
       System.out.println("过滤结束");
       System.out.println("请求被定为到:" + hRequest.getRequestURI() + "; 所花费的时间为:" + (end - begin));
   }
}

2、拦截器的使用:

拦截器的主要作用是拦截用户的请求并进行相应的处理。比如通过它来进行权限验证,或者是来判断用户是否登陆,或者是像12306 那样子判断当前时间是否是购票时间。

1.在SpringMVC的配置文件中加上支持MVC的schema

xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation=" http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
 下面是声明示例:

http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    " target="_blank">http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

这样在SpringMVC的配置文件中就可以使用mvc标签了,mvc标签中有一个mvc:interceptors是用于声明SpringMVC的拦截器的。

声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com