Course Content‎ > ‎

Section 05: JavaServer Pages


Introduction to JSPs

JavaServer Pages, commonly known as JSPs, are a simple but powerful technology used to generate dynamic HTML on the server side. They allow Web developers and designers to develop and maintain platform-independent, information-rich, dynamic Web pages that support existing business systems. JSP pages help to achieve the design objective of seperating view and content. The user interface is seperated from content generation, enabling designers to change the overall page layout without altering the underlying dynamic content.

JavaServer Pages make use of XML-like tags and scriptlets written in Java to generate dynamic content. The JSP engine receives requests made by a client to a JSP page, then generates responses from the JSP page back to the client. Before going any further, let us consider the most simple 'Hello World' example as written by a servlet.


Hello World Example

<html> <head><title>JSP Hello World Example</title></head> <body> <h1> <% out.println("Hello World!"); %> </h1> </body> </html>

Source: hello.jsp

Deployment of JSP pages is considerably easier than for servlets - simply copy the SOURCE JSP file to your web content section of your application and then reference the file in the browser as normal. You do not need to precompile the JSP page in any way. So for example, if you wished to put your jsp pages inside a 'myjsps' directory (not required though) then you would copy your .jsp file to your student/myjsps directory and then use the following link:http://localhost/student/myjsps/HelloWorld.jsp. The output from this jsp example can be seen below. Obviously, in this example it would have been easier just to type 'Hello World!' into a plain html file, but we are providing it as an example before we introduce dynamic content, which can not be handled by plain html files.


Figure 5.1. HelloWorld JSP Output



Behind the Scenes

A JSP page is executed by a JSP engine, which is installed in a Web Server or Servlet/JSP Container such as Tomcat. In reality, the JSP engine is typically just another servlet that is mapped to the extension *.jsp. The JSP engine receives requests made by a client to a JSP page, then generates responses from the JSP page back to the client. When the server encounters a request for a JSP document, it recognises the *.jsp extension and realizes that special handling is required. The first time the file is requested, it is compiled into a servlet object and stored in memory, and the output is sent back to the requesting client. Storing the compiled servlet in the server cache increases the speed of response to subsequent calls to that page. After the first request, the server checks to see whether the *.jsp file has changed. If it has not changed, the server invokes the previously compiled servlet object. This process is described in the Figure below:


Figure 5.2. JSP Process Diagram


If you ran the above example on your own Tomcat deployment, you may have noticed that it takes a short time to respond. This is the time necessary for the server to create and compile the background servlet. Subsequent requests should be as fast as ever because the server can reuse the servlet. The obvious exception to this is the case where the .jsp file changes - the server will notice the change and recompile a new background servlet to reflect the changes. If an error is made to the .jsp file, the server will report the problem, typically within the page returned to the client. For example, if we simply remove the trailing bracket at the end of the out.println() method above, we would see the following output:

Figure 5.3. JSP Error Example


The JSP Specification is the product of industry-wide collaboration, led by Sun Microsystems. JSP pages share the "Write Once, Run Anywhere"characteristic of Java technology. Like servlets, JSP pages are typically packaged and combined with an XML descriptor file in a Web Application Archive (WAR) file. These WAR applications can be uploaded into a variesty of vendor application servers and accessed by browser-based clients. Considering again our Web Application structure:


Figure 5.4. Web Application Structure


JSP files are placed within the same directory level as HTML files, but can naturally be placed in 'other directories', subdirectories of the application root directory. They should not however be placed within the WEB-INF directory, or subdirectories of WEB-INF.


Features of JSP Pages

