http请求绕过Filter的实现实例

场景:两个web服务器,A当做服务端,B为客户端,B通过Hessian远程访问A。A上加了session过期filter,通过用户信息检查session是否过期。这种情况下,Hessian会先发给filter,filter读不到用户信息就会认为过期了,引起错误。

解决方案:让hessian请求绕过session过期filter。

filter配置中,不能加exclusion,所以需要用初始化参数给出不过滤的请求。本例中不过滤的格式为>/SarService。

 <!--session过期filter -->
 <filter>
 <init-param>
  <param-name>exclusions</param-name>
  <param-value>/SarService</param-value>
 </init-param>
 <filter-name>loginFilter</filter-name>
 <filter-class>org.sigsit.vinca.sar.filter.LoginFilter
 </filter-class>
 </filter>
 <filter-mapping>
 <filter-name>loginFilter</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

Filter类中,在init中读取exclusions,并在doFilter中判断。如下:

 public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    // 由于 session 属于 HTTP 范畴,故需要向下转型成 HttpServletRequest 类型
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res=(HttpServletResponse)response;

    HttpSession session = req.getSession(); // 取得 session

    String username = (String) session.getAttribute("username");
    StringBuffer fileURL = req.getRequestURL();

    if(fileURL.indexOf(this.exclusions)!=-1){
        chain.doFilter(request, response);
    }
    else{
             //原来的处理代码
    }

  }

 public void init(FilterConfig config) throws ServletException {
 // TODO Auto-generated method stub
 this.exclusions=config.getInitParameter("exclusions");
 }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

01-28 18:34