Archive for the ‘Java’ Category

h1

Putting properties in the web xml file

January 25, 2011

If you are building a web app in Java or Scala, you might want to feed in a variable from outside which describes something special about the particular environment the web app is running on.  On a normal application you might do this from the command line with a command line argument.  In a web app, you put the variables in the web.xml file. In a maven built project this can be found in /src/main/java/webapp/WEB-INF/web.xml

The XML for the variable looks like this …

<env-entry>
<env-entry-name>PROPS_FOLDER</env-entry-name>
<env-entry-value>/opt/webapp/properties</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>

In your code, the property can be accessed by any class which extends HttpServlet. The following imports are therefore required:

import javax.servlet.http.HttpServlet;
import javax.naming.Context;
import javax.naming.InitialContext;

The property can then be accessed in your Java code like this:

Context env = (Context) (new InitialContext().lookup("java:comp/env"));
String PROPS_FOLDER = (String) env.lookup("PROPS_FOLDER");

And in Scala like this:

val env:Context = (new InitialContext().lookup("java:comp/env")).asInstanceOf[Context];
val PROPS_FOLDER:String = env.lookup("PROPS_FOLDER").asInstanceOf[String];
Advertisements
h1

Getting Java running from Maven

November 3, 2010

Good site describing how to get Java applications compiled, tested and run from mvn:

http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/

h1

Character encoding issues with MySQL and JAVA

August 12, 2010

I had an interesting (annoying) bug with one of my Java applications today. Using the MySQLConnector I was reading a record out of a table, then re-inserting it with a few fields changed. One of the untouched fields was a piece of text into which a user had used a non-standard character (a greek sigma σ). The JAVA appeared to read the original record fine and would print it out correctly to the terminal. However, writing it back the db caused it to be converted into a question mark (?). Tracked the problem down to the MySQL driver not being able to determine the character set of the database and making a guess which was wrong. You can specify the character set in the connection string like this though which fixes the problem:

jdbc:mysql://host/dbname?characterEncoding=utf8

There is a whole list of cool flags you can put on the end of the connection string listed here:
http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.htm

My other favourite is profileSQL=true which prints all the statements sent to the MySQL db to the terminal.