JSP pages make for efficient use of server-side Java. Their development can be shared among various developers while still promoting consistency and standards for development. We list some of the features of JSPs below:

  • Java Based - Server applications benefit from Java's development features such as type safety, virtual absence of memory leaks, security and multithreading. JSP is a key component of the Java 2 Platform, Enterprise Edition.

  • Reusable - Most JSP pages rely on reusable, cross-platform components (JavaBeans or EJBs) to perform the processing required of the application. Developers are able to share and exchange components that perform common operations, both speeding and simplifying overall development.

  • Seperate Business Login and Presentation - Using JSP technology, Web page developers construct HTML to format the Web page. JSP tags are used to generate the dynamic content on the page - the content that changes according to the request (perhaps a username for the client). As the core dynamic logic is encapsulated within these JSP tags, web designers can edit and work with the JSP page without affecting the generation of the content.

  • Large Community Support - Nearly all software developer vendors (with the exception of Microsoft :) have merged to form the "Java Community". The JSP specification is developed under the "Java Community Process", ensuring that the specification has a broad spectrum of industry input and support.

  • Platform Independent - JSP technology provides a component-based, platform-independent process for building Web-based applications. This widespread, multi-platform support allows web developers to write their JavaServer Pages code once and run it anywhere.

  • Ease of Development - Web page authors are not always programmers familiar with scripting languages - JSP technology allows much server-side functionality to be included using simple JSP specific tags. This means that web authors need not be accustomed to Java programming in order to perform simple common tasks, especially when using elements such as JavaBeans components.

  • Portable - As JSPs are part of the Web Application Structure, they can be ported in this format easily to alternate application servers.


JavaBeans

In the Java Servlets section we introduced JavaBeans for the first time, when we used a User.java bean to represent the entity concept of a user of our system.  In general in web development beans are used to store the state and methods for a particular real-world entity.  Similar to servlets, we can use JavaBeans from within JSP code.  For this example we simply provide a short and extremely simple example of a JavaBean, which we will include using JSP tags.

SimpleBean.java

package mybeans; public class SimpleBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } }

Source: SimpleBean.java

Note: This class file should be copied to a subdirectory of your classes directory called mybeans (feel free to rename it, but make sure the package corresponds). This simple bean (literally!) just defines two methods, one which sets the message variable, and the second which returns the message variable. You will notice that in comparison to a typical Java application there is no main method implemented, as this JavaBean is not expected to be directly executed. So in order to utilize this JavaBean, we can use it inside the following JSP.

<html> <head> <title>Reusing JavaBeans in JSP</title> </head> <body> <div style="text-align:center"> <jsp:useBean id="test" class="mybeans.SimpleBean" /> <jsp:setProperty name="test" property="message" value="Hello World!" /> <h1>Message: <jsp:getProperty name="test" property="message" /> </h1> </div> </body> </html>

Source: bean.jsp


Figure 5.5. SimpleBean.jsp Output using SimpleBean JavaBean



JSP Syntax

In this section, we briefly introduce some of the more common syntaxes used in JSPs:

Comments

  • HTML Comments - A typical HTML comment generates a comment that is sent to the client. Comments within JSP files operate very similar to any other HTML comments.

    <!-- comment -->
  • Hidden Comments - Hidden comments aren't sent to the client, they mark text or lines that the JSP container should ignore. The JSP contain does not process anything within the <%-- and --%> characters.

    <%-- This comment is not visible to the client --%>

JSP Directives

JSP Directives are used to define and set attributes that apply to the entire JSP page and the resulting servlet. A directive affects the overall structure of the servlet class. The syntax os a directive is: <%@ directive attr_name=value %> . Multiple attributes can be set as follows:

<%@ directive attrA="valueA" attrB="valueB" %>

There are three types of JSP directives:

  • include

  • page

  • taglib


include Directive

The include directive is used to instruct the JSP container to insert text into a JSP page at translation time. The included file can be an HTML file, a JSP file, a text file, or a code file written in the Java programming language. The syntax for an include directive is as follows:

<%@ include file="fileName" %>

As an example, let us write a JSP which just prints out the current date/time in large text HTML:

<%@ page import="java.util.*" %> <h1>The current date and time: <%= (new java.util.Date()).toLocaleString() %> </h1>

Source JSP File: DateTime.jsp


Now we can write a second JSP which "include"s the first:

<html><head> <title>JSP Include Example</title> </head> <body> This is the main page, which includes the following: <br/> <br/> <%@ include file="DateTime.jsp" %> </body> </html>

Source JSP File: JSPInclude.jsp


The output from this second JSP is as follows:

Figure 5.6. JSP Include Example Output



page Directive

A JSP page has attributes that describe its runtime behaviour. The page directive is used to define one of more attributes for the whole JSP page. No matter where the page directive is placed within the JSP file (or included file), it applies to the entire translational unit. There are quite a number of seperate page directive attributes - we will just cover a few of the more popular ones:

<%@ page import="java.util.*, java.sql.*" %>

import specifies in a comma-seperated list, the Java packages that the JSP file should import.

<%@ page session="true" %>

session="true|false" the session attribute can be set to true if the client must join a session in order to use the JSP page. If the value is false, the session variable isn't available to scripting elements in your page. The default value is true.

<%@ page contentType="text/html" %>

contentType defines the MIME type for the response. You can use any MIME type or character sets that are valid for the JSP container. This defaults to text/html.

<%@ page extends="ClassName" %>

extends - the fully qualified name of the superclass of the Java class file this JSP file will be compiled to.

<%@ page language="Java" %>

language="Scripting Language" - multiple scripting languages may be used in JSP files (assuming supported). The default value is java.


taglib Directive

The taglib directive, was not supported in JSP Version 1.0, but was implemented since JSP Version 1.1. The purpose of the taglib directive is to allow JSP authors to define their own tags. The <%@ taglib %> directive declares that the JSP file uses custom tags, names the tag library that defines them, and specifies their tag prefix. The taglib directive introduces an additional library of tags.

We will not be covering the taglib directive in further detail in this module.


Scripting Elements

JSP scripting elements allow Java code to be inserted into the servlet that will be generated from the defined JSP page. Script elements can be categorized into three types:

  • Declarations

  • Scriptlets

  • Expressions


Declarations

A JSP declaration allows you to define methods or variables that get inserted into the main body of the servlet class. The declared variables and methods have class scope and are available throughout the JSP page. You must declare variables or methods before you use them in your JSP file. Variable declarations and method definitions are embedded within a special set of tags: <%! and %>. The declaration of a variable and defintion of a method can be performed at any point in a JSP page. The syntax for a declaration is as follows:

<%! declaration; %> Examples: <%! String testString = "Hello World!"; %> <%! int x,y,z; %> <%! int count = 0; %>

Scriptlets

Scriptlets provide the ability to directly insert code into an HTML document. Scriptlets can contain any code that is valid based on the language specified in the language directive. This course will concentrate exclusively on Java code. A scriptlet is a block of Java code embedded in the service() method of the compiled servlet. Thus, the code is executed on every client's request. Any number of scriptlets can appear within a JSP page.

The syntax of a JSP scriptlet is listed as follows:
<% javacode %> eg. <% out.println("Your address is: " + request.getRemoteAddr()); %>

The XML equivalent can also be used:

<jsp:scriptlet> java_code </jsp:scriptlet>

So this could appear in the following JSP:

<html> <title>JSP Scriptlet Example</title> <body> <% out.println("Your address is: " + request.getRemoteAddr()); %> </body> </html>


Figure 5.7. JSP Scriptlet Output


There are four implicit variables automatically available to a JSP file.

  • request - this is a reference to the HttpServletRequest object

  • response - this is a reference to the HttpServletResponse object

  • in - this is a reference to the BufferedReader object that is part of the client request

  • out - this is a reference to the PrintWriter object that will be sent back to the client

It is for this reason, that we are able to use the "request" in the example above, even though it is not defined within the jsp file. Using the "request" (ie. the HttpServletRequest object) we can handle forms simply - consider the following example:

<html> <title>JSP Form Example</title> <body> <% out.println("Parameter A = " + request.getParameter("a")); out.println("<br/>Parameter B = " + request.getParameter("b")); %> </body> </html>

Source JSP File: SimpleForm.jsp

If this JSP file were set as the target of a HTML Form (either GET or POST) it would display the values entered in the form. Rather than write a form for this purpose (you should be able to write these forms yourself!) you can test this by simply passing the parameters in the URL. So for example, you might use: http://localhost/student/jsp/SimpleForm.jsp?a=test&b=test2 The output from this request to this jsp would appear as follows:

Figure 5.8 -  JSP Form Handler Output


Excercise: Try writing your own HTML form using the POST method and two fields a and b, and set the target of the form to be the above JSP.


Expressions

