<< Set up Maven and Tomcat || Homepage || A simple REST style application with Apache Wink >>

Create a Bare Minimum Configuration Test Application

  1. Create a Bare Minimum Configuration Test Application
    1. Generate an empty Web Application
    2. Build the empty application to see what is created
    3. Try to deploy the WAR file to TomCat
    4. Prepare the Maven to TomCat interaction
      1. Start TomCat
      2. Tell Maven where to find TomCat
      3. Verify TomCat Manager can extract the link to the new Web Application.
      4. Go take a look
    5. Prepare to work in Eclipse
      1. Ask Maven to generate an Eclipse project for us
      2. Import the project into Eclipse
      3. Fix Problems
    6. Add the JDBC code to access the back-end data server.
      1. Introduction
      2. The text of the file index.jsp
      3. The text of the file .\DBstuff\JDBC_Test.java
      4. The new layout
      5. Rebuild, redeploy and test
      6. Solve the missing JDBC driver
    7. Next step : REST

The previous guide was quite error prone.

In this guide, we’ll set up a simple test, that will validate everything.

The test is simple, but the set up for isn’t so simple, unfortunately.

The first step is to use Maven to create an empty project for us.

Generate an empty Web Application

Change to a place where you can create a temporary directory and mvn archetype:generate :

C:\Documents and Settings\Hasan>e:
E:\>mkdir temp
E:\>cd temp
E:\temp>mvn archetype:generate

Maven loads a great many different artifacts into your %M2_REPO% directory and finishes asking you to choose a skeleton system you’d like to use.

You want to search for and pick maven-archetype-webapp (A simple Java web application). Sometimes it’ll be #18. Sometimes #107. I have not figured out how to ensure which list of archetypes appears. Hard thing to Google for.

Since we’re just setting up a little test device here, there is no need to be methodical about file names. I chose these values:

Define value for groupId: : tempTest
Define value for artifactId: : test
Define value for version: 1.0-SNAPSHOT: :
Define value for package: tempTest: :

This got us a seemingly trivial set of directories and three files:

Neither the index.jsp nor the web.xml have anything of interest for the moment. Seemingly trivial too, is the pom.xml but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy.

Build the empty application to see what is created

If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type mvn install (first time around it’ll go out collecting dozens more required artifacts.)

We have a bunch of generated artifacts now :

Try to deploy the WAR file to TomCat

We now want Maven to put the web archive (test.war) into TomCat, so we can see if we’ve got those two installations done right. Following that, we’ll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end.

There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it is as simple as a button click, but setting that up is another can’o worms.

We execute mvn tomcat:redeploy in in the same directory as the pom.xml file and (after a mess of yet more artifacts) we get the following failure :

Prepare the Maven to TomCat interaction

There’s plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected.

  1. Is TomCat running? Can we access the TomCat Manager from a browser?
  2. Does Maven know how to find TomCat?
  3. Does Maven have Manager privileges in TomCat?

Start TomCat

Yup, I forgot I had shut down TomCat. I run the command startup

In a browser I go to the address http://rest.mowa.justtrade.net:8765/manager/html and am challenged to supply user name and password. In our case mowa_user and someDumbPWord

Run mvn tomcat:redeploy yet again. Same result.

Tell Maven where to find TomCat

Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly.

The generated file has a build section like this :

<build>
  <finalName>temp</finalName>
</build>

We need to edit it to look like this :

<build>
  <finalName>temp</finalName>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>tomcat-maven-plugin</artifactId>
      <version>1.1</version>
      <configuration>
        <server>www.mowa.justtrade.net</server>
        <url>http://www.mowa.justtrade.net:8765/manager</url>
      </configuration>
    </plugin>
  </plugins>
</build>

Let’s see what another redeploy attempt gets us ...

Good! It’s changed its complaint. The error is now :

[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Server not defined in settings.xml: www.mowa.justtrade.net
[INFO] ------------------------------------------------------------------------

We edited the settings file earlier, but it seems we need to do so again. In the file %MAVEN_HOME%\conf\settings.xml find the tag <servers> and make that section look like this :

<servers>
  <server>
    <id>www.mowa.justtrade.net</id>
    <username>mowa_user</username>
    <password>someDumbPWord</password>
  </server>
</servers>


Time for another attempt, and ... Nice!

[INFO] Building war: E:\temp\test\target\temp.war
[INFO] [tomcat:redeploy {execution: default-cli}]
[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test
[INFO] OK - Deployed application at context path /test
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------

Verify TomCat Manager can extract the link to the new Web Application.

Click on List Applications and then look down the page. It is called /test Archetype Created Web Application

Go take a look

We’re done!

Prepare to work in Eclipse

Ask Maven to generate an Eclipse project for us

To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project.

As you can see in the image below, the command mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true creates the two project descriptor files .classpath and .project with inclusion of source and javadoc files for some of the dependencies.

Import the project into Eclipse

The following steps are all we need to do to get this newly created Eclipse project into Eclipse.

In the File menu select Import...

Choose Existing Projects into Eclipse

Import the temp project as indicated.

Hit Finish to see the project instantiated easily in Eclipse.

Evidently there are some issues with finding all the required resources.

Fix Problems

The report Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'
is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now.

Pick the Libraries tab, select the problematic variable (M2_REPO/junit...) and click the Edit... button.

Good.

Now we have no errors. We can start adding the JDBC & JSF stuff.

Add the JDBC code to access the back-end data server.

After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file index.jsp and add a new one JDBC_Test.java. Simple code after-all is the point of all this infrastructure.

Introduction

The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes.

<jsp:useBean id="conn" class="JDBC_Test" scope="session"/>
       :
       :
       :
<%
    conn.doUpdate(sInsert1);
%>
       :
       :
       :
<%
    rs = conn.getResult(sSelect);
    rs.first();
%>

The class JDBC_Test methods are very simple ...

\*  For getting data out  *\
public ResultSet getResult(String sql)throws SQLException{
    return statementSelect.executeQuery(sql);
}

\*  For making changes  *\
public int doUpdate(String sql) throws SQLException {
    return statementUpdate.executeUpdate(sql);
}

The full file text is here below.

It must replace the text of the existing index.jsp (E:\temp\test\src\main\webapp\index.jsp).

The text of the file index.jsp

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
  <head>
    <meta name="generator" content=
    "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org">
    <title></title>
  </head>
  <body>
	
<%@page language="java" import="java.sql.*"%>

<p>Test connectivity of TomCat application to MySql</p>

<jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/>

<%
	try {
	
		ResultSet rs = null;
		String sMkTable = "create table if not exists test_it (id int, name varchar(16))";
		String sInsert1 = "insert into test_it values (1, 'goofy')";
		String sInsert2 = "insert into test_it values (2, 'pluto')";
		String sSelect = "select id, name from test_it";
		String sDropIt = "drop table test_it";

%>

Make table : create table if not exists test_it (id int, name varchar(16))<br/>
<%
		System.out.println("Conn is null? " + (conn == null));
		conn.doUpdate(sMkTable);
%>
<br/>Insert into table : insert into test_it values (1, 'goofy')<br/>
<%
		conn.doUpdate(sInsert1);
%>
<br/>Insert into table : insert into test_it values (2, 'pluto')<br/>
<%
		conn.doUpdate(sInsert2);
%>
<br/>Select from table : select id, name from test_it<br/>
<%
		rs = conn.getResult(sSelect);
		rs.first();
%>

<form method="POST" action="catalog1.jsp">

            <select SIZE="1" NAME="departmentnumber">
            <%while(!rs.isAfterLast()){%>
            <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option>
            <%rs.next();}%>
          </select>
          <input type="submit" value="Catalog" name="B1">
</form>

<%
		rs.close();
%>
<br/>Drop table :  drop table test_it<br/>
<%
		conn.doUpdate(sDropIt);

	} catch (Exception e) {
		out.print ("An error occurred: " + e.getMessage());
	}
%>
	
  </body>
</html>
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important.

The file must appear in the path E:\temp\test\src\main\java\DBstuff\JDBC_Test.java

The text of the file .\DBstuff\JDBC_Test.java

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
package DBstuff;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_Test
{

	Connection connSelect;
	Connection connUpdate;
	
	Statement statementSelect;
	Statement statementUpdate;
	String url;
	String errMessage;

	public JDBC_Test() {
		
		System.out.println("Constructing ConnectionBean ");

	    String sDriver = "com.mysql.jdbc.Driver";
	    String sProtocol = "jdbc:mysql";
	    String sHost = "db.mowa.justtrade.net";
	    String sPort = "3306";
	    String sDatabase = "mowa";
		
	    String sUser = "mowa_user";
	    String sPassword = "someDumbPWord";
	    
	    StringBuffer sbURL = new StringBuffer();
	    sbURL.append(sProtocol);
	    sbURL.append("://");
	    sbURL.append(sHost);
	    sbURL.append(":");
	    sbURL.append(sPort);
	    sbURL.append("/");
	    sbURL.append(sDatabase);
	    
		
		try {
			
		    Class.forName(sDriver).newInstance();

			connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword);
			connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword);
			
			System.out.println("Select connection is null? " + (connSelect == null));
			statementSelect=connSelect.createStatement(
					ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY
				);
			System.out.println("Update connection is null? " + (connUpdate == null));
			statementUpdate=connUpdate.createStatement(
					ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE
				);
			
	    } catch(java.lang.InstantiationException e) {
		      System.err.println("Exception: " + e.getMessage());
		      System.out.println("Exception: " + e.getMessage());
		      
	    } catch(java.lang.IllegalAccessException e) {
		      System.err.println("Exception: " + e.getMessage());
		      System.out.println("Exception: " + e.getMessage());
		      
	    } catch(java.lang.ClassNotFoundException e) {
		      System.err.println("Exception: " + e.getMessage());
		      System.out.println("Exception: " + e.getMessage());
		      
		} catch (SQLException e) {
			errMessage =  "driver not loaded";
			connSelect = null;
			connUpdate = null;
		}
	}

	public ResultSet getResult(String sql)throws SQLException{
	    System.out.println("Querying : " + sql);
		return statementSelect.executeQuery(sql);
	}

	public int doUpdate(String sql) throws SQLException {
	    System.out.println("Altering : " + sql);
		return statementUpdate.executeUpdate(sql);
	}
}
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

The new layout

We should have files in Eclipse and a directory structure as shown in the two images below:

Rebuild, redeploy and test

Rebuilding and redeploying are the same as we have done previously.

mvn clean
mvn install
mvn tomcat:redeploy

If all goes well, we should hit one last failure. The web page and the TomCat console log should like this :

The line Exception: com.mysql.jdbc.driver is telling us that the Web Application has no means og accessing the database.

Solve the missing JDBC driver

The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory lib for that kind of thing.

E:\temp\test>dir %CATALINA_HOME%\lib
 El volumen de la unidad C no tiene etiqueta.
 El número de serie del volumen es: AC81-FBB0

 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib

2011-02-02  20:04    <DIR>          .
2011-02-02  20:04    <DIR>          ..
2011-02-02  20:04            15,239 annotations-api.jar
2011-02-02  20:04            53,756 catalina-ant.jar
2011-02-02  20:04           129,895 catalina-ha.jar
2011-02-02  20:04           237,317 catalina-tribes.jar
2011-02-02  20:04         1,216,210 catalina.jar
2011-02-02  20:04         1,563,059 ecj-3.3.1.jar
2011-02-02  20:04            33,410 el-api.jar
2011-02-02  20:04           112,550 jasper-el.jar
2011-02-02  20:04           526,946 jasper.jar
2011-02-02  20:04            76,692 jsp-api.jar
2011-02-02  20:04            88,210 servlet-api.jar
2011-02-02  20:04           764,743 tomcat-coyote.jar
2011-02-02  20:04           253,526 tomcat-dbcp.jar
2011-02-02  20:04            70,034 tomcat-i18n-es.jar
2011-02-02  20:04            51,971 tomcat-i18n-fr.jar
2011-02-02  20:04            55,036 tomcat-i18n-ja.jar
              16 archivos      5,248,594 bytes
               2 dirs   2,292,920,320 bytes libres

We’ll find the missing Java ARchive (JAR) file on the MySql Downloads page. We want the file mysql-connector-java-5.1.15.zip. When you have downloaded it, copy the jar file into TomCat’s \lib directory. The result should look like this ...

E:\temp\test>dir %CATALINA_HOME%\lib
 El volumen de la unidad C no tiene etiqueta.
 El número de serie del volumen es: AC81-FBB0

 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib

2011-03-31  06:46    <DIR>          .
2011-03-31  06:46    <DIR>          ..
2011-02-02  20:04            15,239 annotations-api.jar
2011-02-02  20:04            53,756 catalina-ant.jar
2011-02-02  20:04           129,895 catalina-ha.jar
2011-02-02  20:04           237,317 catalina-tribes.jar
2011-02-02  20:04         1,216,210 catalina.jar
2011-02-02  20:04         1,563,059 ecj-3.3.1.jar
2011-02-02  20:04            33,410 el-api.jar
2011-02-02  20:04           112,550 jasper-el.jar
2011-02-02  20:04           526,946 jasper.jar
2011-02-02  20:04            76,692 jsp-api.jar
2011-02-08  18:25           785,998 mysql-connector-java-5.1.15-bin.jar
2011-02-02  20:04            88,210 servlet-api.jar
2011-02-02  20:04           764,743 tomcat-coyote.jar
2011-02-02  20:04           253,526 tomcat-dbcp.jar
2011-02-02  20:04            70,034 tomcat-i18n-es.jar
2011-02-02  20:04            51,971 tomcat-i18n-fr.jar
2011-02-02  20:04            55,036 tomcat-i18n-ja.jar
              17 archivos      6,034,592 bytes
               2 dirs   2,290,769,920 bytes libres

Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it.

%CATALINA_HOME%\bin\shutdown
%CATALINA_HOME%\bin\startup

If there’s nothing wrong you should see :

Next step : REST

We are ready at last to get our first REST style application up and running with the help of Apache Wink in the next stage of the guide. A simple REST style application with Apache Wink.

<< Set up Maven and Tomcat || Homepage || A simple REST style application with Apache Wink >>

Create a Bare Minimum Configuration Test Application

Etc..

All Wiki Pages

Feeds

Wiki Page

Wiki Page and Comments

Create a Bare Minimum Configuration Test Application is a public wiki page

This wiki page is a public wiki page. It can be read by anyone including users that have not logged in and web crawlers such as Google.

Entry has no comments

You do not have sufficient permissions to comment

7 years ago
hasan.bramwell picture

Text: << [Set up Maven and Tomcat] || [Homepage] || [A simple REST style application with Apache Wink] h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6470! The line @Exception: com.mysql.jdbc.driver@ is telling us that the Web Application has no means og accessing the database. h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres p. Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it. @%CATALINA_HOME%\bin\shutdown@ @%CATALINA_HOME%\bin\startup@ If there's nothing wrong you should see : !http://www.xp-dev.com/file/6471! h3. Next step : REST We are ready at last to get our first REST style application up and running with the help of Apache Wink in the next stage of the guide. [A simple REST style application with Apache Wink]. << [Set up Maven and Tomcat] || [Homepage] || [A simple REST style application with Apache Wink]<< [Set up Maven and Tomcat] || [Homepage] || [A simple REST style application with Apache Wink] >> h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6470! The line @Exception: com.mysql.jdbc.driver@ is telling us that the Web Application has no means og accessing the database. h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres p. Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it. @%CATALINA_HOME%\bin\shutdown@ @%CATALINA_HOME%\bin\startup@ If there's nothing wrong you should see : !http://www.xp-dev.com/file/6471! h3. Next step : REST We are ready at last to get our first REST style application up and running with the help of Apache Wink in the next stage of the guide. [A simple REST style application with Apache Wink]. << [Set up Maven and Tomcat] || [Homepage] || [A simple REST style application with Apache Wink] >>

hasan.bramwell picture

Text: << [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6470! The line @Exception: com.mysql.jdbc.driver@ is telling us that the Web Application has no means og accessing the database. h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres p. Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it. @%CATALINA_HOME%\bin\shutdown@ @%CATALINA_HOME%\bin\startup@ If there's nothing wrong you should see : !http://www.xp-dev.com/file/6471! << [Set up Maven and Tomcat] || [Homepage] || - - -<< [Set up Maven and Tomcat] || [Homepage] || [A simple REST style application with Apache Wink] h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6470! The line @Exception: com.mysql.jdbc.driver@ is telling us that the Web Application has no means og accessing the database. h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres p. Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it. @%CATALINA_HOME%\bin\shutdown@ @%CATALINA_HOME%\bin\startup@ If there's nothing wrong you should see : !http://www.xp-dev.com/file/6471! h3. Next step : REST We are ready at last to get our first REST style application up and running with the help of Apache Wink in the next stage of the guide. [A simple REST style application with Apache Wink]. << [Set up Maven and Tomcat] || [Homepage] || [A simple REST style application with Apache Wink]

hasan.bramwell picture

Text: << [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6470! The line @Exception: com.mysql.jdbc.driver@ is telling us that the Web Application has no means og accessing the database. h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres p. Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it. @%CATALINA_HOME%\bin\shutdown@ @%CATALINA_HOME%\bin\startup@ << [Set up Maven and Tomcat] || [Homepage] || - - -<< [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6470! The line @Exception: com.mysql.jdbc.driver@ is telling us that the Web Application has no means og accessing the database. h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres p. Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it. @%CATALINA_HOME%\bin\shutdown@ @%CATALINA_HOME%\bin\startup@ If there's nothing wrong you should see : !http://www.xp-dev.com/file/6471! << [Set up Maven and Tomcat] || [Homepage] || - - -

hasan.bramwell picture

Text: << [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6468! h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres p. Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it. @%CATALINA_HOME%\bin\shutdown@ @%CATALINA_HOME%\bin\startup@ << [Set up Maven and Tomcat] || [Homepage] || - - -<< [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6470! The line @Exception: com.mysql.jdbc.driver@ is telling us that the Web Application has no means og accessing the database. h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres p. Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it. @%CATALINA_HOME%\bin\shutdown@ @%CATALINA_HOME%\bin\startup@ << [Set up Maven and Tomcat] || [Homepage] || - - -

hasan.bramwell picture

Text: << [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6468! h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\tomcat\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres E:\temp\test> p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre,, E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de C:\programs\org\apache\tomcat\60\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres E:\temp\test> p. Now try again... mysql driver in tomcat logging << [Set up Maven and Tomcat] || [Homepage] || - - -<< [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6468! h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\apache-tomcat-6.0.32\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres p. Trying again will get you the same failure because TomCat needs to be told to reload its library, for which the easiest means right now is to stop it and restart it. @%CATALINA_HOME%\bin\shutdown@ @%CATALINA_HOME%\bin\startup@ << [Set up Maven and Tomcat] || [Homepage] || - - -

hasan.bramwell picture

Text: << [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6463! !http://www.xp-dev.com/file/6464! mysql driver in tomcat logging << [Set up Maven and Tomcat] || [Homepage] || - - -<< [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6466! !http://www.xp-dev.com/file/6468! h4. Rebuild, redeploy and test Rebuilding and redeploying are the same as we have done previously. @mvn clean@ @mvn install@ @mvn tomcat:redeploy@ If all goes well, we should hit one last failure. The web page and the TomCat console log should like this : !http://www.xp-dev.com/file/6468! h4. Solve the missing JDBC driver The one remaining task is to put the MySql JDBC driver file where TomCat can find it. TomCat searches in its directory @lib@ for that kind of thing. pre.. E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de E:\programs\org\apache\tomcat\lib 2011-02-02 20:04 <DIR> . 2011-02-02 20:04 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 16 archivos 5,248,594 bytes 2 dirs 2,292,920,320 bytes libres E:\temp\test> p. We'll find the missing Java ARchive (JAR) file on the "MySql Downloads page":http://dev.mysql.com/downloads/connector/j/. We want the file @mysql-connector-java-5.1.15.zip@. When you have downloaded it, copy the jar file into TomCat's @\lib@ directory. The result should look like this ... pre,, E:\temp\test>dir %CATALINA_HOME%\lib El volumen de la unidad C no tiene etiqueta. El número de serie del volumen es: AC81-FBB0 Directorio de C:\programs\org\apache\tomcat\60\lib 2011-03-31 06:46 <DIR> . 2011-03-31 06:46 <DIR> .. 2011-02-02 20:04 15,239 annotations-api.jar 2011-02-02 20:04 53,756 catalina-ant.jar 2011-02-02 20:04 129,895 catalina-ha.jar 2011-02-02 20:04 237,317 catalina-tribes.jar 2011-02-02 20:04 1,216,210 catalina.jar 2011-02-02 20:04 1,563,059 ecj-3.3.1.jar 2011-02-02 20:04 33,410 el-api.jar 2011-02-02 20:04 112,550 jasper-el.jar 2011-02-02 20:04 526,946 jasper.jar 2011-02-02 20:04 76,692 jsp-api.jar 2011-02-08 18:25 785,998 mysql-connector-java-5.1.15-bin.jar 2011-02-02 20:04 88,210 servlet-api.jar 2011-02-02 20:04 764,743 tomcat-coyote.jar 2011-02-02 20:04 253,526 tomcat-dbcp.jar 2011-02-02 20:04 70,034 tomcat-i18n-es.jar 2011-02-02 20:04 51,971 tomcat-i18n-fr.jar 2011-02-02 20:04 55,036 tomcat-i18n-ja.jar 17 archivos 6,034,592 bytes 2 dirs 2,290,769,920 bytes libres E:\temp\test> p. Now try again... mysql driver in tomcat logging << [Set up Maven and Tomcat] || [Homepage] || - - -

hasan.bramwell picture

Text: << [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ mysql driver in tomcat logging << [Set up Maven and Tomcat] || [Homepage] || - - -<< [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h4. The new layout We should have files in Eclipse and a directory structure as shown in the two images below: !http://www.xp-dev.com/file/6463! !http://www.xp-dev.com/file/6464! mysql driver in tomcat logging << [Set up Maven and Tomcat] || [Homepage] || - - -

hasan.bramwell picture

Text: << [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ mysql driver in tomcat logging << [Set up Maven and Tomcat] || [Homepage] || - - -<< [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. h4. Introduction The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). h4. The text of the file index.jsp pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ h4. The text of the file .\DBstuff\JDBC_Test.java pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ mysql driver in tomcat logging << [Set up Maven and Tomcat] || [Homepage] || - - -

hasan.bramwell picture

Text: << [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\temp\src\main\webapp\index.jsp@). pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\temp\src\main\java\DBstuff\JDBC_Test.java@ pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ mysql driver in tomcat logging << [Set up Maven and Tomcat] || [Homepage] || - - -<< [Set up Maven and Tomcat] || [Homepage] || - - - h1. Create a Bare Minimum Configuration Test Application {toc} The previous guide was quite error prone. In this guide, we'll set up a simple test, that will validate everything. The test is simple, but the set up for isn't *so* simple, unfortunately. The first step is to use Maven to create an empty project for us. h3. Generate an empty Web Application Change to a place where you can create a temporary directory and @mvn archetype:generate@ : @C:\Documents and Settings\Hasan>e:@ @E:\>mkdir temp@ @E:\>cd temp@ @E:\temp>mvn archetype:generate@ !http://www.xp-dev.com/file/6432! Maven loads a great many different artifacts into your @%M2_REPO%@ directory and finishes asking you to choose a skeleton system you'd like to use. !http://www.xp-dev.com/file/6433! You want to search for and pick @maven-archetype-webapp (A simple Java web application)@. Sometimes it'll be #18. Sometimes #107. I have not figured out how to ensure *which* list of archetypes appears. Hard thing to Google for. !http://www.xp-dev.com/file/6434! Since we're just setting up a little test device here, there is no need to be methodical about file names. I chose these values: @Define value for groupId: : tempTest@ @Define value for artifactId: : test@ @Define value for version: 1.0-SNAPSHOT: :@ @Define value for package: tempTest: :@ This got us a seemingly trivial set of directories and three files: !http://www.xp-dev.com/file/6428! Neither the @index.jsp@ nor the @web.xml@ have anything of interest for the moment. Seemingly trivial too, is the @pom.xml@ but it counts for a great deal; understanding which of those settings aligns with what you want to do is far from easy. h3. Build the empty application to see what is created If we tell Maven to build it, we get more artifacts. Change directory into the newly created project where the pom file is, and type @mvn install@ (first time around it'll go out collecting dozens more required artifacts.) We have a bunch of generated artifacts now : !http://www.xp-dev.com/file/6429! h3. Try to deploy the WAR file to TomCat We now want Maven to put the web archive (@test.war@) into TomCat, so we can see if we've got those two installations done right. Following that, we'll adapt our earlier JDBC connectivity test application, to work from a WAR with a JSP front-end. There is a TomCat plugin for Maven that should let us deploy to TomCat, more or less, at the click of a button. In Eclipse it *is* as simple as a button click, but setting that up is another can'o worms. We execute @mvn tomcat:redeploy@ in *in the same directory as the pom.xml file* and (after a mess of yet more artifacts) we get the following failure : !http://www.xp-dev.com/file/6435! h3. Prepare the Maven to TomCat interaction There's plenty of reasons why it might of failed, and that many things to check to get ourselves properly connected. # Is TomCat running? Can we access the TomCat Manager from a browser? # Does Maven know how to find TomCat? # Does Maven have Manager privileges in TomCat? h4. Start TomCat Yup, I forgot I had shut down TomCat. I run the command @startup@ In a browser I go to the address @http://rest.mowa.justtrade.net:8765/manager/html@ and am challenged to supply user name and password. In our case @mowa_user@ and @someDumbPWord@ Run @mvn tomcat:redeploy@ yet again. Same result. h4. Tell Maven where to find TomCat Although the Tomcat Maven plugin can remain unspecified, yet implicit, in the Project Object Model (pom.xml) file, anything out of the normal means we do have to specify it explicitly. The generated file has a build section like this : pre.. <build> <finalName>temp</finalName> </build> p. We need to edit it to look like this : pre.. <build> <finalName>temp</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <server>www.mowa.justtrade.net</server> <url>http://www.mowa.justtrade.net:8765/manager</url> </configuration> </plugin> </plugins> </build> p. Let's see what another redeploy attempt gets us ... Good! It's changed its complaint. The error is now : @[INFO] ------------------------------------------------------------------------@ @[ERROR] BUILD ERROR@ @[INFO] ------------------------------------------------------------------------@ @[INFO] Server not defined in settings.xml: www.mowa.justtrade.net@ @[INFO] ------------------------------------------------------------------------@ We edited the settings file earlier, but it seems we need to do so again. In the file @%MAVEN_HOME%\conf\settings.xml@ find the tag <servers> and make that section look like this : pre.. <servers> <server> <id>www.mowa.justtrade.net</id> <username>mowa_user</username> <password>someDumbPWord</password> </server> </servers> p. Time for another attempt, and ... Nice! @[INFO] Building war: E:\temp\test\target\temp.war@ @[INFO] [tomcat:redeploy {execution: default-cli}]@ @[INFO] Deploying war to http://www.mowa.justtrade.net:8765/test@ @[INFO] OK - Deployed application at context path /test@ @[INFO] ------------------------------------------------------------------------@ @[INFO] BUILD SUCCESSFUL@ @[INFO] ------------------------------------------------------------------------@ h4. Verify TomCat Manager can extract the link to the new Web Application. !http://www.xp-dev.com/file/6436! Click on _List Applications_ and then look down the page. It is called @/test Archetype Created Web Application@ !http://www.xp-dev.com/file/6437! h4. Go take a look !http://www.xp-dev.com/file/6438! We're done! h3. Prepare to work in Eclipse h4. Ask Maven to generate an Eclipse project for us To work with JDBC we will find it much more convenient to do it in Eclipse than a standard editor. Maven can make Eclipse understand our new project. As you can see in the image below, the command @mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true@ creates the two project descriptor files @.classpath@ and @.project@ with inclusion of source and javadoc files for some of the dependencies. !http://www.xp-dev.com/file/6440! h4. Import the project into Eclipse The following steps are all we need to do to get this newly created Eclipse project into Eclipse. In the @File@ menu select @Import...@ !http://www.xp-dev.com/file/6443! Choose @Existing Projects into Eclipse@ !http://www.xp-dev.com/file/6444! Import the temp project as indicated. !http://www.xp-dev.com/file/6445! Hit @Finish@ to see the project instantiated easily in Eclipse. !http://www.xp-dev.com/file/6446! Evidently there are some issues with finding all the required resources. h4. Fix Problems The report @Unbound classpath variable: 'M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar'@ is telling us that an internal variable of Eclipse, has been indicated, but not defined. We''l do that now. !http://www.xp-dev.com/file/6447! Pick the @Libraries@ tab, select the problematic variable (@M2_REPO/junit...@) and click the @Edit...@ button. !http://www.xp-dev.com/file/6448! !http://www.xp-dev.com/file/6449! !http://www.xp-dev.com/file/6450! !http://www.xp-dev.com/file/6451! !http://www.xp-dev.com/file/6452! !http://www.xp-dev.com/file/6453! Good. Now we have no errors. We can start adding the JDBC & JSF stuff. h3. Add the JDBC code to access the back-end data server. After all the work above the actual code seems a comical anti-climax. All we need to do is edit the file @index.jsp@ and add a new one @JDBC_Test.java@. Simple code after-all is the point of all this infrastructure. The jsp page consists of instantiation of the JDBC_Test object, and several calls to the two methods that JDBC_Test exposes. pre.. <jsp:useBean id="conn" class="JDBC_Test" scope="session"/> : : : <% conn.doUpdate(sInsert1); %> : : : <% rs = conn.getResult(sSelect); rs.first(); %> p. The class JDBC_Test methods are very simple ... pre.. \* For getting data out *\ public ResultSet getResult(String sql)throws SQLException{ return statementSelect.executeQuery(sql); } \* For making changes *\ public int doUpdate(String sql) throws SQLException { return statementUpdate.executeUpdate(sql); } p. The full file text is here below. It must replace the text of the existing index.jsp (@E:\temp\test\src\main\webapp\index.jsp@). pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> <title></title> </head> <body> <%@page language="java" import="java.sql.*"%> <p>Test connectivity of TomCat application to MySql</p> <jsp:useBean id="conn" class="DBstuff.JDBC_Test" scope="session"/> <% try { ResultSet rs = null; String sMkTable = "create table if not exists test_it (id int, name varchar(16))"; String sInsert1 = "insert into test_it values (1, 'goofy')"; String sInsert2 = "insert into test_it values (2, 'pluto')"; String sSelect = "select id, name from test_it"; String sDropIt = "drop table test_it"; %> Make table : create table if not exists test_it (id int, name varchar(16))<br/> <% System.out.println("Conn is null? " + (conn == null)); conn.doUpdate(sMkTable); %> <br/>Insert into table : insert into test_it values (1, 'goofy')<br/> <% conn.doUpdate(sInsert1); %> <br/>Insert into table : insert into test_it values (2, 'pluto')<br/> <% conn.doUpdate(sInsert2); %> <br/>Select from table : select id, name from test_it<br/> <% rs = conn.getResult(sSelect); rs.first(); %> <form method="POST" action="catalog1.jsp"> <select SIZE="1" NAME="departmentnumber"> <%while(!rs.isAfterLast()){%> <option VALUE="<%=rs.getString("id")%>"><%=rs.getString("name")%></option> <%rs.next();}%> </select> <input type="submit" value="Catalog" name="B1"> </form> <% rs.close(); %> <br/>Drop table : drop table test_it<br/> <% conn.doUpdate(sDropIt); } catch (Exception e) { out.print ("An error occurred: " + e.getMessage()); } %> </body> </html> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ p. The full text of the Java class follows. As with all artifacts in a WAR file, location and accurately matched names are all important. The file must appear in the path @E:\temp\test\src\main\java\DBstuff\JDBC_Test.java@ pre.. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ package DBstuff; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test { Connection connSelect; Connection connUpdate; Statement statementSelect; Statement statementUpdate; String url; String errMessage; public JDBC_Test() { System.out.println("Constructing ConnectionBean "); String sDriver = "com.mysql.jdbc.Driver"; String sProtocol = "jdbc:mysql"; String sHost = "db.mowa.justtrade.net"; String sPort = "3306"; String sDatabase = "mowa"; String sUser = "mowa_user"; String sPassword = "someDumbPWord"; StringBuffer sbURL = new StringBuffer(); sbURL.append(sProtocol); sbURL.append("://"); sbURL.append(sHost); sbURL.append(":"); sbURL.append(sPort); sbURL.append("/"); sbURL.append(sDatabase); try { Class.forName(sDriver).newInstance(); connSelect = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); connUpdate = DriverManager.getConnection(sbURL.toString(), sUser, sPassword); System.out.println("Select connection is null? " + (connSelect == null)); statementSelect=connSelect.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ); System.out.println("Update connection is null? " + (connUpdate == null)); statementUpdate=connUpdate.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); } catch(java.lang.InstantiationException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.IllegalAccessException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch(java.lang.ClassNotFoundException e) { System.err.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage()); } catch (SQLException e) { errMessage = "driver not loaded"; connSelect = null; connUpdate = null; } } public ResultSet getResult(String sql)throws SQLException{ System.out.println("Querying : " + sql); return statementSelect.executeQuery(sql); } public int doUpdate(String sql) throws SQLException { System.out.println("Altering : " + sql); return statementUpdate.executeUpdate(sql); } } _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ mysql driver in tomcat logging << [Set up Maven and Tomcat] || [Homepage] || - - -

hasan.bramwell picture

View View full history