© Luciano Manelli and Giulio Zambon 2020
L. Manelli, G. ZambonBeginning Jakarta EE Web Developmenthttps://doi.org/10.1007/978-1-4842-5866-8_1

1. Introducing JSP and Tomcat

Luciano Manelli1  and Giulio Zambon2
(1)
Taranto, Italy
(2)
Harrison, ACT, Australia
 

Web applications (together with apps) can be considered the cornerstone of the modern technology both in private and government organizations. In fact, by interacting with a remote server, it is possible to find the needed information or to purchase something online and, in general, to use many services for your job or your personal life.

Every time you type something into a web form, an application “out there” interprets your request and prepares a web page to respond. To understand web applications, you first need to have a clear idea of what happens when you ask your browser to view a web page, either by typing a URL (Uniform Resource Locator) into the address field of your browser or by clicking a hyperlink. Figure 1-1 shows you how it works.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig1_HTML.jpg
Figure 1-1

Viewing a plain HTML page

The following steps show what happens when you request your browser to view a static web page:
  1. 1.

    When you type an address such as www.website.com/path/whatever.html into the address field, your browser first resolves www.website.com (i.e., the name of the web server) into the corresponding Internet Protocol (IP) address, usually by asking the Domain Name Server provided by your Internet service provider (ISP). Then your browser sends an HTTP (HyperText Transfer Protocol) request to the newly found IP address to receive the content of the file identified by /path/whatever.html.

     
  2. 2.

    In reply, the web server sends an HTTP response containing a plain-text HTML (HyperText Markup Language) page. Images and other non-textual components, such as sound and video clips, only appear in the page as hyperlinks to those resources stored either on the same server or another server on the Internet.

     
  3. 3.

    Your browser receives the response, interprets the HTML code contained in the page, requests the non-textual components from the server, and displays the lot.

     
So, it is possible to list the main components:
  • JavaServer Pages (JSP): It is a technology that helps you create such dynamically generated pages by converting script files into executable Java modules.

  • JavaServer Faces (JSF): It is an API for creating component-based UIs for Java web applications.

  • Tomcat: It is a server application that can execute your code and act as a web server for your dynamic pages.

Moreover, any nontrivial web application is likely to need handling data. Therefore, you will use Oracle MySQL that is a powerful relational database (RDBMS) for the creation and the management of database for web applications.

Everything you need to develop JSP/JSF web applications is available for free download from the Internet; but to install all the necessary packages and tools and obtain an integrated development environment (IDE), you need to proceed with care. There is nothing more annoying than having to deal with incorrectly installed software. When something doesn’t work, the problem will always be difficult to find.

In this chapter, I’ll introduce you to Java servlets and JSP, and I’ll show you how they work together within Tomcat to generate dynamic web pages.

You’ll have to install more packages as you progress. In total, you will need at least 300MB of disk space for Java and Tomcat alone, at least 300MB of disk space for database, and twice as much space to install the Eclipse development environment useful for developing software.

To run all the examples contained in this book, you do not need large computational resources. I used a PC Intel i7 with 4 GB of memory and running Windows 7 (I also used a PC Intel i3 with 4 GB of memory and running Windows 10). I will focus on Windows operating system (OS), even if I will develop a cursory mention of package installation on macOS and Linux (Ubuntu distribution). At the time of this writing, the latest versions of all the packages you will need to install are
  • Java: 14

  • Tomcat web server: 9.0.34

  • Eclipse development environment: Java IDE 2020-03

  • MySQL database: MySQL Community Server 8.0.20

The installation of these components is explained in this chapter. In the next chapters, I also explained you how to download and configure other components: from the MySQL Java DataBase Connector (JDBC) to the Apache JavaServer Faces libraries.

Note that for security reasons, I wouldn’t recommend installing something unless absolutely necessary and with no alternative, so it is easier and safer to just download a compressed version and run the relevant scripts for the respective OS. Of course, after this book is published, there will most likely be newer releases of all the aforementioned packages. Nevertheless, you should be able to adapt my instructions to install the latest versions without any problem.

Installing Java

Nothing runs without Java: on one hand, it is the runtime environment (JRE), which lets you execute Java, and on the other, it is the Java Development Kit (JDK), which lets you compile Java sources into executable classes. There are two main distributions: the Oracle JDK and the OpenJDK. I chose the second one under the open source GPL, because the Oracle JDK License has changed for releases starting from April 2019, permitting only certain uses at no cost. For more information about Oracle JDK License Update, you can go to the URL www.oracle.com/java/technologies/javase-jdk14-downloads.html.

Now, let’s download the latest OpenJDK release. Here’s what you need to do for Windows OS:
  1. 1.

    Go to the URL https://jdk.java.net/14/ in Firefox browser as you can see in Figure 1-2.

     
  2. 2.

    Click the link of the zip file of Windows/x64 under Builds paragraph and the download of the archive file will start. We don’t need any installer file.

     
  3. 3.

    Extract the archive file in your PC. I chose C:.

     
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig2_HTML.jpg
Figure 1-2

OpenJDK home page Firefox browser

At this point, you should have the folder C:jdk-14, that I changed in C:OpenJDK-14, or the equivalent folders for the version you have downloaded. The Java home folder has the “bin” subfolder that will help you to develop and execute programs in Java language (with tools and utilities) and that supports the execution of programs written in the Java programming language (with an implementation of the Java Runtime Environment, class libraries, and other files). Note that since Java 11, Oracle and the OpenJDK team decided to distribute a single thing, the JDK, and to stop to duplicate some of the things the JDK in the JRE folder.

In order to be able to compile Java from the command line, you need to add the JDK path to the PATH environment variable. From the Windows Start menu, select SettingsControl PanelSystem. When the System Properties dialog opens, click the “Advanced system settings” link that you find on the left-hand side and then on the Advanced tab. Finally, to reach the dialog that lets you modify the PATH variable, click the “Environment Variables” button. You will see the double dialog window shown in Figure 1-3.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig3_HTML.jpg
Figure 1-3

The Environment Variables double dialog

You might see a PATH variable on the top dialog, but what you need to do is scroll the bottom dialog by clicking the sidebar of “System variable” section until you see a variable named Path. Double-click it (or highlight it and click the “Edit...” button) and insert the text “C:OpenJDK-14in;” in the field “Variable value” (you can also set the JAVA_HOME with the value of C:OpenJDK-14 and then set in the Path the value %JAVA_HOME%in).

The semicolon at the end of the text is essential because it separates the new path from the existing ones. Do not insert additional spaces before or after.

Click the “OK” button to save the changes. Then click this button another couple of times until the system dialog closes.

What About Linux and macOS?

Linux is a complete operating system composed of free and open source software intended for personal computers. Last versions make it easy to use for non-developers, and its interface is like the Windows desktop. macOS is the operating system for Macintosh personal computers. It is a property of Apple, and it is based on a solid and secure Unix-like foundation.

Now, let’s download the latest OpenJDK release for Linux OS. The simplest way is to go to the Terminal window in the Applications folder:
  1. 1.

    First, you need to update and upgrade the installed software of your OS.

     
  2. 2.

    Download and install the last version of the openjdk with the command sudo apt install openjdk-14-jdk. After inserting the password, the download will start. We don’t need any installer file.

     
  3. 3.

    Now, the JDK is installed in the folder /usr/lib/jvm/java-14-openjdk-amd64/. If you think that can be more than one JDK installed, you can test it with the command sudo update-alternatives --config java.

     
  4. 4.

    At last, you can add the installed JDK to the environment variables of the environment file in the /etc/ folder appending the path at the end of it (you can open and modify it using the sudo nano /etc/environment command and then add the following value: JAVA_HOME=/usr/lib/jvm/java-14-openjdk-amd64/bin/).

     
Now, let’s download the latest OpenJDK release for macOS. Here’s what you need to do:
  1. 1.

    Go to the URL https://jdk.java.net/14/. You can use Apple’s browser, that is, Safari, as shown in Figure 1-4.

     
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig4_HTML.jpg
Figure 1-4

OpenJDK home page Safari browser

  1. 2.

    Click the link of the tar.gz file of macOS/x64 under Builds paragraph and the download of the archive file will start. We don’t need any installer file.

     
  2. 3.

    Open the Terminal app in the Utilities folder, go to the Download location, and extract the downloaded file (you can use the command tar -xf openjdk-14.0.1_osx-x64_bin.tar.gz).

     
  3. 4.

    Now move the JDK to its default location (you can use the command sudo mv jdk-14.0.1.jdk /Library/Java/JavaVirtualMachines/).

     
  4. 5.

    At last, you can add the installed JDK to the environment variables of the bash file (setting the following value: JAVA_HOME=$(/usr/libexec/java_home)).

    Note Terminal (or command prompt for Windows) is a command-line interface that allows you to control your OS using a command prompt. The command sudo for a Unix-like operating systems allows to run programs or create directories by Terminal with the security privileges of a superuser (your account needs to be root or admin because administrator rights are required), and when executing it, you will be asked to enter your password.

     

Java Test

To test the Java installation, you can open a command-line window. The commands in the following paragraph are the same for Windows and for the other two OS. I decided to do it in Windows environment. Click the Start button and select ProgramsAccessoriesCommand Prompt, or digit the command "cmd" in the search field of the Windows OS. Now type javac command.

If you see a screen like Figure 1-5, Java is installed.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig5_HTML.jpg
Figure 1-5

Testing Java

If you want to test and confirm the installed Java version, go to command prompt and type java -version command. If you see a screen like Figure 1-6, the correct Java version is installed.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig6_HTML.jpg
Figure 1-6

Testing Java version

Moreover, to test the Java installation, you can also use the little application shown in Listing 1-1. In this example, you can use a smart editor as Notepad++ or a different text editor.

To create the source code for your first Java program, you have to
  • Declare a class with name “Hello”.

  • Declare the main method “public static void main(String args[])”.

  • Type the command “System.out.println(“Hello World”)” for displaying the text Hello World on the command prompt window.

class Hello {
   public static void main(String args[]){
     System.out.println("Hello World");
   }
}
Listing 1-1

Hello.java

Now, save the file as Hello.java in your working folder. Open again the command window and, after changing to your work directory, type “javac Hello.java” to compile the application. It should return the prompt without saying anything. It also means that you have correctly updated the Path system variable. If you want to know more about what the javac compiler is doing, type –verbose between javac and the name of the file. You will see a file named Hello.class in your work directory. Now, to run the application, type “java Hello” on Command Prompt as shown in Figure 1-7.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig7_HTML.jpg
Figure 1-7

Testing a Java class

Note that all the code described in this book is available for download from the Apress website. In this case, you can simply type the code; in others, you don’t need to retype it, even if I think that it is important that you improve your programming skills developing in the Eclipse environment. You can find the examples in folders with the same names as the corresponding chapters.

Installing Tomcat

This is the Java web server of Apache’s Tomcat service, which is the servlet container that allows you to run JSP and in which Java code can run (Tomcat 9 is the latest version). It is easier and safer to just download a zipped version and run the relevant scripts for the respective OS.

Tomcat listens to three communication ports of your PC (8005, 8009, and 8080). Before you install Tomcat, you should check whether some already installed applications are listening to one or more of those ports. To do so, use the command netstat that displays detailed information about your computer’s network communications.

In Windows OS, you can open a terminal window and type the command netstat /a. It will display a list of active connections in tabular form. The second column of the table will look like this:
Local Address
0.0.0.0:135
0.0.0.0:445
0.0.0.0:3306

The port numbers are the numbers after the colon. If you see one or more of the ports Tomcat uses, after installing Tomcat, you will have to change the ports it listens to.

Here’s how to install Tomcat 9 correctly:
  1. 1.

    Go to the URL https://tomcat.apache.org/download-90.cgi. Immediately below the second heading (“Quick Navigation”), you will see four links: KEYS, 9.0.34, Browse, and Archives.

     
  2. 2.

    By clicking 9.0.34, you will be taken toward the bottom of the same page to a heading with the same version number. Below the version heading, you will see the subheading “Core”. Below that, you will see the link for the zip download, arranged as follows: zip (pgp, sha512) apache-tomcat-9.0.34.zip. Click zip link to download the file apache-tomcat-9.0.34.zip (11.5MB).

     
  3. 3.

    Unzip the downloaded file in C:/. At this point, you should have the folder C:apache-tomcat-9.0.34. I prefer to maintain the default folder name in this case because I can use different server versions without confusion. In fact, a very business situation includes different environments (such as development, test, and delivery), so remember to maintain consistency between the server versions to prevent bugs or different behaviors.

     
  4. 4.
    Now, you can configure the server creating in the folder C:apache-tomcat-9.0.34in the file setenv.bat with the following code:
    set "JRE_HOME=C:OpenJDK-14"
    set "JAVA_HOME=C:OpenJDK-14"
    exit /b 0
     
Now the server is ready to start up. Go to C:apache-tomcat-9.0.34in and double-click startup.bat file or open a command window, go to bin folder, and type startup.bat as in Figure 1-8.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig8_HTML.jpg
Figure 1-8

Starting up Tomcat server

A second window is generated: if there are no problems, it will end with the code line that indicates the startup time, as shown in Figure 1-9. In this window, it will be also written the log of our applications.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig9_HTML.jpg
Figure 1-9

Starting up Tomcat window

To see that Tomcat is working properly, open a browser and type localhost:8080. You should see the page shown in Figure 1-10 (Firefox in the example).
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig10_HTML.jpg
Figure 1-10

The localhost home page

A URL like http://localhost:8080/ that you saw in the previous figure specifies that on the host side, the port number for HTTP is 8080 instead of 80, which is the standard port for HTTP. This is because Tomcat expects and routes HTTP traffic through port 8080. This is appropriate if you intend to use Tomcat to handle requests for JSP pages and place it behind a server (typically, the Apache web server) that handles static HTTP/HTTPS. But if you intend to use Tomcat to handle HTTP/HTTPS as well, you should change its default ports 8080 and 8443 to 80 and 443, respectively.

What About Linux and macOS?

Here’s how to install Tomcat 9 correctly in Linux:
  1. 1.

    Go to the URL https://tomcat.apache.org/download-90.cgi. Immediately below the second heading (“Quick Navigation”), you will see four links: KEYS, 9.0.34, Browse, and Archives.

     
  2. 2.

    By clicking 9.0.34, you will be taken toward the bottom of the same page to a heading with the same version number. Below the version heading, you will see the subheading “Core”. Below that, you will see the link for the tar.​gz download, arranged as follows: tar.gz (pgp, sha512). Click tar.​gz link to download the file apache-tomcat-9.0.34 (10.7MB).

     
  3. 3.

    Unzip the downloaded file in /opt/ (you can use the command sudo tar xf /Downloads/apache-tomcat-9.0.35.tar.gz -C /opt/). At this point, you should have the folder /opt/apache-tomcat-9.0.34.

     
  4. 4.

    You can change and organize the owner permissions of the tomcat folder for security purposes.

     
  5. 5.

    Now the server is ready to start up. Go to optapache-tomcat-9.0.34in in the terminal window and type .startup.sh (to stop the server, type ./shutdown.sh).

     
  6. 6.

    To see the console of Tomcat, go to optapache-tomcat-9.0.34 and type in the Terminal the command tail -f logs/catalina.out.

     
  7. 7.

    At last, you can open a browser and type localhost:8080.

     
Here’s how to install Tomcat 9 correctly in macOS:
  1. 1.

    Go to the URL https://tomcat.apache.org/download-90.cgi. Immediately below the second heading (“Quick Navigation”), you will see four links: KEYS, 9.0.34, Browse, and Archives.

     
  2. 2.

    By clicking 9.0.34, you will be taken toward the bottom of the same page to a heading with the same version number. Below the version heading, you will see the subheading “Core”. Below that, you will see the link for the tar.​gz download, arranged as follows: tar.gz (pgp, sha512). Click tar.​gz link to download the file apache-tomcat-9.0.34 (10.7MB).

     
  3. 3.

    Unzip the downloaded file in /usr/local (you can use in the Downloads folder the command sudo tar xf apache-tomcat-9.0.35.tar.gz -C /usr/local/). At this point, you should have the folder /usr/local/apache-tomcat-9.0.34.

     
  4. 4.

    You can change and organize the owner permissions of the tomcat folder for security purposes.

     
  5. 5.

    Now the server is ready to start up. Go to /usr/local/apache-tomcat-9.0.34/bin in the terminal window and type ./startup.sh (to stop the server, type ./shutdown.sh). The JRE_HOME is set in a correct way because it points to the folder usr defined in the previous paragraph or to the defined JAVA_HOME folder.

     
  6. 6.

    To see the console of Tomcat, go to /usr/local/apache-tomcat-9.0.34 and type in the Terminal the command tail -f logs/catalina.out.

     
  7. 7.

    At last, you can open a browser and type localhost:8080.

     

With Java and Tomcat in place, we can finally begin playing with JSP!

Introduction to HTML

You can find on the Internet several websites that describe HTML, Cascading Style Sheets (CSS), and JavaScript in detail. Therefore, instead of attempting to cover everything there is to know about them, I will introduce a few key concepts for anyone who is beginning the study of web development for the first time.

HyperText Markup Language (HTML) is the standard “tag” markup language used for creating html pages (with extension .htm or .html). Therefore, it is the base for JSP pages. HTML documents are organized as a hierarchy of elements that normally consist of content enclosed between a pair of start and end tags.

The schema is
<TAG attributes>contents</TAG>
You can nest HTML elements inside each other, and in fact, without nesting, no HTML page would be possible. The tag can be organized in the following way (with indentation):
<TAG1 attributes >
       <TAG2 attributes >
            content 2
       </TAG2>
</TAG1>

For example, the tags <html> and </html> delimit the whole HTML document. However, some elements are empty, in which case you can usually replace the end tag with a slash immediately before the closing bracket of the start tag, as in <img src=“mypict.gif”/>.

You can insert comments in the following way:
<!-- comments -->
Each tag can have some attributes with some values:
<tag1 attribute1= "value1" attribute2= "value2">
The html document presents two sections:
<head>...</head>
<body>...</body>
It is possible defining
  • Bold characters: <b>

  • Underline characters: <u>

  • Italic characters: <i>

  • Newline: <br>

  • Paragraph: <p>

  • Heading: from <h1> to <h6>

The title tag defines a title for the HTML document.

The style tag defines style information for the HTML document: it can be inline for a section of the page or general (in this case, it is defined in the head tag of the html page).

Listing 1-2 shows the simplest possible HTML page. Copy the code in a text document and then save the file as basic.html. Double-click the file and the html page will be open in the predefined browser.
<html>
        <head><title>Page title</title></head>
                <style type="text/css">
                    body {background-color:gray; font-size=10pt;}
                </style>
        <body>
                <b>Bold characters</b>
                <u>Underline characters</u>
                <i>Italic characters</i>
                A newline<br>
                <p>A paragraph</p>
                <h1>A heading</h1>
        </body>
</html>
Listing 1-2

basic.html

Figure 1-11 shows the outcome of Listing 1-2.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig11_HTML.jpg
Figure 1-11

A basic HTML page

Essentially, an HTML document consists of text, images, audio and video clips, active components such as scripts and executables, and hyperlinks. A browser then interprets and renders the components in sequence, mostly without inserting any empty space or newline between them.

At last, it is possible defining tables:
  • <table>…</table>: It opens/closes a table.

  • <tr>…</tr> (“table row”): It creates a row.

  • <td>…</td> (“table data”): It creates a cell.

A table consists of rows and columns, with cells containing text, images, and other components. In almost every chapter of this book, you’ll find examples of tables. Tables are an easy way to present components in an organized fashion.

<table border="1">
   <tr>
       <td> content 1</td>
       <td> content 2</td>
    </tr>
    <tr>
        <td> content 3</td>
        <td> content 4</td>
    </tr>
  </table>
Listing 1-3

table.html

Listing 1-3 shows the code that generates the simple table of Figure 1-12.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig12_HTML.jpg
Figure 1-12

An HTML-generated table

To turn your web pages into an interactive experience, you have to give users the ability to make choices and type or upload information (i.e., when you create a new email, you type data in an online form!). To achieve this, you use the form element, which accepts data from the user and sends it to the server.

This book is full of examples of input forms. But a summary of all possible input elements as shown in Figure 1-13 might be useful as a reference. The browser was Firefox.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig13_HTML.jpg
Figure 1-13

An HTML form with examples of all input elements

The various types of the input element let the user enter a string of text or a password, check one or more check boxes, choose one of several radio buttons, submit a form, or reset a form’s fields. The textarea element lets the user enter several lines of text, while the fieldset element lets you group several input fields under one or more headings. To present multiple choices, you use the select element, which contains one option element for each alternative. Listing 1-4 shows the source code of Figure 1-13.
<html>
<head>
  <title>Example of input form</title>
  <style type="text/css">
    td.h {font-size: 120%; font-weight: bold}
    </style>
  </head>
<body>
<form name="nameForm" action="" method="GET">
  <input type="hidden" name="agent" value="007"/>
  <table  cellpadding="5" border="1" rules="all">
    <tr>
      <td class="h">Element</td><td class="h">Attribute</td>
      <td class="h">Result</td></tr>
    <tr>
      <td>input</td><td>type="text"</td>
      <td><input type="text" name="t"/></td>
      </tr>
    <tr>
      <td>input</td><td>type="password"</td>
      <td><input type="password" name="p"/></td>
      </tr>
    <tr>
      <td>input</td><td>type="checkbox"</td>
      <td>
        <input type="checkbox" value="a" name="abc">A</input>
        <input type="checkbox" value="b" name="abc">B</input>
        <input type="checkbox" value="c" name="abc">C</input>
        </td>
      </tr>
    <tr>
      <td>input</td><td>type="radio"</td>
      <td>
        <input type="radio" name="yn" value="y">yes</input>
        <input type="radio" name="yn" value="n">no</input>
        </td>
      </tr>
    <tr>
      <td>input</td><td>type="submit"</td>
      <td><input type="submit"/></td>
      </tr>
    <tr>
      <td>input</td><td>type="reset"</td>
      <td><input type="reset"/></td>
      </tr>
    <tr>
      <td>input</td><td>type="button"</td>
      <td><input type="button" value="click me" name="b"/></td>
      </tr>
    <tr>
      <td>textarea</td><td></td>
      <td><textarea name="ta">Default text</textarea></td>
      </tr>
    <tr>
      <td>fieldset</td><td></td>
      <td><fieldset>
        <legend>Dimensions:</legend>
        Width <input type="text" size="3" name="w"/>
        Height <input type="text" size="3" name="h"/>
        </fieldset></td>
      </tr>
    <tr>
      <td>select / option</td><td></td>
      <td><select name="food">
        <option value="pizza" selected >Pizza</option>
        <option value="spaghetti">Spaghetti</option>
        </select></td>
      </tr>
    </table>
  </form>
</body>
</html>
Listing 1-4

form.html

I’ve highlighted two lines. The first line, which contains the form element , shows that the action attribute is set to the empty string. The action attribute defines the URL of the page that must handle the request form. An empty string means that the same page displaying the form will also handle it. The second highlighted line shows how you can use the input element to set parameters without the user being aware of it (unless he or she peeks at the source, that is).

If you fill in the form as shown in Figure 1-13 and click the Submit button (or hit the Enter key), you’ll see in the address field of your browser that the following string appears at the end of the URL (I’ve inserted newlines for readability):
?agent=007
&t=bla+bla+bla
&p=abc
&abc=a
&abc=c
&yn=n
&ta=ciao!
&w=1
&h=2
&food=pizza

The browser has translated each input element into a string parameter-name=parameter-value. Notice that each space in the text fields has been replaced by a plus sign, including the spaces within the password. Also notice that the parameter abc appears twice, because I checked two of the three available check boxes. To avoid seeing all the parameters in the browser, use in the form element the attribute method="POST". Moreover, the POST method is more secure because data are stored in the request body of the HTTP and it has no restrictions on data length.

For more information, you can simply go to www.w3schools.com/ that is one of the more important and complete sites for web development site.

What Is JSP?

JSP is a technology that lets you add dynamic content to web pages. In absence of JSP, to update the appearance or the content of plain static HTML pages, you always have to do it by hand. Even if all you want to do is change a date or a picture, you must edit the HTML file and type in your modifications. Nobody is going to do it for you, whereas with JSP, you can make the content dependent on many factors, including the time of the day, the information provided by the user, the user’s history of interaction with your website, and even the user’s browser type. This capability is essential to provide online services in which you can tailor each response to the viewer who made the request, depending on the viewer’s preferences and requirements. A crucial aspect of providing meaningful online services is for the system to be able to remember data associated with the service and its users. That’s why databases play an essential role in dynamic web pages. But let’s take it one step at a time.

Viewing a JSP Page

With JSP, the web page doesn’t actually exist on the server. As you can see in Figure 1-14, the server creates it fresh when responding to each request.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig14_HTML.jpg
Figure 1-14

Viewing a JSP page

The following steps explain how the web server creates the web page:
  1. 1.

    As with a normal page, your browser sends an HTTP request to the web server. This doesn’t change with JSP, although the URL probably ends in .jsp instead of .html or .htm.

     
  2. 2.

    The web server is not a normal server, but rather a Java server, with the extensions necessary to identify and handle Java servlets. The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine.

     
  3. 3.

    The JSP engine loads the JSP page from disk and converts it into a Java servlet. From this point on, this servlet is indistinguishable from any other servlet developed directly in Java rather than JSP, although the automatically generated Java code of a JSP servlet is not always easy to read, and you should never modify it by hand.

     
  4. 4.

    The JSP engine compiles the servlet into an executable class and forwards the original request to another part of the web server called the servlet engine . Note that the JSP engine only converts the JSP page to Java and recompiles the servlet if it finds that the JSP page has changed since the last request. This makes the process more efficient than with other scripting languages (such as PHP) and therefore faster.

     
  5. 5.

    The servlet engine loads the servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response.

     
  6. 6.

    The web server forwards the HTTP response to your browser.

     
  7. 7.

    Your web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page. In fact, static and dynamic web pages are in the same format.

     

You might ask, “Why do you say that with JSP, the page is created fresh for each request, if the server only converts and compiles the JSP source if you have updated it since the previous request?”

What reaches your browser is the output generated by the servlet (i.e., by the converted and compiled JSP page), not the JSP page itself. The same servlet produces different outputs depending on the parameters of the HTTP request and other factors. For example, suppose you’re browsing the products offered by an online shop. When you click the image of a product, your browser generates an HTTP request with the product code as a parameter. As a result, the servlet generates an HTML page with the description of that product. The server doesn’t need to recompile the servlet for each product code.

The servlet queries a database containing the details of all the products, obtains the description of the product you’re interested in, and formats an HTML page with that data. This is what dynamic HTML is all about!

Plain HTML is not capable of interrogating a database, but Java is, and JSP gives you the means of including snippets of Java inside an HTML page.

Hello World!

A small example of JSP will give you a more practical idea of how JSP works. Let’s start once more from HTML. Listing 1-5 shows you a plain HTML page to display “Hello World!” in your browser’s window.
<html>
        <head>
                <title>Hello World static HTML</title>
        </head>
        <body>
                Hello World!
        </body>
</html>
Listing 1-5

hello.html

Create the folder %CATALINA_HOME%webappsROOT ests and store in it hello.html. Then type the following URL in your browser to see the web page:
http://localhost:8080/tests/hello.html
Normally, to ask your browser to check that the syntax of the page conforms to the XHTML standard of the World Wide Web Consortium (W3C), you would have to start the page with the following lines:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
You’d also have to replace
<html>
with
<html xmlns:="http://www.w3.org/1999/xhtml">
However, for this simple example, I prefer to keep the code to what’s essential. Figure 1-15 shows you how this page will appear in your browser.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig15_HTML.jpg
Figure 1-15

“Hello World!” in plain HTML

If you direct your browser to show the page source, not surprisingly, you’ll see exactly what’s shown in Listing 1-5. To obtain the same result with a JSP page, you only need to insert a JSP directive before the first line, as shown in Listing 1-6, and change the file extension from .html to .jsp.
<%@page language="java" contentType="text/html"%>
<html>
        <head>
                <title>Hello World dynamic HTML</title>
        </head>
        <body>
                Hello World!
        </body>
</html>
Listing 1-6

“Hello World!” in a Boring JSP Page

As with hello.html, you can view, as shown in Figure 1-16, hello.jsp by placing it in Tomcat’s ROOT ests folder and then type the following URL in your browser to see the web page:
http://localhost:8080/tests/hello.jsp
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig16_HTML.jpg
Figure 1-16

“Hello World!” in JSP

Obviously, there isn’t much point in using JSP for such a simple page. It only pays to use JSP if you include dynamic content. Check out Listing 1-7 for something more juicy.
<%@page language="java" contentType="text/html"%>
<html>
        <head>
                <title>Hello World dynamic HTML</title>
        </head>
        <body>
                Hello World!
                <%
                String userAgent = request.getHeader("user-agent");
                out.println("<br/>user-agent " + userAgent);
                %>
        </body>
</html>
Listing 1-7

hello.jsp

The code within the <% ... %> pair is a scriptlet written in Java. When Tomcat’s JSP engine interprets this module, it creates a Java servlet like that shown in Listing 1-8 (with some indentation and empty lines removed).
out.write(" ");
out.write("<html> ");
out.write("<head><title>Hello World dynamic
 HTML </title></head> ");
out.write("<body> ");
String userAgent = request.getHeader("user-agent");
out.println("<br/>User-agent: " + userAgent);
out.write(" ");
out.write("Hello World! ");
out.write("</body> ");
out.write("</html> ");
Listing 1-8

Java Code from the “Hello World!” JSP Page

As I said before, this servlet executes every time a browser sends a request to the server. However, before the code shown in Listing 1-8 executes, the server binds the variable out to a character stream associated with the content of the HTML response. As a result, everything written to out ends up in the HTML page that you’ll see in your browser. As you can see, Tomcat copies the scriptlet in your JSP file into the servlet and sends everything outside the scriptlet directly to the output. This should clarify how HTML and Java work together in a JSP page.

As the variable out is defined in each servlet, you can use it within any JSP module to insert something into the response (more on variables in Chapter 2).

Another such “global” JSP variable is request (of type HttpServletRequest). The request contains the IP address from which the request was originated, that is, of the remote computer with the browser (remember that this code runs on the server). The request also contains information about the browser. When some browsers send a request, they provide somewhat misleading information, and the format is complex.

The line that prints the userAgent informations , in the code in Listing 1-7, tells you the used browser and whether the browser is running on a Windows system or a Mac.

Figure 1-17 shows the generated page as it appears in a browser.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig17_HTML.jpg
Figure 1-17

hello.jsp with Firefox

Installing MySQL

In this section, I will explain how to install MySQL. I prefer manual installation because it offers some benefits and more control: you can back up or move databases in seconds and you can install and reinstall MySQL anywhere (also on USB drive). It will be also useful the installation of the MySQL Workbench, which is a user-friendly tool for the management of the database.

To install MySQL, do the following steps:
  1. 1.

    Go to https://dev.mysql.com/downloads/mysql/, the MySQL Community Server page, as shown in Figure 1-18 and agree the privacy policy.

     
  2. 2.

    Ensure that the selected platform is “Microsoft Windows” and click the download of the without installer version “Windows (x86, 64-bit), ZIP Archive” under “Other Downloads” section.

     
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig18_HTML.jpg
Figure 1-18

MySQL download page

  1. 3.

    Before you can download the package, you will have to log in as a user or register to be one, or, if you want, you can skip this step.

     
  2. 4.

    Finally, you can download the without installer version (mysql-8.0.20-winx64.zip): it has a dimension of 187.5M. This package contains MySQL database server.

     
  3. 5.

    Extract the zip file into C folder: drive and rename the folder from “mysql-8.0.20-winx64” to “mysql”.

     
  4. 6.

    Now, create the “data” folder. I chose in the same folder mysql, even if I recommend always placing the data folder on another drive. This prevents loss of data and makes easy reinstallation.

     
  5. 7.

    Now, you must initialize the data directory manually before MySQL can be started. Open a command window and type under the bin folder

     
C:mysqlin>mysqld --console --initialize

The --console option enables writing the diagnostic output to console (if you omit this option, the server writes output to the error log in the data folder).

You will get the following result on the console shown in Listing 1-9.
2020-05-11T22:35:02.223801Z 0 [System] [MY-013169] [Server] C:mysqlinmysqld.exe (mysqld 8.0.20) initializing of server in progress as process 7472
2020-05-11T22:35:02.243301Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2020-05-11T22:35:17.626425Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2020-05-11T22:35:47.786871Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: >7<s#XV!lsKz
Listing 1-9

Log of Database Initialization

The string I have highlighted in bold is the generated password for root user (which is the default administrative account in the MySQL grant system) displayed in the stream during the initialization. Now, you are ready to work with your database. Open two console windows: in the first, start the database with the command
C:mysqlin>mysqld.exe –console
Listing 1-10 shows the starting up of the server. The command --console lets you see the startup logs being printed.
C:mysqlin>mysqld.exe --console
2020-05-12T09:00:22.716177Z 0 [System] [MY-010116] [Server] C:mysqlinmysqld.exe (mysqld 8.0.20) starting as process 4188
2020-05-12T09:00:22.767345Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2020-05-12T09:00:25.311052Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2020-05-12T09:00:27.089744Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060
2020-05-12T09:00:27.880666Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2020-05-12T09:00:28.129496Z 0 [System] [MY-010931] [Server] C:mysqlinmysqld.exe: ready for connections. Version: '8.0.20'  socket: ''  port: 3306  MySQL Community Server - GPL.
Listing 1-10

Log of Database Starting Up

In the second, connect to the database with user and password and start the mysql console with the command
C:mysqlin>mysql -u root -p
After typing the password when prompted (Enter password: ************), you will see the welcome message on the console, as shown in Listing 1-11.
C:mysqlin>mysql -u root -p
Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 8
Server version: 8.0.20
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
mysql>
Listing 1-11

Log of Database Connection

Now the command-line interface (CLI) is activated; you can note the change of the prompt command I have highlighted.

At last, I recommend changing the password with the command
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';

The string I have highlighted in bold is the new password I used.

Then, run the command
mysql> FLUSH PRIVILEGES;

It tells the server to reload the grant tables: this operation puts your new changes into effect.

Finally, if you want to stop the database, enter exit in the prompt to stop the command-line client and then type
C:mysqlin>mysqladmin.exe -u root -p shutdown
Enter password: ****

The command mysqladmin invokes the administrative utility to connect to MySQL server as root user and tell it to shut down.

The console writes the following message as shown in Listing 1-12.
2020-05-12T16:03:03.527360Z 20 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.20).
2020-05-12T16:03:03.531865Z 0 [System] [MY-013105] [Server] C:mysqlinmysqld.exe: Normal shutdown.
2020-05-12T16:03:05.704839Z 0 [System] [MY-010910] [Server] C:mysqlinmysqld.exe: Shutdown complete (mysqld 8.0.20)  MySQL Community Server - GPL.
Listing 1-12

Log of Server Shut Down

Now you can install Workbench. Do the following steps for Windows:
  1. 1.

    Go to https://dev.mysql.com/downloads/workbench/, the MySQL Community Server page, as shown in Figure 1-19.

     
  2. 2.

    Ensure that the selected platform is “Microsoft Windows” and click the download installer version “Windows (x86, 64-bit), MSI Installer” under “Other Downloads” section.

     
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig19_HTML.jpg
Figure 1-19

MySQL Workbench download page

  1. 3.

    Before you can download the package, you will have to log in as a user or register to be one, or, if you want, you can skip this step.

     
  2. 4.

    Finally, you can download the installer version (mysql-workbench-community-8.0.20-winx64.msi): it has a dimension of 35.6M.

     
  3. 5.

    Be aware that Workbench requires “Microsoft .NET Framework 4.5.2” and the “Visual C++ 2015-2019 Redistributable Package”. However, if some packages are not installed, the installer will guide you to download and install the latest binary compatible version with your operating system.

     
  4. 6.

    When you execute the mysql-workbench-community-8.0.20-winx64.msi installer, the wizard starts as shown in Figure 1-20.

     
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig20_HTML.jpg
Figure 1-20

MySQL Workbench setup wizard

After finishing the installation, we can start the Workbench, as shown in Figure 1-21.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig21_HTML.jpg
Figure 1-21

MySQL Workbench home

From the Workbench menu, select Database ➤ Connect to Database…. Select the stored connection shown in Figure 1-22 and click OK!
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig22_HTML.jpg
Figure 1-22

MySQL Workbench—Connect to Database

Figure 1-23 shows the authentication panel. Now, set to “root” the password and confirm!
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig23_HTML.jpg
Figure 1-23

MySQL Workbench—database authentication

Now, it is also possible to work with Workbench.

What About Linux and macOS?

Here’s how to install MySQL correctly in Linux. The simplest way is to go to the Terminal window in the Applications folder:
  1. 1.

    Download and install the last version of the MySQL with the command sudo apt install mysql-server. After inserting the password, the download will start. We don’t need any installer file.

     
  2. 2.

    Change and organize the owner permissions of the mysql folder for security purposes.

     
Now, the steps are the same that for Windows OS. You must initialize the data directory manually, before MySQL can be started, typing in the Terminal under the bin folder the command mysqld –console --initialize. Then start the MySQL console (use the command sudo mysql) and change password. You can start and stop the server by typing the following commands:
sudo /etc/init.d/mysql start
sudo /etc/init.d/mysql stop

You can also download the Workbench file mysql-workbench-community_8.0.20-1ubuntu20.04_amd64.deb (that is similar to an installer package for Linux systems) from MySQL site. Then you can run the file (you can use the command sudo dpkg -i mysql-workbench-community_8.0.20-1ubuntu20.04_amd64.deb). Now you can work with Workbench. It is installed on your system in the Applications folder.

Here’s how to install MySQL correctly in macOS. To install MySQL, do the following steps:
  1. 1.

    Go to https://dev.mysql.com/downloads/mysql/, the MySQL Community Server page in Safari browser.

     
  2. 2.

    Ensure that the selected platform is “macOS” and click the download of the without installer version “macOS 10.15 (x86, 64-bit), Compressed TAR Archive” under “Other Downloads” section.

     
  3. 3.

    Open a Terminal window and unpack it at the typically installation location (/usr/local/mysql).

     
  4. 4.

    Change and organize the owner permissions of the mysql folder for security purposes.

     
Now, the steps are the same that for Windows OS. You must initialize the data directory manually, before MySQL can be started, typing in the Terminal under the bin folder the command mysqld –console --initialize. You can start and stop the server by typing the following commands:
sudo /usr/local/mysql/support-files/mysql.server start
sudo /usr/local/mysql/support-files/mysql.server stop

You can also download the Workbench file mysql-workbench-community-8.0.20-macos-x86_64.dmg from MySQL Workbench site, after selecting the macOS operating system. Double-click the downloaded file and, in the installation window, drag the icon of MySQL Workbench onto the icon of Applications as suggested. Now you can launch the application: the first time you would get the warning “Workbench is an application downloaded from the internet. Are you sure you want to open it?”, just click “open”. Now you can work with Workbench.

Installing Eclipse

Although it’s possible to build web applications by compiling Java modules from the command line, it’s more efficient to use an integrated development environment (IDE). This way, you can concentrate on the more creative part of developing software, rather than fix inconsistency and fiddle with folder hierarchies.

An IDE integrates all the applications that you need to develop software—from a source editor and a compiler to tools to automate the application building process and a debugger—into a single application. When developing in Java or in another object-oriented language, an IDE also includes tools to visualize class and object structure as well as inheritance and containment. Another advantage of using an IDE is that it propagates changes you make to individual modules. For example, if you rename a class, the IDE can automatically update its occurrences throughout your project files.

As the applications you develop become more complex, it makes more and more sense to use an IDE. That’s why, before continuing to our next project, I will tell you how to install and configure Eclipse.

Eclipse is an extremely powerful and extensible IDE, well suited for web application development. The Eclipse Foundation makes a new release four times a year (in March, June, September, and December), due to continuous integration and delivery in the software industry (the so-called rolling release). To develop the examples contained in this book, I used Eclipse IDE 2020-03, March 2020.

Once you’ve installed Eclipse to develop web applications, you can use it for any other software development task, for example, developing and debugging applications written in Java, C++, and even Fortran, which is still widely used in the scientific community.

Furthermore, whatever task related to software development you need to perform, it’s likely that somebody has already developed an Eclipse plug-in for it. The website http://marketplace.eclipse.org/ lists about 2000 plug-ins organized in dozens of categories. In fact, Eclipse itself consists of a core platform that executes plug-ins, plus a series of plug-ins that implement most of its functionality. Therefore, the standard packages available for download from the Eclipse website already include dozens of plug-ins.

In this section, I’ll only explain how to install the standard Eclipse configuration for Java EE development, which is what you need as you go through the rest of this book.

First of all, you need to download the package. To do so, go to www.eclipse.org/downloads/packages/ and click the Windows 64-bit link of Eclipse IDE for Java EE Developers, as shown in Figure 1-24.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig24_HTML.jpg
Figure 1-24

Downloading Eclipse

The website will suggest a mirror site for the download. The installation of Eclipse is very easy: expand the downloaded eclipse-jee-2020-03-R-win32-x86_64.zip and download the Eclipse IDE for Enterprise Java Developers.

File and move the eclipse folder to a convenient place. For no particular reason, I chose to move it to C:. Old habits are difficult to change. You might like to move the Eclipse folder to C:Program Files.

To execute Eclipse, double-click eclipse.exe, which you find immediately inside the eclipse folder.

When it starts, Eclipse asks you to select a workspace. The workspace is the folder where Eclipse stores your development projects. Therefore, it makes sense to place it on a drive or in a directory that you back up regularly. Before clicking the OK button, check the box marked “Use this as the default and do not ask again”. It will make your life easier. I chose C:Usersmanelli, which is my user’s home directory. The first time it executes, Eclipse displays a Welcome screen. To enter the screen where you do development, click the Workbench icon, as shown in Figure 1-25.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig25_HTML.jpg
Figure 1-25

Eclipse—the Welcome screen

Once you see the Workbench screen, select the Servers tab and click the new server wizard link, as shown in Figure 1-26.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig26_HTML.jpg
Figure 1-26

Eclipse—the Workbench screen

The screen that comes up is where you tell Eclipse to use Tomcat 9, as shown in Figure 1-27.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig27_HTML.jpg
Figure 1-27

Eclipse—choosing Tomcat 9 as localhost

Next (and last), you need to tell Eclipse where to find Tomcat 9 and what version of JDK to use, as shown in Figure 1-28.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig28_HTML.jpg
Figure 1-28

Eclipse—completing the Tomcat configuration

Now, if you have done everything correctly, Tomcat 9 should appear under the Servers tab of the Workbench. I have explained this configuration procedure because Eclipse is a very complex application, and it is easy to get lost among the many options.

For the same reason, to be on the safe side, I will also explain how to create a new web project. Later, you will learn how to import into Eclipse the example projects included in the software package of this book.

At last, you can verify that Eclipse uses the correct JDK. Go to Help ➤ About Eclipse IDE and click “Installation Detail” button. You can see the path and the name of the installed and used JDK, as shown in Figure 1-29.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig29_HTML.jpg
Figure 1-29

Eclipse Configuration

What About Linux and macOS?

Here’s how to install Eclipse correctly in Linux:
  1. 1.

    Type the URL www.eclipse.org/downloads/packages/ and go to the section Eclipse IDE for Enterprise Java Developers.

     
  2. 2.

    By clicking the Linux 64-bit link of Eclipse IDE, you will be forwarded to the download page that suggests a mirror site for the download. Clicking that link, the download of the file eclipse-jee-2020-03-R-incubation-linux-gtk-x86_64.tar.gz starts (399M).

     
  3. 3.

    Unzip the downloaded file in /home/. At this point, you should have the folder /home/eclipse. Now you can launch Eclipse and work with it.

     
Here’s how to install Eclipse correctly in macOS:
  1. 1.

    Type the URL www.eclipse.org/downloads/packages/ and go to the section Eclipse IDE for Enterprise Java Developers.

     
  2. 2.

    By clicking the Mac Cocoa 64-bit link of Eclipse IDE, you will be forwarded to the download page that suggests a mirror site for the download. Clicking that link, the download of the file eclipse-jee-2020-03-R-incubation-macosx-cocoa-x86_64.dmg starts (401M).

     
  3. 3.

    Double-click the downloaded file and, in the installation window, drag the icon of Eclipse Workbench onto the icon of Applications as suggested. Now you can launch the application: the first time you would get the warning “Eclipse is an application downloaded from the internet. Are you sure you want to open it?”, just click “open”. Now you can work with Eclipse.

     

Eclipse Test: JSP in a New Web Project

In the menu bar of the Workbench, select FileNewDynamic Web Project, type a project name (e.g., test), and click the Next button. In the new screen, named Java, click again the Next button. In the new screen, named Web Module, tick the box Generate web.xml deployment descriptor (i.e., the web.xml file) before clicking the Finish button.

The new project will appear in the Project Explorer pane (i.e., on the left-hand side) of the Workbench as shown in Figure 1-30.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig30_HTML.jpg
Figure 1-30

Eclipse—the test project

Now, expand it as shown in Figure 1-31, right-click the WebContent folder and select “New ➤ JSP File”.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig31_HTML.jpg
Figure 1-31

Eclipse—the test project

In the new JSP screen that appears, replace the default name NewFile.jsp with index.jsp and click the Finish button.

Eclipse shows the newly created file in the Project Explorer pane and opens it in the central pane of the Workbench for you to edit. Listing 1-13 shows its content. For me, the newly created file is located in the folder C:Usersmanelliworkspace estWebContent. If, for any reason, you edit the file with some other editor, to see the latest version within Eclipse, you need to right-click it in Eclipse’s Project Explorer and select Refresh. But I suggest that you stick to Eclipse with all editing, because it is very easy to make a mistake otherwise.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
Listing 1-13

index.jsp of the Test Project

Replace “Insert title here” with “My first project” (or whatever you like, of course), and write “Hello from Eclipse!” between <body> and </body>. Then save the file.

Caution

You must stop the Tomcat service in Windows before using Tomcat from within Eclipse and vice versa.

Position the cursor on the test project folder shown in the Project Explorer, right-click, and select Run AsRun on Server as shown in Figure 1-32.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig32_HTML.jpg
Figure 1-32

Eclipse—the run on Tomcat of the first project

When a screen comes up, click Finish. You will be rewarded with what is shown in Figure 1-33.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig33_HTML.jpg
Figure 1-33

Eclipse—the output of the first project

It might seem very convenient that Eclipse can launch Tomcat and show the output within the Workbench. In practice though, it has a couple of drawbacks. First of all, because of the side and bottom panes, the space available in the central pane is limited. As a result, most web pages are “too squeezed” to display correctly.

You can maximize the web panel by double-clicking the title bar, but there is also a more important reason: Eclipse doesn’t always display everything. It should copy all files from the project folder to a Tomcat work directory, but it doesn’t! It tends to “lose” CSS files and images. This means that, except for a quick check of simple features, you might do what I do and use Tomcat in Eclipse with an external browser.

In fact, if you open a browser and type localhost:8080/test, you should see the same result on a browser page as shown in Figure 1-34 (Firefox in the example).
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig34_HTML.jpg
Figure 1-34

The first project home page on browser

A second choice is to use Tomcat externally. To see the output of the test project outside Eclipse, first of all, stop the “internal” Tomcat by right-clicking it under the Servers tab of the Workbench and selecting Stop. Then, start the Tomcat service in Windows.

Right-click the test-project folder as you did to launch it within Eclipse, but this time select ExportWAR File.

When the WAR Export screen appears, the only thing you have to do is browse to select the destination, which should be %CATALINA_HOME%webapps est.war, and click Finish.

In a browser, type http://localhost:8080/test to see the output of the project. This works because Tomcat automatically expands all WAR files it discovers in its webapps folder, without any need to restart it, and because by default Tomcat looks for index.html, index.htm, and index.jsp. If you want, you can change the default by adding the following element to the body of the web-app element of web.xml:
<welcome-file-list>
    <welcome-file>whatever.jsp</welcome-file>
</welcome-file-list>

Listing the HTML-Request Parameters

With JSP you can generate dynamic web pages. That’s settled. But the utility of dynamic pages goes well beyond recognizing what browser the viewer is using or displaying different information on different days. What really matters is to be able to adapt the content of a web page on the basis of who the viewer is and what the viewer wants.

Each HTML request includes a series of parameters, which are usually the results of what the viewer enters into a form before hitting the “Submit” button. Additional parameters can also be part of the URL itself. For example, pages in multilingual websites sometimes have URLs ending with “?lang=en” to tell the server that it should format the requested page in English.

Listing 1-14—that you can insert in your Eclipse Project test—shows a simple JSP page that lists all the HTML-request parameters. It is a useful little tool you can use to easily check what your HTML pages actually send to the server.
<%@page language="java" contentType="text/html"%>
<%@page import="java.util.*, java.io.*"%>
<%
  Map      map = request.getParameterMap();
  Object[] keys = map.keySet().toArray();
  %>
<html><head><title>Request Parameters</title></head><body>
  Map size = <%=map.size()%>
  <table border="1">
    <tr><td>Map element</td><td>Par name</td><td>Par value[s]</td></tr>
<%
    for (int k = 0; k < keys.length; k++) {
      String[] pars = request.getParameterValues((String)keys[k]);
      out.print("<tr><td>" + k + "</td><td>'" + keys[k] + "'</td><td>");
      for (int j = 0; j < pars.length; j++) {
        if (j > 0) out.print(", ");
        out.print("'" + pars[j] + "'");
        }
      out.println("</td></tr>");
      }
  %>
    </table>
</body></html>
Listing 1-14

req_params.jsp

The interesting bits are in the lines I have highlighted in bold. The first one tells you that the parameters are stored in an object of type Map and shows you how to retrieve the list of the parameter names.

The second highlighted line shows you how to insert the value of a Java variable directly into the output (i.e., into the HTML page), by enclosing it between the pair <%= and %>. This is different from using a scriptlet, in which you can use JSP to build dynamicity into a web page.

The third highlighted line shows how to request the values of each parameter you know the name of. I said “values” instead of “value” because each parameter can appear more than once within the same request. For example, if you view the URL
http://localhost:8080/test/req_params.jsp?a=b&c=d&a=zzz&empty=&empty=&1=22
you get what you see in Figure 1-35.
../images/309332_3_En_1_Chapter/309332_3_En_1_Fig35_HTML.jpg
Figure 1-35

Output of req_params.jsp

Notice that the parameter aptly named empty appears twice in the query string, which results in two empty strings in the parameter map. Also, looking at the parameter a, you’ll notice that the values are returned in the same order in which they appear in the query string.

Summary

In this chapter, you learned how to install Java and Tomcat and how to check that they work correctly. You then learned how to install the Eclipse IDE, how to configure it to use the latest versions of Java and Tomcat, and how to create JSP applications from scratch.

After explaining what happens on the server when you click a link in your browser to view a new page, I introduced servlet and JSP technologies and explained what role they play in a web server.

Then, I showed you a simple HTML page and how you can begin to add dynamic content to it with JSP.

Finally, you learned how to use JSP to display the HTTP-request parameters .

Perhaps this was not the most exciting chapter, but you now have in place a basic development and run environment, without which you wouldn’t be able to proceed. And you have had your first taste of JSP.

In the next chapter, you’ll learn more about JavaServer Pages and how you can best structure web applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.60