Wednesday, September 10, 2008

Some notes about tomcat/hibernate/servlet

Tomcat

For tomcat applications, resources (configuration files...) should be put in directory WEB-INF/classes. The files cannot be symbolic links. They MUST be regular files in order for tomcat to handle them correctly. Of course, you can embed resources into your .jar files.
For Tomcat, the regular CLASSPATH environment variable is IGNORED. The resources (jars, configuration files...) must be put into your tomcat app directory. Read this post to see what is under the hood.
Resource/class search order for web apps: 
  • Bootstrap classes of your JVM
  • System class loader classses (described above)
  • /WEB-INF/classes of your web application
  • /WEB-INF/lib/*.jar of your web application
  • $CATALINA_HOME/lib
  • $CATALINA_HOME/lib/*.jar
The System class loader is the only place where CLASSPATH can be parsed and used. However, tomcat startup script(bin/catalina.sh) totally ignore environment variable CLASSPATH. You will figure it out if you read file bin/setclasspath.sh. In my case, first several lines are :
#  Set CLASSPATH and Java options
# 
#  $Id: setclasspath.sh 589060 2007-10-27 08:19:24Z jfclere $
# -----------------------------------------------------------------------------

# First clear out the user classpath
CLASSPATH= 
Now, you know the root of the problem right? If you want to include CLASSPATH, you can modify the bash file. I have not tried it. It should work.

Hibernate

For hibernate app, corresponding mapping tables must be created before you can run your app. Hibernate will NOT create those tables automatically for you. For the primary key property/column, If you use generator "native", you must set property of the primary key column correctly in order to let database generate primary key values correctly. For example, you can use AUTO_INCREMENT to make database automatically generate primary key values in MySQL. You can choose to use generator "assigned" to assign primary key values in your programs.
For database operations in Hibernate, you should always EXPLICITLY start and commit a transaction.

Servlet/JSP

Method Forward declared in RequestDispatcher should be understood correctly. It is an INTERNAL control transfer. It means this control transfer is TRANSPARENT to end users. One consequence is that the links in the target page, to which you forward control, MUST use absolute path instead of relative path.
For example, first a user sends request to http://domain/users/gerald.jsp. At server side, your servlet internally transfers control to /users/profiles/g/gerald.jsp. In the target page, if you have links with relative path, the paths are relative to the original request path (/users/ in this example) instead of path of the target page (/users/profiles/g/ in this example).
Your servlet should not have generated any response ( in output stream to request sender ) when redirection or forwarding is carried out.

No comments: