gerrytan
gerrytan

Reputation: 41123

Spring RedirectAttributes results in "Cannot create a session after the response has been committed" error

Adding a redirect attributes to a flash map results in following exception

java.lang.IllegalStateException: Cannot create a session after the response has been committed
    at org.apache.catalina.connector.Request.doGetSession(Request.java:2377)
    at org.apache.catalina.connector.Request.getSession(Request.java:2097)
    at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:833)
    at org.springframework.web.servlet.support.DefaultFlashMapManager.retrieveFlashMaps(DefaultFlashMapManager.java:149)
    at org.springframework.web.servlet.support.DefaultFlashMapManager.requestCompleted(DefaultFlashMapManager.java:202)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:830)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)

This is what my request handler look like

@RequestMapping(value = "/foo", method = RequestMethod.POST)
public String getFoo(RedirectAttributes attr) {
  attr.addFlashAttribute("twiddle", "doodle");
  return "redirect:/cow";
}

Does anyone know what causes this / how to debug the problem?

Upvotes: 0

Views: 3661

Answers (3)

Mwangi Thiga
Mwangi Thiga

Reputation: 1369

Ensure that on your configuration files, the urls begin with a foward slash i.e. '/' e.g '/index.jsp'.

Upvotes: 0

abishkar bhattarai
abishkar bhattarai

Reputation: 7641

To better understand problem see this link http://nirlevy.blogspot.com/2007/09/requestdispatcherforward-and-filters.html Add more

<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher> 

in web.xml.It will work.

Upvotes: 1

gerrytan
gerrytan

Reputation: 41123

After some investigation, turns out the JSP view that served the form that posts into /foo had session=false page directive attribute like this:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"  session="false" %>

Spring redirect attributes utilizes HttpSession object, and that attribute causes HttpSession generation to be skipped. After removing that attribute / setting it to true, the redirect works fine

Upvotes: 1

Related Questions