July 5, 2010

Your First Cup of Coffee

A friend of mine asked me to provide a simple getting started guide for a first time Java programmer and it so happened it were other people that also wanted the same thing, so all of you out there here it comes, a simple learning by example guide in Java.

The example is a simple Web application that do simple Create, Retrieve, Update and Delete (CRUD) operation against a MySQL database.

Before starting writing you need to install the following on your system.
Installing programs on Windows is a pain and I will leave that as an exercise and instead show you how that this is done on a Linux platform, Ubuntu (ubuntu.com).
$ sudo apt-get install sun-java6-jdk mysql-server mysql-query-browser maven2 


That's it! That took 3 minutes on a modest Internet connection. Are you still stuck on downloading the files on your Windows machine? And thereafter looking forward to reboot you system after each installation?

The Eclipse Ubuntu installation bundle is sadly quite old and therefore it is better to download the zip file manually and extracted it anywhere of you liking and run eclipse.exe (eclipse) in the eclipse folder.

Now lets create your database. Start the MySQL Query Browser and right click in the Schemata dockable window and then select Create Schema.... Enter simpledb.
Now double click on the newly created schema and then right click again to create a new table.



From here you can take several paths, either create a new project with maven archetype 'simple-webapp' (http://www.sonatype.com/books/mvnex-book/reference/web-sect-creating-project.html) or you can install the m2eclipse plugin (http://m2eclipse.sonatype.org/installing-m2eclipse.html) and create your project from Eclipse. Here, I will hopefully, choose the easiest way and do it manually, since we only will be needing two source files, where one will be empty – web.xml and index.jsp.
$ cd [your local workspace directory] 
$ mkdir -p first-coffee/src/main/webapp/WEB-INF


Now create you Maven Project Object Model file pom.xml in first-coffee/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelversion>4.0.0</modelVersion>
 <groupid>se.msc.example</groupId>
 <artifactid>first-coffee</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>first-coffee Maven Webapp</name>
 <url>http://www.msc.se/example</url>
 <dependencies>
  <!-- mysql jdbc driver -->
  <dependency>
   <groupid>mysql</groupId>
   <artifactid>mysql-connector-java</artifactId>
   <version>5.1.13</version>
  </dependency> 
  <!-- test support -->
  <dependency>
   <groupid>junit</groupId>
   <artifactid>junit</artifactId>
   <version>4.8.1</version>
   <scope>test</scope>
  </dependency>
 </dependencies>
 <build>
  <finalname>first-coffee</finalName>
  <pluginmanagement>
   <plugins>
    <!-- to compile with JDK 1.6 -->
    <plugin>
     <groupid>org.apache.maven.plugins</groupId>
     <artifactid>maven-compiler-plugin</artifactId>
     <configuration>
      <source>1.6</source>
      <target>1.6</target>
     </configuration>
    </plugin>
   </plugins>
  </pluginManagement>
  <plugins>
   <!-- built-in web server 'mvn jetty:run' -->
   <plugin>
    <groupid>org.mortbay.jetty</groupId>
    <artifactid>maven-jetty-plugin</artifactId>
    <configuration>
     <scanintervalseconds>1</scanIntervalSeconds>
     <stopkey>foo</stopKey>
     <stopport>9999</stopPort>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>


Now create your first-coffee/src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 version="2.5">
</web-app>


And finally your dynamic web page (first-coffee/src/main/webapp/index.jsp), where all your work be done.
<%@ page import="java.sql.*" %>
<html>
<body>
<%
 // Step 1: Load the JDBC driver. 
 Class.forName("com.mysql.jdbc.Driver");
 // Step 2: Establish the connection to the database. 
 String url = "jdbc:mysql://localhost:3306/simpledb";
 Connection conn = DriverManager.getConnection(url, "root", "root");
 // Step 3: Do possible posted logic - Create, Update or Delete
 if ("Create".equals(request.getParameter("submitCreate"))) {
  String name = request.getParameter("Name");
  Statement statement = conn.createStatement();
  statement.executeUpdate("INSERT INTO Person (Name) VALUES ('" + name + "')");
 } else if ("Update".equals(request.getParameter("submitUpdate"))) {
  String personId = request.getParameter("PersonId");
  String name = request.getParameter("Name");
  Statement statement = conn.createStatement();
  statement.executeUpdate("UPDATE Person SET Name='" + name + "' WHERE PersonId=" + personId);  
 } else if ("Delete".equals(request.getParameter("submitDelete"))) {
  String personId = request.getParameter("PersonId");
  Statement statement = conn.createStatement();
  statement.executeUpdate("DELETE FROM Person WHERE PersonId=" + personId);  
 }
%>
<table border="1">
<tr>
<th>PersonId</th>
<th>Name</th>
<th>Action</th>
</tr>
<%
 // Step 4: Load all content from table
 Statement stmt = conn.createStatement();
 ResultSet rs = stmt.executeQuery("SELECT PersonId, Name FROM Person");
 while (rs.next()) {
%>
<!-- Here we display the content of the DB table. -->
<form action="index.jsp" method="get">
<input type="hidden" name="PersonId" value='<%=rs.getString("PersonId")%>' />
<tr>
<td><%=rs.getString("PersonId")%></td>
<td><input type="text" name="Name" value="<%=rs.getString("Name")%>" /></td>
<td>
<!-- Provide simple Update and Delete Action for each DB table row. -->
<input type="submit" name="submitUpdate" value="Update" />
<input type="submit" name="submitDelete" value="Delete" />
</td>
</tr>
</form><%
 }
%>
<!-- Provide an empty row for creating new DB table row.  -->
<form action="index.jsp" method="get">

<tr>
<td> </td>
<td><input type="text" name="Name" /></td>
<td><input type="submit" name="submitCreate" value="Create" /></td>
</tr>
</form></table></body>
</html>


To test your application, simply start the Maven built in web server, from your first-coffee directory.

$ mvn jetty:run


Now open your web browser and enter the address http://localhost:8080/first-coffee/.

If you want to continue to further evolve this simple example, you can leave the jetty server running and simply refresh you web server, after saving your changes.

No comments: