Webucator's Blog

|

Java Memory Management

In C/C++ memory management is handled by the programmer. Even after a programmer has put in a lot of effort to ensure the code is free of memory management problems, the more likely it is that they are likely to exist. The risk of these bugs increases with code size and complexity. Continue Reading »

|

JavaServerPages as Servlets

A common misconception about JavaServer Pages is that they are executed by the web container. Actually they only supply the web container with the instructions it needs to generate the Java code for a specialized servlet. That generated code is then compiled by the web container, and the resulting class is executed. To illustrate this concept, consider the simple JSP listing below:

Continue Reading »

|

Java SE 6: Top Ten Features

I remember when Sun released JDK 1.08. It was dubbed the “classic” version. After a few years of feedback from developers, Sun made some meaningful changes and additions and released the JDK 1.1. The release was given the nickname of Java SE 2. Obviously the 0.02 increment in the version number is a little misleading. A few years later, Sun released version 1.5. Once again the industry judged the changes more significant than the version indicated so they dubbed it Java 5. It happened again. The release of version1.6 is called Java SE 6. The following is a list of some of the notable additions and changes: Continue Reading »

|

Java Database Connectivity (JDBC) Basics using MySQL

I was asked to go into Java’s database API (the JDBC) using the open source database, MySQL. The JDBC is included in the Java SE and the Java EE distributions in the java.sql package. It’s designed to hide the specifics of a RDBMS from business logic. In this article I’ll cover the basics of the JDBC and what it requires to use MySQL.

Before we get started we need to install the software:

  1. Of course you will need a current revision of the JDK or Java EE installed on your computer.
  2. Download MySQL and install it. The MySQL download for Windows comes in two types: as an Installer, and as a simple ZIP file. I use the ZIP version, mysql-noinstall-5.1.48-win32.zip. Other OS platforms will require matching versions of MySQL and the installation procedures may vary.
  3. Download the MySQL jConnector. I used mysql-connector-java-5.1.13.zip. Unzip the archive and locate the mysql-connector-java-5.1.13-bin.jar file. You’ll need to point your CLASSPATH to this JAR. It contains the MySQL driver, com.mysql.jdbc.Driver.

The mysql text console utility in the bin directory of MySQL can be used to execute SQL statements. See the documentation for this utility for it’s commands and login requirements. In this example, I used the following SQL statements to establish a database and user:

create database test;
use test;

create table person (
id integer,
name varchar(30),
job_id integer,
location varchar(30)
);

grant all on test.* to roger@localhost identified by 'toast';

I populated the test database with the following statements:

insert into person (id, name, job_id, location) 
	values (1, 'Bill Smith', 1183, 'OH');
insert into person (id, name, job_id, location) 
	values (2, 'Sue Jones', 529, 'NJ');
insert into person (id, name, job_id, location) 
	values (3, 'Tom Swift', 84443, 'FL');
insert into person (id, name, job_id, location) 
	values (4, 'Bob the Builder', 34693, 'MA');
insert into person (id, name, job_id, location) 
	values (5, 'Homer Simpson', 39, 'NE');
insert into person (id, name, job_id, location) 
	values (7, 'Margo Lane', 2222, 'TX');
insert into person (id, name, job_id, location) 
	values (8, 'Bud Abbot', 5202, 'RI');

It’s not much to look at, but it does give us something to work against.

The JDBC defines five classes that our example will use:

  • java.sql.DriverManager: serves as a factory for creating Connection objects.
  • java.sql.Connection: fosters the database connection and serves as a factory for creating Statement objects.
  • java.sql.Statement: represents the SQL statement to be executed by the database.
  • java.sql.ResultSet: represents the rows and fields obtained through a SQL select statement.
  • java.sql.SQLException: all JDBC operations require this exception to be caught.

The following code serves as my Data Access Object (DAO). The block comments explain how it works:

package com.webucator.jdbc;

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

public class DAO {

   /* These variable values are used to setup
      the Connection object */

   static final String URL = "jdbc:mysql://localhost:3306/test";
   static final String USER = "roger";
   static final String PASSWORD = "toast";
   static final String DRIVER = "com.mysql.jdbc.Driver";

   /* This method is used to create a connection using 
      the values listed above. Notice the throws clause 
      in the method signature. This allows the calling method 
      to deal with the exception rather than catching it in 
      both places. The ClassNotFoundException must be caught 
      because the forName method requires it. */

   public Connection getConnection() throws SQLException {
      Connection con = null;
      try {
         Class.forName(DRIVER); 
         con = DriverManager.getConnection(URL, USER, PASSWORD);
      }
      catch(ClassNotFoundException e) {
         System.out.println(e.getMessage());
         System.exit(-1);
      }
      return con;
   }

   /* This method does most of the work. Note the try 
      and catch. Virtually all JDBC methods throw a 
      SQLException that must be tended to. The Connection 
      object is used to create a Statement object. 
      The executeQuery method is used to submit a 
      SELECT SQL query. The executeUpdate method can be 
      used to delete, change, or insert records. 
      The executeQuery method returns a ResultSet object. 
      It contains methods to navigate through the records 
      in the ResultSet object (the next method for 
      example moves the cursor to the next row; it 
      returns false when it runs out of rows) as well 
      as methods to access fields in those rows. Notice 
      that the id and job_id fields are long data types 
      while name and location are Strings. The ResultSet 
      object provides methods to deal with most common data 
      types, but it’s a good idea to review how Java data 
      types align with database data types. The report is 
      formatted using the format method introduced in Java 5.  */
	
   public void getEmployees() {
      ResultSet rs = null;
      try {
         Statement s = getConnection().createStatement();
         rs = s.executeQuery("SELECT * FROM PERSON");
         System.out.format("%3s %-15s %-7s %-7s%n", 
            "ID", "NANE", "JOB ID", 
			"LOCATION");
         System.out.format("%3s %15s %7s %7s%n", 
            "---", "---------------", 
			"-------", "--------");

         while(rs.next()) {
            long id = rs.getLong("id");
            String name = rs.getString("name");
            long job = rs.getLong("job_id");
            String location = rs.getString("location");
            System.out.format("%-3d %-15s %7d %5s%n", 
               id, name, job, location);
         }
      }
      catch(SQLException e) {
         System.out.println(e.getMessage());
         System.exit(-1);
      }
   }
}

The following class just exercises the DOA object:

package com.webucator.jdbc;

public class JDBCClient {

	public static void main(String[] args) {
		DAO dao = new DAO();
		dao.getEmployees();
	}
}

The output of this program is shown below:

ID NANE            JOB ID  LOCATION
--- --------------- ------- --------
1   Bill Smith         1183    OH
2   Sue Jones           529    NJ
3   Tom Swift         84443    FL
4   Bob the Builder   34693    MA
5   Homer Simpson        39    NE
7   Margo Lane         2222    TX
8   Bud Abbot          5202    RI

Check out our JDBC course for more information.

|

Java Application Servers: Which One Fits Your Project Best?

A common question students ask me is what’s the difference between a Java Application server and a Java EE Application server? Actually the question usually goes a bit further to include a HTTP (HyperText Transport Protocol) Server as well. Seeing as how the application server is a central player in running your projects, the question isn’t trivial.

A HTTP Server:
Client requests to a HTTP Server create a server response, usually in the form of an HTML (HyperText Markup Language) document or dynamic content through CGI (Common Gateway Interface) programs. The most popular HTTP Server is Apache, an open source Web server. The first version of Apache was developed in 1995. A distant second place in popularity is Microsoft’s IIS.

Java Application Server:
These servers are focused on Java technologies for dynamic content rather than CGI. They provide a web container capable of executing JSP (JavaServer Pages) and Servlets, a subset of the Java EE specification. They do have some HTTP Server capabilities as well, but they are usually not strong enough to meet the needs of a large, complex web site. It is common to front a Java Application Server with a HTTP Server to capitalize on the best of both worlds. The most popular Java Application Server is Tomcat from the Apache Software Foundation. Described as a "reference implementation" of the Java Servlet and the JSP specifications, Tomcat is the result of an open collaboration of developers and is available from the Apache Web site in both binary and source versions. Tomcat requires a Java Runtime Environment that conforms to JRE 1.1 or later.

Java EE Application Server:
Enterprise servers provide everything Java Application Servers do and a lot more. Java EE includes several API specifications, such as JDBC, RMI, e-mail, JMS, web services, XML, etc., and defines how to coordinate them. Java EE also features some specifications unique to Java EE components. These include Enterprise JavaBeans (EJB), Connectors, servlets, portlets, JavaServer Pages and several Web Service technologies. This allows developers to create enterprise applications that are portable and scalable, and that integrate with legacy technologies. A Java EE Application Server can handle transactions, security, scalability, concurrency and management of the components that are deployed to it.

JBoss is the most popular Java EE Application Server. It is a Red Hat, open source project supporting the JBoss Enterprise Middleware Suite (JEMS) brand. It is an alternative to commercial offerings from IBM WebSphere, Oracle BEA Services, and SAP NetWeaver. Like Tomcat, JBoss is often fronted by Apache to support clustering and cash in on its Web Server power.

|

Apache Struts: Putting the Pieces Together

The following Struts Hello World application introduces the primary players in a Struts application. It might seem like a lot of work to do a very simple job (display Hello World! in your browser), but don’t let that put you off. The real value of any framework is realized after it’s been setup. Building on it is extremely easy, efficient and maintainable from then on.

The first order of business is to create the web.xml so we can use Struts’ ActionServlet.

Continue Reading »

|

Apache Struts: A Time-Tested Java EE Framework

In a standard Java EE web application, a client typically submits information via an HTML or JSP form. The information is handed a Java servlet or another JSP for processing. This approach is not recommended for large projects. How come? You guessed it. It usually mixes model and presentation logic inappropriately making maintenance difficult. It would be nice if we had a framework that inherently supported MVC. Apache Struts to the rescue!

Continue Reading »

|

Java Frameworks: Why You Should Care

In previous articles, I talked a lot about the Model/View/Controller design pattern. Using it is recommended for all programming projects in the same way it’s recommended to pull a parachute’s ripcord when sky diving. The more independent (loosely coupled) each MVC tier is in relation to the complexities of the others, the more likely our applications will survive maintenance changes and enhancements. Equally I demonstrated how loose coupling can be employed by using JSP and JavaBeans. Continue Reading »

|

Creating Custom JSP Tags

Tag files contain JSP elements that define a custom action. A JSP tag file is similar to a normal JSP file with three exceptions:

  1. The page directive is not allowed in a tag file.
  2. There are certain JSP directives that are only allowed in a tag file.
  3. The file name extension for a tag file is “.tag”.

Everything else is the same as creating a JSP page. Continue Reading »