Disable session persistence in Tomcat

This a pretty common issue when running java web applications on Tomcat. One puts an object into session and after a restart one gets:

Caused by: java.io.NotSerializableException: java.lang.Object

It may not always be java.lang.Object, any class not implementing java.io.Serializable could be in this error.

This is due to Tomcat's default behavior of serializing all the sessions and after restart trying to deserialize them. (A good question is how does tomcat serialize them in the first place, but no time to research that).

The solution is pretty simple, find tomcat_dir/conf/context.xml and find a place where it says:

<!-- Uncomment this to disable session persistence across Tomcat restarts -->

This works for both Tomcat 6 and Tomcat 7. Tomcat guys did the effort to prepare everything so it's easy for us.

This solution deserves a blog post because every once in a while I get bugged by this problem and have forgotten the solution. Now I know where to search for one.

Howto start tomcat on port 80 without root privileges on linux

Opening ports below 1024 on a *nix machine requires root privileges. If the application opening the port is exploited, then the exploiter would have full access to the machine since the application was run with root. The way to avoid this is to run the application without root privileges. Then the application has to open a port above 1024. Then the real port (<1024) has to be forwarded to the local one (>1024).

This solution would work on a wide variety of *nix machines that route with iptables. This solution is adequate not only for tomcat but for all kinds of applications and ports >1024.

  1. Check unprivileged user has java in its path. Check with java -version
  2. Check JAVA_HOME is set properly in the env of the unprivileged user.
  3. change 80 to 8080 in server.xml. Check if tomcat works with startup.sh. 8080 may be changed to any other port > 1024.
  4. execute the following to forward the port: sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
  5. After restart, do step 4 again or make permanent (depends on the linux used).

The most valuable part of this howto is the iptables script in step 4. Everything else is a prerequisite.

Note: I have made this port short by design. There are many tutorials that are quite long and explain everything. This just worked with me. I read a lot to get it to work. All I wanted is a solution that works without much explanation.

Note: I'm not an administrator or a linux/unix specialist. I have found that this solution works and allows me to start tomcat without sudo. Use at your own risk.