在doFilter方法中获取IllegalStateException

时间:2014-06-16 05:18:11

标签: java spring servlet-filters

当我在Spring MVC中创建一个servlet过滤器时,我得到以下异常。

 [javax.servlet.ServletException: java.lang.IllegalStateException: Cannot create a session after the response has been committed] with root cause

当我把sysout我理解为异常发生在重定向行,但不明白为什么

任何人都可以告诉我一些解决方案吗

SessionFilter.java

public class SessionFilter implements Filter {

    private ArrayList<String> urlList;

    @Override
    public void destroy() {
    }

    @Override
    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) {
                System.out.println("preparing for redirect");
                response.sendRedirect("index.jsp");
            }
        }

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("entered init");
        String urls = config.getInitParameter("avoid-urls");
        StringTokenizer token = new StringTokenizer(urls, ",");

        urlList = new ArrayList<String>();

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

        }
    }

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringMVCHibernate</display-name>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>


    <filter>
        <filter-name>SessionFilter</filter-name>
        <filter-class>com.common.dao.SessionFilter</filter-class>
        <init-param>
            <param-name>avoid-urls</param-name>
            <param-value>index.jsp</param-value>
        </init-param>
    </filter>

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

2 个答案:

答案 0 :(得分:6)

简单回答您的问题:

要避免这种情况,您应该有一个return语句,或者避免重定向或转发请求,或者这类事情应该由过滤器链中的最后一个过滤器完成。

有关详细信息,请参阅以下内容:

当您尝试在响应已提交并刷新到用户时再次发送响应时,会发生此异常。 例如:

在下面的示例代码中,首先将请求转发到index_test.jsp并将响应刷新给用户,然后控件将再次返回过滤器并尝试向用户发送另一个响应(重定向),并且会失败。

通常我们检查过滤器中的多个条件并相应地转发和重定向,如果满足两个条件,则会产生问题。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 

  request.getRequestDispatcher("index_test.jsp").forward(request, response);
  ((HttpServletResponse)response).sendRedirect("new.jsp");
  chain.doFilter(request, response);
 }

您案件的解决方案:

要避免这种情况,您应该有一个return语句,或者避免重定向或转发请求,或者这类事情应该由过滤器链中的最后一个过滤器完成。

因此您可以将代码更改为:

public class SessionFilter implements Filter {

    private ArrayList<String> urlList;

    @Override
    public void destroy() {
    }

    @Override
    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) {
                System.out.println("preparing for redirect");
                response.sendRedirect("index.jsp");
                return;
            }
        }

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("entered init");
        String urls = config.getInitParameter("avoid-urls");
        StringTokenizer token = new StringTokenizer(urls, ",");

        urlList = new ArrayList<String>();

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

        }
    }

答案 1 :(得分:0)

明显的权利:

System.out.println("preparing for redirect");
   response.sendRedirect("index.jsp");
   return; 

我们在声明之后回来了。 所以进一步的执行不会发生,所以你不会得到例外。

看到我们不能同时涉及过滤和重定向或转发,它会产生IllegalStateException,因为: 当您尝试在响应已提交并刷新到用户

时再次发送响应时,会发生此异常