50% off from Dreamhost hosting plan (that's 59.50$ less for full hosting) - use promo code HOSTING_PROMO during account cration on Dreamhost

Nowalijka - Śledzenie nowych aukcji allegro

question markHave 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.

Tomcat1. 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-". 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:

  1. Using CATALINA_BASE:   /home/krzyk/apache-tomcat-5.5.17
  2. Using CATALINA_HOME:   /home/krzyk/apache-tomcat-5.5.17
  3. Using CATALINA_TMPDIR: /home/krzyk/apache-tomcat-5.5.17/temp
  4. 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:

  1. WEB-INF
  2. WEB-INF/src
  3. 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:

  1. package com.coderookie;
  3. import javax.servlet.http.HttpServlet;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  7. import java.io.PrintWriter;
  8. import java.io.IOException;
  10. public class FirstServlet extends HttpServlet //#1
  11. {
  12.   public void doGet(HttpServletRequest request,
  13.         HttpServletResponse response)
  14.     throws IOException                        //#2
  15.     {
  16.       PrintWriter out = response.getWriter(); //#3
  17.       out.println("Hello world!");            //#4
  18.     }
  19. }

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:

  1. <web-app xmis="http://java.sun.com/xml/ns/j2ee"
  2.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
  4.   version="2.4">
  6.   <servlet>
  7.     <servlet-name>SimpleServlet</servlet-name>
  8.     <servlet-class>com.coderookie.FirstServlet</servlet-class>
  9.   </servlet>
  11.   <servlet-mapping>
  12.     <servlet-name>SimpleServlet</servlet-name>
  13.     <url-pattern>/first</url-pattern>
  14.   </servlet-mapping>
  16. </web-app>

Don't worry about the long tag, you will copy it between different applications, you do not have to memorize it.

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 ";"):

  1. javac -cp TOMCAT\common\lib\servlet-api.jar;classes;.
  2.    -d classes src\com\coderookie\FirstServlet.java

For Unix ones (here we have "/" and ":"):

  1. javac -cp TOMCAT/common/lib/servlet-api.jar:classes:.
  2.    -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!

3. Combining servlet and JSP

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:

  1. out.println("<HTML>");
  2. out.println("<HEAD>");
  3. out.println("<TITLE>" + "My first page" + "</TITLE>");
  4. out.println("</HEAD>");
  5. out.println("<BODY>");
  6. out.println("</BODY>");
  7. 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):

  1. <html>
  2.   <head>
  3.     <title>${title}</title>
  4.   </head>
  5.   <body>
  6.   Hi World !
  7.   </body>
  8. </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:

  1. package com.coderookie;
  3. import javax.servlet.http.HttpServlet;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import javax.servlet.RequestDispatcher;
  7. import javax.servlet.ServletContext;
  8. import javax.servlet.ServletException;
  10. import java.io.IOException;
  12. public class FirstServlet extends HttpServlet
  13. {
  14.   public void doGet(HttpServletRequest request,
  15.     HttpServletResponse response)
  16.     throws ServletException, IOException
  17.     {
  18.       request.setAttribute("title", "My first super page"); // #1
  20.       ServletContext app = getServletContext();
  21.       RequestDispatcher dispatcher =
  22.         app.getRequestDispatcher("/hi.jsp"); //#2
  23.       dispatcher.forward(request,response);
  24.     }
  25. }

#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.

  2. |
  3. |- hi.jsp
  4. |
  5.  -- WEB-INF
  6.     |
  7.     |
  8.      - classes
  9.     |
  10.      - src
  11.     |
  12.      - (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 ;).

234620006_892d12a8b4_m.jpgThis 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.


Add to del.icio.us delicious

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DZone
  • del.icio.us
  • Digg
  • Technorati

10 Responses to “A Really Easy Introduction to JSP and Servlets and . Part I”  

  1. 1 James

    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!

  2. 2 Christian


    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 :)

  3. 3 Kris


    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 :)

  4. 4 Jeremy

    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.

  5. 5 Christian

    Hi Guys,

    thanks for your help, especially Kris, who figured it out. It wasn’t in the JDK after all, just a little typo.

  6. 6 k. gangadhara rao


  7. 7 k. gangadhara rao

    Thank you, If u don’t understand here, u cannot understand form anywhere.

  8. 8 Avinash

    Awesome ….DUDE!!! Really a good tutorial for the beginners….

  9. 9 anon

    Worked great thanks.

  10. 10 anon #2

    Thanks! :)

Leave a Reply