I fixed this problem.
In case anyone else experiences this, the issue was not with the code.
I am using the Eclipse
IDE, and starting and stopping the server with a
Tomcat plugin. Whilst developing, I encountered the behaviour described above.
However, when I exported the project as a WAR file to the Tomcat directory, and started the Tomcat server from its bin folder, the program worked correctly.