使用过滤器和重定向进行会话检查

时间:2013-03-25 05:17:34

标签: servlets servlet-filters

我正在尝试进行登录操作,但是当我使用过滤器检查会话是否有效时,我得到的异常为: - java.lang.IllegalStateException,在提交响应后无法创建会话。

Myservlet过滤器代码是: -

 public class SessionFilter implements javax.servlet.Filter 
    {

private ArrayList<String> urlList;

     public void destroy() {

}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
    throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String url = request.getServletPath();
    boolean allowedRequest = false;


    if(urlList.contains(url)) {
        allowedRequest = true;

    }

    if (!allowedRequest) {
        HttpSession session = request.getSession(false);
        if (null == session) {
            response.sendRedirect("Login.jsp");
        }
    }

  chain.doFilter(req, res);



}


public void init(FilterConfig fConfig) throws ServletException {

    String urls = fConfig.getInitParameter("avoid-urls");

    //StringTokenizer token = new StringTokenizer(urls, ",");

    StringTokenizer token = new StringTokenizer(urls);

    urlList = new ArrayList<String>();

    urlList.add(token.nextToken());

    /*while (token.hasMoreTokens()) {
        urlList.add(token.nextToken());

    }*/
}

}



  Filter mapping in web.xml is :-

<filter>
   <filter-name>SessionFilter</filter-name>
   <filter-class>Filter.SessionFilter</filter-class>

    <init-param>
      <param-name>avoid-urls</param-name>
      <param-value>Login.jsp,</param-value>
    </init-param>
</filter>

<filter-mapping>

    <filter-name>SessionFilter</filter-name>
    <url-pattern>/*</url-pattern>

</filter-mapping>

现在,当我请求login.jsp时,我得到了这个例外。请帮助我   自从过去2天以来一直困在我的项目上。

1 个答案:

答案 0 :(得分:3)

执行sendRedirect后不要继续使用过滤器。 sendRedirect会将标头提交给客户端,之后你不应该写任何东西。

将login.jsp保存到您允许的网址。

  if (!allowedRequest) {
    HttpSession session = request.getSession(false);
    if (null == session || ) {
        response.sendRedirect("Login.jsp");
        return;
    }
}

<强>参考文献:

Cause of Servlet's 'Response Already Committed'