Have you ever wondered "What the hell is this J2EE thingy?", "How can someone use Java to develop web applications?" or even "Web pages in Java? Isn't this for applets only?".
If so, than we have something in common, for years I have been asking myself those questions, while not having enough time to dig into the subject and learn more about Java. This language had always seemed to me to slow and having an ugly GUI (remember all that applets floating around the web in the late 90-ties ?).
As I have finally found some time to study a part of J2EE consisting of Servlets and JSP (using the excellent Head First Servlets and JSP: Passing the Sun Certified Web Component Developer Exam (SCWCD) by Kathy Sierra et al.), I will present you with what I have learned. I really hope that you will benefit from the information presented below. If you have bought some kind of Tomcat hosting or some other J2EE web hosting than you can skip the first point, and go straight to the second one.
1. Getting a web container - Tomcat
First of all, you should know that most J2EE technologies (OK, maybe not most, but few crucial ones: EJB, servlets & JSP) cannot be run like normal Java applications just by invoking java executable in the command line.
Servlets, JSP and EJB need a... lets call it a framework and this kind of framework implementation specifically for servlets/JSP (called a Web Container) is Apache Tomcat, and it will be the basis for this tutorial. If you would like to use some other container than have a look at e.g. Jetty.
Now, lets start with the tutorial.
Garmin nĂ¼vi 660 wide screen GPS review
First you need to have JDK installed, which can be downloaded from http://java.sun.com/javase/downloads/index.jsp (choose JDK 5.0 Update x), and then install the JDK (if there are any problems than let me know I'll try to clarify this).
Secondly we will download tomcat from here and for this tutorial I use Tomcat 5.5.17. For the lazy ones, here is a direct link to 5.5.17 version.
Before running Tomcat, there should be a JAVA_HOME variable defined in environment, how to do it:
in Windows: Go to Control Panel, double click System, select Advanced tab, and click "Environment Variables" button. Check if there is no JAVA_HOME defined in user and system variables pointing to JDK directory, if there is then double check that it points correctly to a JDK (not JRE), if there is no such variable then click New button in system, give a JAVA_HOME name, and paste in the directory where your JDK is sitting (on my system it is "C:\Program Files\Java\jdk1.5.0_06").
in Unix: Find where you have JDK, usually "where java" or "whereis java" should give you the path to the java executable (not a symlink!), on my system it is "/opt/sun-jdk-1.5.0.07". Depending on the shell you have, setting variable will be "export JAVA_HOME=..." or "setenv JAVA_HOME ..." (replace the dots with the path to the JDK). BTW, please feel free to ask be questions if you have any problem.
Unzip the archive in a directory you want and start the file startup.bat. Unix users should first do "chmod u+x *.sh", and then run startup.sh. If everything works fine then you should see something like this:
-
Using CATALINA_BASE: /home/krzyk/apache-tomcat-5.5.17
-
Using CATALINA_HOME: /home/krzyk/apache-tomcat-5.5.17
-
Using CATALINA_TMPDIR: /home/krzyk/apache-tomcat-5.5.17/temp
-
Using JRE_HOME: /usr/lib/jvm/sun-jdk-1.5
Now go to the address http://localhost:8080/ and see if it really works, you should see a page about Apache Tomcat.
If it is correct then....

