JSP - Servlets: A simple JSP example

This section is going to show you some simple tasks you can perform using the Java Server Pages - JSP - technology.

You are assumed to be familiar with HTML; you can learn HTML from W3Schools at http://w3schools.com/html/default.asp

  1. Open eclipse and choose your workspace:
    • Open the folder where you unzipped eclipse
    • Double click "eclipse.exe"
    • Browse to your workspace and then click OK
    • If the Welcome page is opened, go to the workbench by clicking this icon

  2. Create a new Dynamic web project:
    • In the menu bar File / New / Dynamic Web Project
    • Name your project - To be consistent with the tutorial, name it "JSPExample". Your project should appear in the "Project Explorer" view located at the left side of the eclipse window. If the Project Explorer view is not shown, you can show it from Window / Show View / Project Explorer.

  3. Create a JSP file:
    • In the "Project Explorer" view, expand your project by clicking the project's corresponding '+' sign
    • R-click WebContent / New / JSP. If JSP is not shown in the list, go to other / Web / JSP.
    • Name your JSP (To be consistent with the tutorial, name it "myFirstJSP")

  4. Write HTML code to display "Hello World!" at the center of the page. To do that place the following code:

    <center> <font color="gray" size="7"> Hello World! </font> </center>

    in the body of your HTML body (i.e between the body tags <body> ... </body>). The result HTML document should look as follows:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <center> <font color="gray" size="7"> Hello World! </font> </center> </body> </html>

  5. Add your project to "Tomcat":
    • Open the server view by clicking the "Servers" tab at the bottom of your page. If the "Servers" tab is not shown, you can show it from the menu bar, Window / Show View/ Servers. Or Window / Show View / Other… / Server / Servers.
    • In the "Servers" view, R-click Tomcat-server record / Add and Remove Projects. (If Tomcat-server record is not there, please check Steps 5-6 in the Configurations section by clicking next from here)
    • Add your project

  6. Start "Tomcat": In the "Servers" view, R-click Tomcat-server record / Start

  7. Test your project:
    • In your web browser (Internet Explorer or Firefox) : Please note that Tomcat's default port is 8080, but the version refered to in the Downloads section (the pre-configured version), has its port set to 80. We will proceed in this tutorial assuming that the port is set to 80. (You can check your version's port from Tomcat-Installation-Directory / conf / server.xml)
    • Click your JSP file name shown in the directory listing - in our example it is myFirstJSP.jsp

    This should be the result:

  8. Set your project's welcome file (let the server open "myFirstJSP.jsp" once you open the project -- to pass the second part of step 7 --).
    • Open "web.xml": WebContent / Web-INF / R-click web.xml / Open With / Text Editor
    • Set the "welcome-file-list" to your home page (In our example it is myFirstJSP.jsp). Place:

      <welcome-file> myFirstJSP.jsp</welcome-file>

      in the "welcome-file-list" between:

      <welcome-file-list> and </welcome-file-list>

    • web.xml should look as follows:

      <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>JSPExample</display-name> <welcome-file-list> <welcome-file>myFirstJSP.jsp</welcome-file> </welcome-file-list> </web-app>

      Restart the server and test your project again using http://localhost/yourProjectName - in our example, the URL will be http://localhost/JSPExample/ .

      Please note that the server does not recognize changes in "web.xml" except if you restarted, or started, the server

If you have passed these steps successfully and saw the intended results, this means that you were able to use the JSP technology to display ordinary, static, HTML pages.

Click next for Dynamic WebPages.

Most probably if you have asked the question "What is the difference between HTML and JSP?" a part of the answer was that "HTML represents Static Web Pages, while JSP allows embedding java code in HTML to represent Dynamic Web Pages". So now let's see what does that mean, by adding some simple JSP tags and java code to our example.

  1. Open your JSP file - in our example it is myFirstJSP.jsp
  2. Add this code before the center end-tag (</center>)

    <br><br> <font color="gray" size="5"> The date now is: <%= new java.util.Date() %> </font>

  3. Refresh your web page - in our example, the URL of the web page was http://localhost/JSPExample

    The page should now look like that:

    Refresh and refresh your web page to see how dynamic it is (It is dynamic since the date is changing). This is the simplest dynamic web page. To check further examples, and learn more about JSP tags, go to the next page.

In order to be able to embed scripts of java code into HTML, JSP introduced new tags; three of them (the first, second and fourth) are called "Scripting elements"

  1. Expression tags <%= expression %>
  2. Scriptlet tags <% scriptlet %>
  3. Directive tags <%@ directive attribute="value" %>
  4. Declarative tags <%! declarations %>

In our example, we used the tag <%= expression %> which is basically used to get the string value of this expression and write it to the body of the response. (Initially we will assume that it gets the string value of this expression and display it).