An expression element contains an expression that is valid in the scripting language used in the JSP page. They are like single-line scriptlets - you can think of an expression as a tag that will be replaced by the value of the evaluated expression. This is a shortcut notation for inserting values directly into the output. The value is evaluated, converted to a string, and inserted where the expression appears in your JSP file. The syntax for an expression is:

<%= expression %> eg. The current time is: <%= new java.util.Date() %> Your IP address is: <%= request.getRemoteAddr() %> <%=number1 + " multiplied by " + number2 + " gives " + number1*number2%>


JSP Examples

To help develop your familiarity with JSPs, we provide some examples which use JSPs - you should get used to these and deploy them on Tomcat.


Text Comparison

This JSP reads in two text strings from a self-generated form (ie. the form is generated within the JSP if the parameters are not provided) and compares them, deciding if they are identical or not.

comparison.jsp

<html> <head> <title>String Comparison JSP</title> </head> <body> <%! String stringA = null; %> <%! String stringB = null; %> <% if (request.getParameter("stringA")==null) { // display form %> <br/>Please enter the two strings for comparison:<br/> <form method="post" action="comparison.jsp" name="myform"> <br/>First String: <input name="stringA" /> <br/>Second String: <input name="stringB" /> <br/><br/><input type="submit" value="Submit Form"> <input type="reset" value="Reset"> <% } else { // The parameters exist so do the comparison stringA = request.getParameter("stringA"); stringB = request.getParameter("stringB"); if (stringA.equals(stringB)) out.println("<br/>The two strings <b>ARE</b> identical!!"); else out.println("<br/>The two strings <b>ARE NOT</b> identical!!"); } %> </body> </html>

Source: comparison.jsp 

You will notice that in this example, we don't even create a seperate HTML form as a file. Instead, we simply call the JSP, which checks to see if parameters have already been passed so it can perform the comparison. If parameters have not been passed (the getParameter method will return a null), then we generate up the form for entering the details. Essentially, we are using the JSP file to generate a HTML form.


Local Access Test

This JSP checks the IP address of the client making the request. Let us suppose that a system administrator only wishes people within a certain ip address range to access certain applications (eg. only people on the finance network within a company can access FinanceBalance.jsp). While this JSP does not add any further functionality, it provides sample code you could use to implement your own IP-based security:

LocalCheck.jsp

<html> <head> <title>Local IP Check JSP</title> </head> <body> <%! String userIP = null; %> <%-- Test if ip begins with 136.206 (DCU) or 127.0.0.1 (localhost) --%> <% userIP = request.getRemoteAddr(); if ((userIP.substring(0,6).equals("136.206")) ||(userIP.equals("127.0.0.1"))) { %> <h1>ACCESS GRANTED</h1> User is accessing page at DCU or locally! <br/><br/>The secret password is: spk.ll <% } else { // The client is not at DCU or on the local machine out.println("<h1>ACCESS DENIED</h1>"); out.println("Illegal access from an external machine with IP Address: " + userIP); // Email an administrator, make a log or whatever..... } %> </body> </html>

Source: LocalCheck.jsp 

All computers on the Internet have an address, known as an Internet Protocol Address (IP). When any user makes a request to a web server their IP address accompanies the request (the server needs to know where to send things!). IPv4 addresses have the form [0-255].[0.255].[0-255].[0.255] such as 136.206.25.27. There are a number of IP addresses, which are not valid globally such as 127.0.0.1 or 'localhost'. Regardless of what machine you are using, connecting to 127.0.0.1 is always the same as connecting to the same machine.

This JSP does a IP range test, which checks whether the user IP address begins with "136.206" which is DCU's domain. Alternatively, if the IP address is 127.0.0.1 this is also allowed, as it means that the user is sitting at the server machine. If the user passes the IP test, they will be granted access and provided with the secret password :)


JSP Database Connectivity

Naturally, many JSP applications require connecting to a database, whether for maintaining company information, storing order and customer details, student registration information etc. JSPs like Servlets connect to databases using JDBC (Java DataBase Connectivity), which is covered later in the module.

Please visit the Database Connectivity Chapter for further information and examples on connecting to databases.

Comments