Congratulations! You have just made the first step into the J2EE world ;).
2. Writing the first servlet
Now it's time to get our hands dirty and write some code, but first we need to make some essential directories.
Create a directory where your project will be kept (I'll name it FirstApplication), under that directory
create following dirs:
-
WEB-INF
-
WEB-INF/src
-
WEB-INF/classes
If you use some java IDE (e.g. Eclipse or NetBeans) for developing code, then mark the "src" directory as the one containing the source, and the "classes" as the one with binaries. For the rest of us lets make directory for com.coderookie, that is under "src" mkdir "com" and "com/coderookie".
Go into the WEB-INF/src/com/coderookie dir, and create a file called FirstServlet.java with the following code:
-
package com.coderookie;
-
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
-
import java.io.PrintWriter;
-
import java.io.IOException;
-
-
public class FirstServlet extends HttpServlet //#1
-
{
-
public void doGet(HttpServletRequest request,
-
HttpServletResponse response)
-
{
-
out.println("Hello world!"); //#4
-
}
-
}
And now for explanations:
#1 - servlet is really just a class that extends HttpServlet and implements certain methods
#2 - here is one of those mentioned methods doGet is responsible for handling the GET method (pretty obvious) of HTTP protocol (see this wiki page for more information on HTTP methods)
#3 - HttpServletResponse has a method that allows us to get a PrintWriter for the web page output
#4 - using PrintWriter methods we can write anything (using a web page) to the user that entered our servlet
Besides writing the code, we need to write a web descriptor for our application. Descriptor is used to inform web container about the applications ingredients. You must put there such information as: what are the names your servlets, how URLs should map to a certain servlet and much more (I'll cover more in other posts).
Create a web.xml file in WEB-INF directory:
-
<web-app xmis="http://java.sun.com/xml/ns/j2ee"
-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
-
version="2.4">
-
-
<servlet>
-
<servlet-name>SimpleServlet</servlet-name>
-
<servlet-class>com.coderookie.FirstServlet</servlet-class>
-
</servlet>
-
-
<servlet-mapping>
-
<servlet-name>SimpleServlet</servlet-name>
-
<url-pattern>/first</url-pattern>
-
</servlet-mapping>
-
-
</web-app>
Don't worry about the long
Go to the WEB-INF directory and run following command (you MUST replace TOMCAT with the exact location of your tomcat installation e.g. "/home/krzyk/apache-tomcat-5.5.17" or "d:\tomcat")
For Windows users (note "\" and ";"):
-
javac -cp TOMCAT\common\lib\servlet-api.jar;classes;.
-
-d classes src\com\coderookie\FirstServlet.java
For Unix ones (here we have "/" and ":"):
-
javac -cp TOMCAT/common/lib/servlet-api.jar:classes:.
-
-d classes src/com/coderookie/FirstServlet.java
It is time to test your servlet, copy your projects directory to TOMCAT/webapps (again change TOMCAT to the directory where you have unzipped Tomcat). Change directory to TOMCAT/bin and do shutdown.bat (or shutdown.sh) and then startup.bat (or startup.sh).
If there is no error then type in a browser http://localhost:8080/PROJECT_NAME/first (where PROJECT_NAME is a name of your projects directory in webapps directory). Notice that "/first" is the url-pattern from web.xml file.
You should see a "Hello world!" displayed on this page, if it is than we have another success!
What if you would like to print a HTML page using the servlet above ?
Using println for the whole page would be a horror, just have a look at the example presented below:
-
out.println("<HTML>");
-
out.println("<HEAD>");
-
out.println("<TITLE>" + "My first page" + "</TITLE>");
-
out.println("</HEAD>");
-
out.println("<BODY>");
-
out.println("</BODY>");
-
out.println("</HTML>");
To much out.println, don't you think ? But have no fear, JSP to the rescue.
Create a file named hi.jsp (or whatever you like) and place is either in WEB-INF or in the directory of the project (the one that is higher then WEB-INF):
-
<html>
-
<head>
-
<title>${title}</title>
-
</head>
-
<body>
-
Hi World !
-
</body>
-
</html>
This page contains an EL (Expression Language) structure ${title}, which can be set from the servlet, we will use this page as a view for our servlet.
Change the code of FirstServlet to this one:
-
package com.coderookie;
-
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
import javax.servlet.RequestDispatcher;
-
import javax.servlet.ServletContext;
-
import javax.servlet.ServletException;
-
-
import java.io.IOException;
-
-
public class FirstServlet extends HttpServlet
-
{
-
public void doGet(HttpServletRequest request,
-
HttpServletResponse response)
-
throws ServletException, IOException
-
{
-
request.setAttribute("title", "My first super page"); // #1
-
-
ServletContext app = getServletContext();
-
RequestDispatcher dispatcher =
-
app.getRequestDispatcher("/hi.jsp"); //#2
-
dispatcher.forward(request,response);
-
}
-
}
Explanations:
#1 - for now, just assume, that everything dynamic that you wan to display on the JSP page, should be previously set by the setAttribute of the HttpServletRequest, first parameter is the name which you will use to display the second argument in JSP (here "title", so in JSP it will be ${title} and will be replaced by Tomcat with "My first super page")
#2 - we must get a ServletContext (this object keeps global configuration for the application), and from it, the RequestDispatcher for the JSP page, in the parameter you need to provide the path to the JSP, relative to the application folder (that is, one step higher than WEB-INF), OK this might be confusing, so look at the ASCII drawing below. And finally, we forward the control to the JSP page by calling forward method of the RequestDispatcher.
-
PROJECT_NAME
-
|
-
|- hi.jsp
-
|
-
-- WEB-INF
-
|
-
|
-
- classes
-
|
-
- src
-
|
-
- (hi.jsp - you can put it even here)
Now make your favorite drink ready, and go to the http://localhost:8080/PROJECT_NAME/first
Probably you should see a page with title "My first super page", and "Hi World!" text on it. If it works, then once again, you rule (and I haven't made any mistakes ;).
This is it for now, stay tuned for the following parts, introducing more advanced topics, you can now review material from this tutorial, play around with the JSP and servlet, have some fun. If you develop an interesting application using the very basic information above, please send me an info, a link to the application or the source code. The next part of this tutorial will be about Model-View-Controler design pattern and how to apply it to servlets and JSP.









Nice article you have there. It could also serve as a good start for those who wish to learn developing web application in Java. Although we have a lot of webframework available, it is still worth to have some knowledge about servlets and JSP as all java webframeworks comes from this.
I wonder what will cover in Part II? More on servlets? like filter? I always see this in the configuration on java webframeworks and I don’t know what is it.
Again, nice work!
Hello,
and thanks for this tutorial. Unfortunately I have come across one thing that it doesn’t cover: which JDK/JRE to use. I know this might sound stupid or obvious, but since this is a beginners-tutorial, I thought it might be helpful to know. I tried the J2SE JDK 1.5.0_08, which comes with the according JRE, but those do not include the packages required in this tutorial (javax.servlet). Since Sun still hasn’t been able to make clear where to download what (at least to me), could you please advise me on what JDK I need? It seems to me that downloading J2EE would be required, but this (both J2EE 1.4 SDK and Java EE 5 SDK) again comes with a J2SE SDK. So what’s all this then? Sun is really confusing me… I really want to solve this thing and get “my” first servlet to run. Thanks :)
Hi,
James: I haven’t decided yet what should I write in the next part, I thougt about extending the basics in servlets and JSP, thanks for the tip on filters :), maybe that will be next. have to think it over.
Christian: My few first aproaches to J2EE ended the same :) Sun doesn’t say explicitli where to download and what it is exactly, back back to your question. The packages you mention are in the Tomcat installation: TOMCAT\common\lib\servlet-api.jar. (of course, TOMCAT should be replaced with the dir where you have unzipped it)
It’s an implementation of Sun’s servlets. For me J2EE is a set of interfaces/standards, that different container developers must obey to be J2EE complaint.
Hope that helps :)
Christian, the servlet api is included with Tomcat. Look under /common/lib. The file should be named servlet-api.jar. Oh, and with latest version of Tomcat you don’t even need the JDK, just the JRE since Tomcat comes with a compiler for the JSP files.
Hi Guys,
thanks for your help, especially Kris, who figured it out. It wasn’t in the JDK after all, just a little typo.
excellent
Thank you, If u don’t understand here, u cannot understand form anywhere.
Awesome ….DUDE!!! Really a good tutorial for the beginners….
Worked great thanks.
Thanks! :)