For example; getting the String value of:

  • A simple String

    <%= "Hello World" %>

    This will display the string value of the expression ("Hello World") which is "Hello World".

  • An expression

    <%= 5+7 %>

    or

    <%= "Hello" + " " + "World" %>

    This will display the string value of (5+7) that is "12"; and the string value of ("Hello" + " " + "World") which is "Hello World".

  • The return of a method

    <%= new java.util.Date() %>

    Like in our example, this will display the String value returned from the method (new java.util.Date()) which is for example "Mon Feb 23 10:09:46 EET 2009"

The scriptlet tag <% scriptlet %> is the most commonly used tag, as it allows placing in an HTML code, a normal script of java code that you are used to write while implementing a desktop application.

In a scriptlet tag, you may declare variables, use loops, conditional operators and you can use the method out.println () to write a string value to the response body (or as assumed before; to display a string value on your result page). This out.println method functions almost exactly like the <%= expression %> tag.

For example, if we would like to have the same result of our example in "myFirstJSP.jsp" without using the expression tag, this can be done this way:

<%@page import="java.util.Date" %> <% Date x = new java.util.Date(); out.println (x); %>

This part <%@page import="java.util.Date" %> will be explained in the directives section.

Let's complicate our example a little bit more, to display:

  • "Good Morning", if it is between 3:00am and 12:00pm
  • "Good Afternoon", if it is between 12:00pm and 6:00pm
  • "Good Evening", if it is after 6:00 pm

We can get this result by using HTML to display the words, and expressing the conditions by adding the appropriate if statements using scriptlet tags this way (complete code found here):

<% Date x = new java.util.Date(); if (x.getHours() > 3 && x.getHours() < 12 ) { %> Good Morning <% } else if (x.getHours() > 12 && x.getHours ()< 18 ) { %> Good Afternoon <% } else if (x.getHours()> 18 || x.getHours() <3) { %> Good Evening <% } %>

<%@directive attribute = "value" %> is the syntax of the so called directives. As you can see they are some how different, as they have attributes and attributes' values (they are not pure java scripts).A directive can be:

  • page, which is used in importing external classes and providing information about the page (the language used for example). In our example, we needed to import "java.util.Date;". This could be done either by:

    Adding a new page directive tag to your code before using the data-type Date

    <%@page import="java.util.Date" %> The date now is: <% Date x = new java.util.Date(); out.println (x); %>

    or by

    Editing the page directive tag, already existing at the beginning of your code.

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="java.util.Date" %>

    For more information about the page directive tag; visit Exforsys at http://www.exforsys.com/tutorials/jsp/jsp-directive-tag.html and Roseindia at http://www.roseindia.net/jsp/jsptags.shtml

  • include, that is used to include the code written in another file. Note that it is not a must for this file's content to be a complete code representing a web page. This tag's function is like copying the content of a file (not necessarily a JSP), and pasting if in another file.

    Try using the include directive by following these steps:

    1. Create a new JSP file. In the "Project Explorer" view, R-click WebContent / New / JSP
    2. Name your JSP – to be consistent with the tutorial, name it "externalContent.jsp"
    3. Delete the default code written once you create the file.
    4. Write a statement that you would like to see displayed at your browser, for example "This content is from an external file". Hence the content of the entire file would looks as follows:

      This content is from an external file

    5. Go to your first JSP page - in our example it is myFirstJSP.jsp
    6. Include your new file in the body of the code using the following tag:

      <%@include file="externalContent.jsp" %>

    7. Refresh your browser to see the new content that results from the updated code.

  • taglib is used to allow users use tags they defined themselves using "custom tags". Learn more about taglib directive from Exforsys at http://www.exforsys.com/tutorials/jsp/jsp-directive-tag-and-scriptlet-tag.html and Sun at http://java.sun.com/products/jsp/tags/11/syntaxref11.fm8.html

Declarative tags <%! declarations %> are used to define variables and methods. Note that you can define a variable in a scriptlet tag, but you can not define a method except in a declarative tag. Try to visualize the difference by assuming that the code written in all scriptlet tags of the whole JSP is placed in a main method, while code written in declarative tags is placed outside the main method (in the form of variables and methods).

Now let's edit our example to use a method. Please follow the following steps:

  1. Go to your first JSP - in our example it is myFisrtJSP.jsp
  2. In a declarative tag, add a method that returns a statement you would like to be displayed in your browser.

    <%! public static String getMyStatment () { return ("This statement is a return of a method"); } %>

  3. Call your method using an expression tag for example.

    <%= getMyStatment() %>

  4. Refresh your browser to see your code working

In addition to these tags, there are XML tags that can be used in JSP and are called "Action tags" Read about action tags from RoseIndia at http://www.roseindia.net/jsp/jspactions.shtml and Exforsys at http://www.exforsys.com/tutorials/jsp/jsp-action-tags.html.

Read more about JSP from sun at http://java.sun.com/products/jsp/tags/11/tags11.html

RenewSession