Question

I'm facing a situation where if I stored a form in session, after making a new deployment of a war and trying to access the form, I get a java.lang.ClassCastException.

In order to make this transparent to the user, I wrote the following code:

try {
        command = (ReservationOfBooksCommand) request.getPortletSession().getAttribute(RESERVATION_OF_BOOKS_COMMAND_SESSION_NAME);
    } catch (ClassCastException e) {
        request.getPortletSession().removeAttribute(RESERVATION_OF_BOOKS_COMMAND_SESSION_NAME);
    }

But not sure if there is a more elegant alternative as I don't like catching RuntimeExceptions and don't want to restart the server every time I deploy a new war.

Thanks.

Was it helpful?

Solution

You can use the instanceof operator

Object command = request.getPortletSession().getAttribute(RESERVATION_OF_BOOKS_COMMAND_SESSION_NAME);

if(!(command instanceof ReservationOfBooksCommand)){
        request.getPortletSession().removeAttribute(RESERVATION_OF_BOOKS_COMMAND_SESSION_NAME);
}else{
   ...
}

OTHER TIPS

Since you've tagged this question with tomcat, I suggest that you:

  1. Create a META-INF/context.xml in your own web application.
  2. Add the following code line inside the context.xml.

Sample:

<context>
    <!-- stuff here-->

    <!-- Persistence Manager. This handles all of session Tomcat handles from our app. -->
    <Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="false">
        <Store className="org.apache.catalina.session.FileStore" /> 
    </Manager>

</context>

As Michael Barker said, most application servers cleans requests and sessions after a redeployment, by default.

To allow Tomcat to store the session, set saveOnRestart="true". This allows tomcat to store the session using PersistentManager in a FileStore (meaning, use a file storage system instead of a database storage system).

Hope this helps.

Some app servers allow the sessions to be cleared down before redeploying. Resin for example will continue to use the old code for the old session, moving new sessions onto new code. Obviously you will need to expire the users session at some point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top