MLAJ185-01 Advanced Java Programming Learning Manual - V1.0 April 2018 PDF
MLAJ185-01 Advanced Java Programming Learning Manual - V1.0 April 2018 PDF
MLAJ185-01
Advanced Java-Programming
MLAJ185-01
Compiled by: Petrus Pelser, Carla Labuschagne and Tatenda Tagutanazvo
Version 1.0
Projects 296
Project 1 – Forum 297
Project 2 – Antique Auctions 301
Glossary 307
References 308
This unit builds on the Java Part 1 course. Students will be introduced to two
Java Enterprise Edition technologies, namely: JavaServer pages and Web
services. Students will also learn how to create mobile applications for use
on wireless devices such as Android mobile devices.
In the first part of the course students will combine a wide variety of Web-
related technologies to develop dynamic Web-based applications, using Java
Servlets, JavaBeans and JavaServer Pages. Students will learn all the basic
techniques and elements used in JSPs, and will also learn how to write their
own JSP custom tags, and how to retrieve records from databases and
display them in JSPs.
There has been a big move away from applications that run off one
computer, with all the components and resources on that one computer, to a
distributed application environment. With the boom of connections to the
Internet these applications do not have to be local to your network. Students
will be introduced to Web services. The second part will guide students
towards creating Web services by using technologies such as JAX-WS, JAXP
and RESTful.
This final part will focus on using the Android Studio to build applications for
use on Android devices. The student will learn how to build graphical
Android applications, implement input and output operations, and how to
enable external devices to access the application resources.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 1 of 309
Assessment for pass
A pass is awarded for the unit on the achievement of all the pass assessment
criteria.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 2 of 309
Reference books
Additional reference books will be listed at the end of each unit. This
supplementary reading is not mandatory, but it will certainly help you to
answer some of the intermediate and advanced questions in the exams. This
reference material will be a great aid if you would like to know more or gain a
different perspective on what you have learnt in this course.
This module is divided into three units. Each unit consists of:
Theory
Examples
Exercises
A theory exam will be written at the end of each unit. You will need to complete
a project at the end of this course. You will write a theory and a practical exam
after you have completed the project. Ensure that you know and understand
the theory before continuing with an exercise, project or exam. Everyone wants
to get their hands dirty as soon as possible with regard to actual programming,
but there will be many opportunities to practise what you have learnt. Work
through the examples in the reference book and complete all the exercises
before attempting the project and exam. Application questions will be asked in
the exam – you must be able to apply your knowledge to practical situations.
You will not pass the exam if you rush through the material and do the project
without understanding what you have learnt. The exams are designed to test
theory, insight and practical skills. Theory exams will consist of multiple choice
questions, identifying errors in an existing section of code, multiple response
questions and selection questions. The practical exam will present you with the
opportunity to code a program on a computer.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 3 of 309
It is very important to use all the study aids available to you. Some of the
questions in the exams will test your general knowledge on advanced subjects
that may not have been covered in the learning manual, although the content
in the learning manual will be sufficient to ensure that you pass each unit.
Take note that each unit builds on previous units. Exams will cover all
the material with which you should be familiar from Basic Java
Programming Module (Unit 1-3). For example, the exam at the end of
Unit 6 will also cover material from all units (unit 1- unit 6). The Unit 5
exam will also cover material from Unit 1 to Unit 5.
You have a certain number of days to complete the course, including all three
units, the project, the theory exams and the practical exam.
Structure of a unit
All the units follow the same structure. You will be presented with the
outcomes for each unit. These outcomes can be used as an indication of what
is important and what you should focus on when going through the unit’s
material. Notes will follow this. Read these sections carefully. Key terms will
list what you should have read and understood in the unit.
You will be presented with exercises that will require you to apply your
knowledge of the material. Ensure that you understand the exercises. Ask for
help if you are unsure of what to do. Revision questions will give you an
indication of what to expect in the examination, although you should not rely on
these questions as your only reference. Some examination questions will
undoubtedly be more difficult than the revision questions.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 4 of 309
You will find the project specifications at the end of the learning manual.
Please do not start working on the project until you have completed (and
understood) all the exercises. Once you have covered all the topics from the
previous units and you are satisfied that you have met the outcomes, you may
start the project. Use the project specifications as a guide. They will list
everything that you need to do to comply with the project’s requirements. If
your project does not comply with these requirements, it will not be marked.
Please see the mark sheets for each project. These indicate how the marks will
be allocated.
Beginning a project
It is suggested that you read through your project as soon as you receive your
new learning manual. This will give you an idea of what is expected of the
project. As you progress through the guide, you will start identifying how to
approach the project. You should only start on your project once you have
worked through the entire learning manual and have a good understanding of
the material. Performing the following steps will help to ensure that you
complete your project successfully:
1. Read the relevant section in the learning manual to familiarise yourself with
the material.
2. Type the examples. This might seem pointless, but it is an easy way to
familiarise yourself with the language. Experiment with the code; make
deliberate mistakes to get a feel for the way in which the compiler handles
errors.
3. Complete the exercises at the end of every chapter in the reference book
(Sams Teach Yourself Java in 21 Days). The best way to learn a language is
to practise it. This will also help you in the examination.
4. Only start with the project if you feel comfortable with the material.
5. Make use of textbooks when the need arises.
If you work according to these guidelines, you should find that the projects are
not too difficult.
Your lecturer will mark your projects and you will find the project evaluation
forms at the back of your learning manual. Your lecturer can also provide
these to you on request. The general expectations for each of the sections are
provided below:
Project specification
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 5 of 309
Program design
You must follow the project specifications. For example, if the project
specifications instruct you to use a specific class, you will need to use that
class. You will be allowed to be creative, but you will be required to incorporate
certain elements into the project.
The first step in any program development cycle should be a design phase:
what exactly it is that you want to do, and how you will achieve it.
Source code
For any serious program that you develop, it is almost guaranteed that either
you or another programmer will have to return to the code on occasion to
correct a problem or add a new feature. It is thus important that your code is
easy to read. One way to make code easy to read is by using indentation and
whitespace.
Your code should also contain comments that clearly explain what is intended
by structures and blocks in the code. If a programmer who has to maintain the
code has to try to understand what it was that you intended first, it not only
wastes time but also opens up the possibility that the intention may be
misunderstood, which may lead to further problems.
The program source code must be clear and well laid out.
You must follow a set naming standard for variable and method names.
Method and variable names should be descriptive.
Each file must be clearly labelled, with a prologue displaying the following
details in comments:
o Name of the file
o Name of the author
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 6 of 309
o Date created
o Operating system
o Version
o Description of the code
For example:
The source code must be printed and submitted with your final project
submission. (This includes any projects submitted electronically.)
Program content
The program does not run or if there are warnings of any kind. Your
program must compile and work properly before you submit it. If your
program does not run correctly, you will fail the project and you
will need to redo it. If you follow the project specification and your
program runs without any extra effort, you should receive at least 60% for
the project. Possible deductions are listed below:
o Project returned and resubmitted (-10%)
o Project copied (resubmit and -20%)
o Program does not run or crashes (resubmit and -20%)
o Redundant code (-10%)
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 7 of 309
There are calculation errors.
There are invalid variable conversions, e.g. float with an integer variable.
There is unnecessary code in the main() method (if applicable).
User interface
User documentation
Those who have to maintain the code must know what was intended by
every single line of code (called program design documentation and source
code documentation).
Those who have to use the program must know how to run it, what to
expect and what output will be displayed or printed (called user
documentation).
You should supply extensive descriptions for your classes and members.
Documentation must be in the form of a Word document unless stated
otherwise.
The user documentation must adequately explain how to install and run the
application, working on the assumption that the end user has no prior
experience of doing so.
The user documentation must explain how to use each feature of the
application. The screenshots included must clarify each operation.
The user documentation should consist of the following:
o An index page
o A description of the program
o Instructions on which operating system to use
o The type and version of programs used
o How to install and set up the program
o How to run the program
o What values to enter when asked for user input
o How to handle any error messages
o Screenshots of all operations
o Bibliography
The user documentation must be printed and submitted with your final project
submission. (This includes any project submitted electronically.)
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 8 of 309
Project documentation
Your project documentation must include all of the following when submitting
your project:
Project specification
Program design
Project source code
User documentation
Databases (if any)
Resources (if any)
System requirements (if any)
Rough work (if any)
System requirements
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 9 of 309
Icons used in the learning manual
Denotes the outcomes of the unit, i.e. the knowledge and skills
that you should have acquired after each section
Points out the keywords for each section. Ensure that you can
name and explain all the keywords before proceeding to the next
section.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 10 of 309
Unit 4 – Storing Data
Introduction to HTML – You will learn just the basic tags of HTML and
how they work.
Introduction to JavaServer Pages – You will learn what a JSP is and
what the benefits of JSPs are.
Servlets – The basic concepts of servlets will be discussed as well as
the differences between servlets and JSPs.
Programming JSP Scripts – You will be introduced to directives, tags
and scripting elements in JSP.
Implicit objects, actions and scope – You will learn about implicit objects
in JSP and also how to use actions and scope effectively in JSPs.
JavaBeans and JDBC – You will learn how to access databases in JSP
and how to incorporate JavaBeans effectively when managing data.
Custom tag libraries – You will learn how to create and use your
own custom tags in JSP.
Creating a Web application – You will learn how to create Web
applications in NetBeans.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 11 of 309
4.1 Introduction to HTML
4.1.3 XML
Another derivative of SGML is XML (Extensible Markup Language). XML allows
you to create your own tags and to define your document structure. XML
separates the content of a page from its design.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 12 of 309
</i></font></h1>.
All attribute values should be quoted, e.g. <body style="background-
color:black">.
<html>
<head>
<title>Testing HTML</title>
</head>
<body>
The sky is blue
</body>
</html>
Example 3 – Indentation
html – These tags surround all the other tags in an HTML document.
head – These tags include the title content and scripting content. (Scripting
will be covered later.)
body – These tags contain all the content that is displayed in the browser.
<html>
<head>
<title>HTML Title</title>
</head>
<body>
<!-- Comment -->
<h1>This is a HTML page!</h1>
</body>
</html>
Example 4 – FirstPage.html
Another tag in the code was the <!-- --> tag. This tag is used to place
comments in your code. Comments are ignored by the browser and are used
to explain code to other programmers, or to remind you of what the code is
doing when you look at it at a later stage.
Click on the File menu in the application and click Save As…. This will open a
screen where you can choose the location in which you want to save your
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 13 of 309
HTML document. Save the code as FirstPage.html. Open the file in Google
Chrome. The output should look like this:
Title
Now you know how to write and display a basic HTML page.
<html>
<head>
<title>HTML background colour</title>
</head>
<body style="background-color:lightblue">
<h1>This is an HTML page!</h1>
</body>
</html>
Example 5 – Changing the background colour
Refresh your browser and note that the background has been set to a different
colour.
There are six levels of HTML headings. Headings are displayed in larger and
bolder font than normal text. The font size for each level is smaller than the
previous one, i.e. the font of level six is smaller than the font of level five.
Include the following tags inside the body tags of FirstPage.html:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 14 of 309
<h1>Heading 1</h1>
<h3>Heading 3</h3>
Save the file and run it in the browser. Note the size difference of each line.
<html>
<head>
<title>HTML Aligning text</title>
</head>
<body style="background-color:lightblue">
<h1 style="text-align:center">This is a HTML page!</h1>
<h1>Heading 1</h1>
<h3>Heading 3</h3>
</body>
</html>
Example 6 – Alignment
Save the code and refresh the browser. This can be done by pressing the Refresh
button or by pressing F5. Note that the text for the first <h1> tag has now been
moved to the centre of the page.
Hexadecimal notation can also be used to define a more specific colour. This is
done by specifying the RGB (Red, Green, Blue) values as a hexadecimal value.
Edit FirstPage.html to look like this:
<html>
<head>
<title>Displaying colour</title>
</head>
<body style="text-align:center">
<h1 style="color:#755331">Heading 1</h1>
<h3 style="color:tan">Heading 3</h3>
</body>
</html>
Example 7 – Changing colour
Save the code and refresh your browser. Note the two different colours.
The table below shows the style attributes.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 15 of 309
Table 2 – Style attributes
Attribute Value
Colour Colour name, hex value
Font size [Size] pt
Text align Left, centre, right, justify
Font weight Normal, bold
Word spacing Normal, [length]
Text transform None, capitalise, uppercase, lowercase
Font family Font name, e.g. Arial
<p> … </p>
The paragraph tag defines a new paragraph, leaving
some space between it and the previous paragraph
Preformatted text, where whitespace in the source
<pre> …
</pre> document is retained in the display. Used to display
text in preset columns, etc.
<q> … </q>
Used to display a short quote with no paragraph
breaks
<small> …
</small> Small text relative to the surrounding text
<strong> …
</strong> Strongly displayed text
<sub> …
</sub> Text displayed as a subscript
<sup> …
</sup> Text displayed as a superscript
<tt> … </tt> Teletype or mono-spaced text (typewriter text)
<u> … </u> Underlined text.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 16 of 309
NOTE For text aligning, font size and colour, you will be using the
style sheets or the following example for style attribute:
style=”color:blue”
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 17 of 309
4.1.6 Key terms
Make sure that you understand the following key terms before you
start with the exercises:
HTML
World Wide Web Consortium
XML
4.1.7 Exercises
1. True/False: Markup means changing the look and function of text and
objects.
2. True/False: HTML that follows the same rules as XML is referred to as
XHTML.
3. Write down the line of code used to make or change the colour of text to
red enclosed in the header 1, <h1>, tag.
4. Write down the code used to insert the entity name for the copyright
symbol for any header tag.
5. Which one of the following is not a value of text-align?
a) Left
b) Right
c) Middle
d) Justify
1. Write an HTML code for a Home.HTML page. The title of the page should be
“My first page”; this page should display centred body text, “Welcome to
my page” of size heading 1. Add a background colour to the page of your
choice.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 18 of 309
4.2 Introduction to JavaServer Pages
JSP pages are made up of static and dynamic content. The static content is
generally written in html and the dynamic content is written in Java as scripts
and embedded within the html. When a request is sent to the Web server, the
JSP code or dynamic code is executed on the Web server and the response is
displayed as normal html to the Web browser.
Before JSP was developed, servlets were used to create Web content
dynamically. Servlets are small, Java-based applications that are used for
adding interactive functionality to Web servers. Java servlets receive an HTTP
request from a Web browser as input, and return appropriate content for the
server’s response, just as CGI does, except servlets do not require a new
process for each new request. Instead the JVM creates a Java thread to handle
each servlet request, making servlet execution much more efficient than CGI
processing. The problem with Java servlets is that they do not allow a
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 19 of 309
developer to fine-tune the appearance of a web page without having to edit
and recompile the Java servlet. This is why JSP was introduced.
End users do not have to install any additional software to run applications.
Nearly unlimited access.
Only one server-based program needs to be changed.
End users have automatic access to all upgrades.
Simplified application deployment and management.
As part of J2EE, JSP pages have access to all J2EE components, including
JavaBeans, Enterprise JavaBean components and Java Servlets.
When a Web server receives a request from a JSP page, it refers the request to
a special servlet known as the page compiler. The page compiler’s function is
to compile the JSP page into a page specific servlet. The page compiler is a
single Java process, running a JVM. It is separate from the HTTP server and
handles all servlet-related requests, including JSP. The page compiler handles
multiple requests for a given servlet or JSP at the same time using Java
threads. The resulting page is sent back to the browser.
The JSP tags are designed for creating, querying, modifying and accessing
server-side JavaBeans which are written in Java in a way that promotes
modularity and reusability.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 20 of 309
There are many advantages to JSP when it is compared with other
technologies:
Server refers to hardware (in the form of a computer accessible over the
Internet or an intranet) and software (in the form of an HTTP server running
on that hardware).
The most popular HTTP servers include Apache, Sun Application Server,
Microsoft’s Internet Information Server and JBoss Application Server.
Most providers of JSP containers include an installation program that will take
care of the details of configuring your Web server to support JavaServer pages.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 21 of 309
4.2.4.1 Installing Apache Tomcat for Windows
Tomcat requires at least the JDK 6 or any later version to be installed. We will
be using the JDK 8 and JRE 8 and install Tomcat 9 in this learning manual.
You will have to run the Tomcat 9 Windows installer package you have. You
can also download it for free at the following website: http://tomcat.apache.org/
Click Next.
Accept and agree with the licence.
Check all boxes on the components page and click Next.
Change the HTTP/1.1 Connector Port to 3128 and the AJP/Connector Port to
3306. (As many servers use port 8080 this is to reduce the chances of you
having problems running the server.)
Click Next.
On Java Virtual Machine, leave the path as shown and then click Next and
then Install.
Once it’s done installing, untick the Show Readme box, and then click
Finish.
Open the browser and type in localhost:3128. This will bring up the
Apache Tomcat Server screen and you have succeeded with the installation.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 22 of 309
Figure 3 – The Welcome screen
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 23 of 309
<html>
<body>
</body>
</html>
Example 8 – First.jsp
In the WEB-INF directory in the Test directory, you can alter the
web.xml file with the following code and save:
<web-app>
<display-name>First</display-name>
</web-app>
Example 9 – web.xml
NOTE You do not need to restart the server each time you deploy a new
application. The server will check the deploy directory
periodically and update the status of the deployed applications.
4.2.5 Index.html
An index page makes navigation around your files much easier. You can create
an HTML page with all your completed exercises as links and save it as
index.html. This file will have to be packaged together with the other files.
The index page will come up in the web browser by default when the URL
points to the directory where it is saved. To access the index page, type
http://localhost:3128/examples into the web browser’s address field. The
index page will be displayed, as shown in Figure 5 below.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 24 of 309
Figure 5 – index.html
Type the following example and save it as test.html in the Test directory:
<<html>
<body style="background-color:gray">
<h1><b>Exercise Examples</b></h1>
<h2>Unit 1</h2>
<a href="http://localhost:3128/Test/First.jsp">
Test.jsp</a><br/>
<h2>Unit 2</h2>
<a href="http://localhost:3128/time">Time.jsp</a>
</body>
</html>
Example 10 – test.html
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 25 of 309
Figure 6 – Example of an Index.html page
Click on the Test.jsp link to open our first example we created earlier.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 26 of 309
Figure 7 – The JSP life cycle
For your applications to work, you will need to add a CLASSPATH variable to
your environment variables. This will enable the compiler to find the Java EE
classes.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 27 of 309
In the name field, type in JAVAEE_HOME.
In the value field, type in the path where the Java EE SDK was installed on
your system.
In the System variables box, click on New.
In the name field, type in CLASSPATH.
In the value field, type %JAVAEE_HOME%\glassfish5\lib\javaee.jar.
Click OK to add the variable.
Close all the windows.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 28 of 309
4.2.8 Key terms
Make sure that you understand the following key terms before you
start with the exercises:
JSP
Servlets
Tomcat
Path
JSP container
ASP
CGI
4.2.9 Exercises
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 29 of 309
4.3 Servlets
Java servlets are very powerful because, being written in Java, they can be
ported to a wide range of operating systems (wherever there is a running
JVM). Servlets play an integral part within enterprises producing dynamic Web
content. For example, servlets can be used to provide custom information to
users who log in to a website, based on their login name and password.
Servlet example:
/*
* NameServlet class illustrates a basic approach to using Java
Servlets
*/
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 30 of 309
HttpServletResponse
response)
throws ServletException, IOException {
Save this file in a new directory (C:\NewServ). Now you need to compile
the file using the java compiler.
Right-click on the start menu button and click Command Prompt (Admin).
Click yes when you see a pop-up message requesting authorisation.
In the command prompt window, change file path to the folder you created
by typing the following:
cd C:\NewServ
Now you will compile the java file by doing the following:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 31 of 309
javac -classpath "C:\Program Files\Apache Software
Foundation\Tomcat 9.0\lib\servlet-api.jar" NameServlet.java
Now go to:
Now you need to edit the web.xml file located in the WEB-INF folder in order
to specify the location of your servlet. Add the following:
<servlet>
<servlet-name>NameServlet</servlet-name>
<display-name>NameServlet</display-name>
<servlet-class>NameServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NameServlet</servlet-name>
<url-pattern>/NameServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Example 12 – web.xml
Make sure you add the above entries between the </web-app> tags of your
web.xml file. Save the web.xml file in your NewServ directory.
Create an html file and name it nameindex.html. Add the following to the
html file:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 32 of 309
<html>
<body style="background-color:gray">
<h1><b>Exercises Examples</b></h1>
<h2>Unit 1</h2>
<a href="http://localhost:3128/test">Test.jsp</a><br/>
<h2>Unit 2</h2>
<a href="http://localhost:3128/time">Time.jsp</a>
</body>
</html>
Example 13 ‒ nameindex.html
Now copy the nameindex.html file to the ROOT directory of your Tomcat
installation under: C:\Program Files\Apache Software
Foundation\Tomcat 9.0\webapps\ROOT
<html>
<body style="background-color:lightyellow">
<%
String name = "Wow, this servlet works great!!";
out.println("Name: " + name );
%>
</body>
</html>
Example 14 – Name.jsp
The following screen will be displayed when you run the servlet or the JSP:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 33 of 309
Figure 9 – NameServlet or Name JSP printout
As you can see, both the servlet and the JSP produce the exact same output,
but the code you had to type to produce it differs greatly. The JSP container
uses the JSP code to generate a servlet which would look similar to the
NameServlet code.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 34 of 309
not needed inside the JSP file because JSP scripts include several implicit
objects automatically; out being one of these objects. Aside from overriding
methods and extending classes, a servlet is basically a JSP file with many
out.print statements to express its output.
HTTP actions are used to send data, usually parameter data, to the servlet or
JSP in a certain format. There are various HTTP actions which can be used
along with the HttpServlet methods, but we will focus on GET and POST.
Here is a list of the available HTTP actions and their equivalent HttpServlet
methods:
For HTTP GET actions, the parameters are appended to the end of the URL, for
example: http://127.0.0.1:8080/tim/source/unit4/EmployeeServlet?fname=Tim.
The parameters are separated from the URL by a question mark (?), multiple
parameter values are separated by an ampersand (&), and spaces are
represented by a plus sign (+).
NOTE When you are not connected to a network, your localhost will
run on 127.0.0.1.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 35 of 309
The following code is the HTML code which submits its data to the
EmployeeServlet:
<html>
<body>
<form action="EmployeeServlet" method="GET">
<!-- GET is the default HTTP action -->
<center>
Name: <input type="text" name="fname"/><br/>
Name: <input type="text" name="lname"/><br/>
<input type="submit" value="Submit">
</center>
</form>
</body>
</html>
Example 15 – input.html
Save this input.html file in the NewServ folder you created in the earlier
example.
The following EmployeeServlet code retrieves the text fields’ values which are
appended to the URL using the GET method:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 36 of 309
//this method is used to provide a POST request from a browser
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
Save this file in the same directory as the input.html file. Now you have to
compile the file using the java compiler as the example in the previous section.
Change file path to the folder you created by typing the following in the
command prompt window: cd C:\NewServ
You need to edit the web.xml file located in the WEB-INF folder in order to
specify the location of your servlet as we did in the earlier example. Copy the
unedited web.xml file as back up before proceeding. Now, add the following:
<servlet>
<servlet-name>EmployeeServlet</servlet-name>
<display-name>EmployeeServlet</display-name>
<servlet-class>EmployeeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EmployeeServlet</servlet-name>
<url-pattern>/EmployeeServlet</url-pattern>
</servlet-mapping>
Example 17 – web.xml
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 37 of 309
Make sure you add the above enteries between the </web-app> tags of
your web.xml file. Now save the web.xml file.
Copy the input.html file you created under C:\NewServ and paste it in
C:\Program Files\Apache Software Foundation\Tomcat
9.0\webapps\ROOT
The following page will be displayed when you run the program:
Figure 10 – input.html
Enter text in the text boxes and press the Submit button. You
should get an output similar to the following:
Figure 11 – EmployeeServlet
Note that if no HTTP method is explicitly specified, then GET is the default
method.
For HTTP POST parameters, a more complex protocol is used to send the
parameters behind the scenes. As a general rule, POST parameters should be
used when the entire URL, including the parameters, is longer than 255
characters. Modify the input.html file’s <form> tag’s "method" attribute as
follows: method="POST".
Redeploy the example and re-run the input.html file. You will notice that
there are no parameters appended to the URL. The parameters are sent behind
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 38 of 309
the scenes. This POST action could be very significant in circumstances where
you would not like users to be able to edit the parameters (for security
purposes). For example, if you have a web page that forwards a single
parameter that represents a password to the end of the URL, if you use GET
the password will not be encrypted. This means if someone happened to see
the URL that was generated, that person could simply type in the URL along
with the parameters at the end of the URL and could then access someone
else’s personal data.
<html>
<body>
</body>
</html>
Example 18 – Employee.jsp
Save this file as Employee.jsp. To run this file, change the input.html file so
that the <form> tag’s action attribute is Employee.jsp. The output will be the
same as that of the EmployeeServlet.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 39 of 309
4.3.4 Key terms
Make sure that you understand the following key terms before you start with
the exercises.
Servlets
GET
POST
Request
Response
PrintWriter
4.3.5 Exercises
1. True/False: There is a separate servlet running on the server for every user
request in a Web-based application.
2. True/False: Java servlets can be run on any platform or any operating
system where there is a running JVM.
3. True/False: JSP technology is based on the original servlet specification,
but is focused on separating presentation from implementation.
4. True/False: A thorough knowledge of Java is necessary to code a simple
JSP page.
5. True/False: It is not necessary to compile a JSP page.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 40 of 309
4.4 Programming JSP scripts
Scripting-oriented tags
XML-based tags
These two tag styles are interchangeable, although some compilers do not
recognise the XML-based tags.
Scripting-oriented tags are self-contained tags that begin with <% and end with
%>. Anything within these tags is evaluated by the Java Virtual Machine. A
further meaning is given to the tag using the characters (!, =, or @). These will
be discussed as we progress through this section.
XML-based tags follow the XML syntax and conventions. They are case
sensitive, and all attribute values must be enclosed in single or double quotes.
Tags that do not contain body content use < and /> as their opening and
closing delimiters. For example:
Tags that have body content use < and > for the opening tag and </ and > for
the closing tag. For example:
JSP tags can be embedded within HTML and XML document tags, as well as
within other JSP tags under certain circumstances. For example, a JSP
expression can be used to specify the value of the page attribute:
These embedded tags are called request-time attribute values, and will be
discussed in more detail at a later stage.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 41 of 309
Tags are easy to use and are shared between applications. Later in the course
we will discuss how we can develop custom tag libraries in which tags can be
created and distributed for specific purposes.
Directives
Scripting
Actions
page
include
taglib (tag library)
Directives do not directly produce any visible output to end users when the
page is requested. They allow you to control the overall structure and global
information about the JSP page.
For example:
For example:
To assign multiple attribute settings for a single directive, the following syntax
is used:
Or in XML syntax:
<jsp:directive.directiveType attribute1="value1"
attribute2="value2" attribute3=.../>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 42 of 309
NOTE It is standard to place a whitespace after <%@ and before %> in
the scripting-oriented tags.
Or:
There are 11 different attributes recognised for the page directive. Take note
of the following concerning the use of some of the attributes:
With the exception of the import attribute, a page directive attribute may
not be specified more than once on the same page.
If a JSP page contains an unrecognised attribute, a translation time error
will result when the JSP container attempts to generate the source code for
the corresponding servlet.
autoFlush
buffer
contentType
extends
import
info
isThreadSafe
language
session
errorPage
isErrorPage
The default value is true which indicates that the output buffer is flushed
automatically if it becomes full. The content is sent to the HTTP server. If the
autoFlush attribute is set to false, the JSP container will not flush automatically
and, when the buffer is full, processing of the JSP page will stop and an error
page will be displayed in the browser that requested the page. If you wish to
set the autoFlush attribute to false, ensure that the page’s buffer is large
enough for any possible output that may be generated by the page.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 43 of 309
4.4.2.1.2 buffer attribute
The buffer attribute controls the use of the buffer output for a JSP page. If the
attribute is set to none, all of the JSP content will be passed directly to the
HTTP server. For example:
To set the size of the output buffer, a kilobyte attribute value must be specified
as follows:
The default is usually 8kb which is sufficient for most pages. Pages that
generate large amounts of dynamic content may need larger output buffers.
The default is text/html. To specify an alternative character set for the JSP
page which will allow the author to deliver localised content using the most
appropriate language encoding, the following can be used:
The class can be referred to by its class name once the package or class has
been imported (e.g. Date). import is the only attribute of the page directive
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 44 of 309
that can occur more than once in a single JSP page. Many classes and
packages may be imported in a single page. More than one package and/or
class may be imported using a single import directive. For example:
Note that, if Java is the scripting language, the page automatically imports all
the classes from the following packages:
java.lang
java.servlet
javax.servlet.http
javax.servlet.jsp
The default value is true. Setting the attribute to false will cause the JSP
container to wait for the current request to finish processing before starting
the next sequential request, therefore only handling one thread at a time. This
is usually not a good idea as it may result in substantial performance loss.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 45 of 309
The default is true. A slight performance gain can be obtained by setting this
attribute to false. However, if an attempt is made to access the session
variable, an error will occur when the JSP page is translated into a servlet.
The page specified by the error page attribute must be on the same server as
the original page.
The following example retrieves a value from the URL and uses it to decide
whether or not an exception should be thrown. When an exception is thrown
the ErrorPage.jsp is displayed.
<html>
<body style="background-color: lightgreen">
<%
/* gets the errorValue from the URL */
error = request.getParameter("errorValue");
(error.equalsIgnoreCase("true")){
new Exception("My own error has occurred");
} else {
.println("<h4> There is no error so this page is shown
</h4>");
}
%>
</body>
</html>
Example 19 – MyError.jsp
The next bit of code is the actual error page that is referenced from the
previous example if an exception occurs:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 46 of 309
<!-- uses the page directive's isErrorPage attribute to
make this page the errorpage. -->
<%@ page isErrorPage="true" %>
<html>
<body style="background-color: red">
</body>
</html>
Example 20 – ErrorPage.jsp
Save this file as ErrorPage.jsp. To run these examples, execute the page with
an errorValue of false:
./MyError.jsp?errorValue=false
The page should display “There is no error so this page is displayed”. Now type
in the URL again, but change the errorValue to true. The ErrorPage should now
be displayed with “There is a huge error. My own error has occurred”. If you
leave out the entire errorValue section in the URL the ErrorPage will also be
displayed because a NullPointerException will occur.
Or:
You may include as many files as you wish, provided they all use the same
scripting language as the original page. The contents of the included file
may be static text (e.g. HTML) or JSP elements.
If the JSP page has been modified, the JSP container will recompile only the
servlet associated with that JSP page and not the file that is included.
Any change made to files included via the include directive will not cause a
new JSP servlet to be generated.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 47 of 309
<%@ taglib uri="tagLibaryURI" prefix="tagPrefix" %>
Or:
The uri attribute indicates the location of the Tag Library Descriptor
(TLD) file for the library. The prefix attribute specifies the XML namespace
identifier that you will use to access a library tag. To reference a tag from
the library use:
<tagPrefix:tag/>
For example:
<mytaglibrary:mytag/>
Declarations
Scriptlets
Expressions
4.4.3.1 Declarations
Declarations are inserted into the body of the servlet class and are used to
define variables and methods for a page, which may be referenced by other
scripting elements on that page. The syntax is:
More than one declaration may appear within a single tag, but each
declaration must be a complete declarative statement. Each declarative
statement must be separated by a semicolon from the other declarations.
For example:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 48 of 309
These variables can now be accessed by all other scripting elements on the
page, including those that appear before the declaration.
Note that if a variable is modified by a scripting element on the page, all
subsequent references to that variable will use the new value. To declare a
variable whose value is local to a single request, you should use a scriptlet.
Class variables, or static variables, are variables whose values are shared
among all instances of a class. By using the static keyword (in Java), if one
instance changes the value of this variable, all instances see the new value.
For example:
When the JSP is compiled into a servlet class, the methods of the JSP
become methods of the servlet. These methods can thus be accessed by all
scripting elements on the page.
A single declaration tag may include many method declarations and many
variable declarations.
<html>
<body>
</body>
</html>
Example 21 – MyPoints.jsp
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 49 of 309
An important use for method declarations is the handling of events related
to the initialisation (jspInit() method) and destruction (jspDestroy()
method) of JSP pages.
These methods are optional and declared as follows:
4.4.3.2 Expressions
An expression is an individual line of code. When it is evaluated, the result
automatically replaces the original expression tag in the page output. The
syntax is as follows:
Or:
JSP expressions can be used to print out individual variables, the result of a
calculation or the result of a value returned by a method.
Expressions can return a value of any type – Java primitive values or Java
objects.
All expression results are converted to a character string before they are
added to the page’s output.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 50 of 309
4.4.3.3 Scriptlets
Scriptlets are blocks of code that are executed each time the JSP page is
processed for a request. Unlike declarations and expressions, scriptlets are not
limited to the type of scripting and may contain expressions, declarations and
JavaBeans. They contain only valid Java code which may or may not produce
output. The syntax is:
Or:
<html>
<body>
<%@ page import= "java.awt.Point" %> <!-- page directive used
import Point class -->
<%!
pt1 = new Point(1,2); /* Variable declarations */
pt2 = new Point(2,3);
pt3 = new Point(3,4);
int sX;
int sY;
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 51 of 309
out.println("<H3>The sum of x values is " + sumY() +
"</H3>");
out.println("The x values are " + pt1.x + " " + pt2.x + " "
+ pt3.x);
out.println("The y values are " + pt1.y + " " + pt2.y + " "
+ pt3.y);
%>
</body>
</html>
Example 23 – MyPoints.jsp
Note that you can achieve the same output by using a scriptlet as you can by
using HTML tags and an expression. Any variable introduced in a scriptlet will
be available for use in subsequent scriptlets and expressions on the same
page. Remember that a block of code can be used to control scope. The
following example will give you an idea of how scope works in JSP. In this
example we leave code blocks open across multiple scriptlets:
<html>
<body>
<%
{ // open java bracket
String names[] = {"Leila", "Joe", "Rowan", "Barbara", "Chris",
"Tom"};
out.println("<UL>");
for(int i = 0; i < names.length; i++){
%>
<li> <%= names[i] %> </li> <!-- normal html with an
expression -->
<%
}
out.println("</li><br/>"); //uses scriptlet code for these
html tags
out.println("The second person in the list is " + names[1]);
</body>
</html>
Example 24 – MyScope.jsp
Save this file as MyScope.jsp. Package, deploy and run the file.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 52 of 309
In this example, names is declared inside the Java brackets and can therefore
only be accessed within them. If you uncomment the last out.println
statement, an error will occur stating that it cannot find a variable called
names; hence it is out of scope.
The use of this technique of opening statement blocks without closing them
can be extremely advantageous when you want to implement conditional or
iterative content, or to add error handling.
<html>
<body>
<!-- imports the necessary class using the page directive -->
<%@ page import="java.util.Random"%>
<% //scriptlet
Random r1 = new Random();
x = r1.nextInt(15); /*generate a random numbers from 0 to
15 */
if (x < 5) {
%>
<P> x, <% out.println(x); %>, is smaller than 5 </P>
<!-- normal html code -->
<% } else {
%>
<P> x, <% out.println(x); %>, is greater than 10 </P>
<% }
%>
</body>
</html>
Example 25 – MyRandom.jsp
This scriptlet consists of three blocks, only one of which will be executed. The
first block will be executed if x is less than five, the second if x is between 5
and 10, the last if x is greater than 10. Therefore, only the relevant html code
will be displayed.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 53 of 309
to incorporate the standard Java exception-handling mechanisms into a JSP
page.
The following example shows how to deal with exceptions in your code:
<html>
<body>
</body>
</html>
Example 26 – MyFloatException.jsp
4.4.4 Comments
There are three different ways to insert comments into a JSP page, depending
on where you are inserting the comment and whether you wish to be able to
view the comment as part of the source code. They are listed below:
You should recognise this as the HTML and XML comment syntax. Comments
of this style are transmitted back to the browser as part of the JSP response
but do not produce any visible output. However, the end user may view them
as part of the source code. It is interesting to note that since these comments
are part of the output from the page, you can include dynamic content, such
as JSP expressions. For example:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 54 of 309
<<!-- The square root of 16 is <%= Math.sqrt(16) %> -->
Viewing the source code from a Web browser, this comment will appear as
follows:
The other two types of comments are visible only through the original JSP file:
JSP comments
Scripting language comments
The JSP container will ignore the body of this comment. You may find this type
of comment useful when commenting out portions of your JSP page –
particularly if the portion you wish to comment out contains JSP expressions
which may not compile.
This can, however, lead to problems because some compilers will comment out
relevant content. For example:
<%= Math.sqrt(16)//get the square root %>is the square root of 16.
In this case, some compilers may comment out is the square root of 16.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 55 of 309
4.4.6 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
Scripting-oriented tags
XML-based tags
Directives
page directive
include directive
taglib directive
Scripting
Declarations
Actions
Expressions
Scriptlets
Comments
4.4.7 Exercises
1. Create an HTML file which uses a form to get a number from the user.
2. Write a JSP which creates a table. Use a for loop to create each row. The
first column in the table holds numbers from 1 to 10, the second column
displays a list of shopping items, and the third column displays the price of
the items. All the values must be stored in separate arrays respectively.
The last row of the table must display the total price of all the items.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 56 of 309
4.4.8 Revision questions
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 57 of 309
4.5 Implicit objects, actions and scope
The following four implicit objects have the ability to store and retrieve
attribute values:
These objects are also referred to as scopes because the lifespan of the
attribute value will depend on the implicit object in which it was stored.
The methods that you will most often use to manage these attributes are:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 58 of 309
Page object
Servlet-related
Config object
Error handling Exception object
The following are the nine implicit objects explained in more detail:
You have already seen the request object’s getParameter() method in some
of the previous examples. The next example will use some of the request
object’s other methods as well:
<html>
<head>
<title>Using Request Object</title>
</head>
<body >
<!-- gets the num value that is appended to the URL -->
Request Parameter: <%=request.getParameter("num") %> <br/>
</body>
</html>
Example 27 – RequestObject.jsp
Remember to include the num parameter on the URL (?num=16) when accessing
this page in your Web browser. Also remember to copy the ErrorPage.jsp file
to your directory or reference it with the name of the package in which it is
contained.
The request object is also used to retrieve HTTP header information. The
getHeader() method takes a String header name as an argument, and returns
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 59 of 309
details about the header as a String. The getHeaderNames() method returns
an enumeration of all the header names the request object contains. Take note
that some servlet containers do not allow access to the header names. In
these cases, the method will return a null value.
The response object can temporarily redirect the user to another page with the
sendRedirect() method. You will also see the response object in use when
we set up cookies.
Type the following example which uses the response object to send you to
another page when the parameter is no:
<html>
<body bgcolor="aqua">
<%
/* gets answer parameter */
String answer = request.getParameter("answer");
if(answer.equals("no")){ // answer = no
/* send the user to the colourinput page */
response.sendRedirect("ColourInput.html");
} else {
/* print out the answer on this page */
out.println("<B>The answer you entered was "+ answer+
"</B>");
}
%>
</body>
</html>
Example 28 – ResponseObject.jsp
Remember to include the answer parameter on the URL. First try ?answer=yes
and then try ?answer=no.
You will see that when the answer is no, you are redirected to another page.
The ColourInput.html page was the page to which you were redirected. Note
that we will create the ColourInput.html in the following sections.
The response object can also be used to set HTTP-specific header information
with the setHeader() method which can be retrieved by the request object.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 60 of 309
specific behaviour. They are primarily used for controlling the output buffer
and managing its relationship with the output stream that will send content
back to the browser.
<html>
<head><title>Out objects and buffering </title>
</head>
<body BGCOLOR="lightblue">
<HR>
<%
out.println("<P>Using <B>out object</B> to write
<I>html</I></P>");
%>
<HR>
</body>
</html>
Example 29 – UseOutObject.jsp
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 61 of 309
4.5.1.2 Contextual objects
In order to see how a session works and how we can access attributes within a
session from a JSP page, type the following example (remember to copy the
ErrorPage.jsp file to your directory):
<html>
<body>
<%
session.setMaxInactiveInterval(60);
out.println("<B>Max InActive Interval: " +
session.getMaxInactiveInterval() + "
seconds</B><br>");
if(session.getAttribute("MyColour") != null){
out.println("The sessions color attribute has been set to
<I>" +
session.getAttribute("MyColour") + "</I>");
} else {
out.println("Refresh the page to view session's colour " +
"attribute");
String colourValue = request.getParameter("ColourValue");
session.setAttribute("MyColour", colourValue);
}
%>
</body>
</html>
Example 30 – ColourSession.jsp
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 62 of 309
Save this file as ColourSession.jsp. The next piece of code will be a form that
accepts a colour value and sends it to ColourSession.jsp
<html>
<body>
<H4>Favourite Colour</H4>
<form ACTION="ColourSession.jsp">
</form>
</body>
</html>
Example 31 – ColourInput.html
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 63 of 309
4.5.1.3.2 Configuration object
The configuration object stores servlet configuration data for the servlet into
which the page is compiled. It stores the initialisation parameters of the page.
This object is seldom used.
4.5.2 Actions
We have already examined three of the four main types of JSP constructs –
directives, comments and scripting elements. The fourth type of tag is actions.
Actions have three main purposes:
In this section you will look at the three actions used to interact with server-
side JavaBeans. They are <jsp:setProperty>, <jsp:getProperty> and
<jsp:useBean>. The other four actions are <jsp:include>, <jsp:forward>,
<jsp:param> and <jsp:plug-in>.
4.5.2.1 <jsp:include>
This action enables the incorporation of content generated by another
document on the same server into the current page’s output. Control is
temporarily transferred from the current JSP page to the location of the other
page on the local server. The output is inserted into the original page’s output
in place of the <jsp:include> tag. The syntax is as follows:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 64 of 309
original page. When transferring information from the original page to the
included page, the data should be stored as an attribute of either the
request or session object.
The major difference between the <jsp:include> action and the include
directive discussed in section 4.5 is that, using the <jsp:include> action,
the changes are reflected in the output of the including page automatically.
You will remember from section 4.5 that the include directive does not
automatically update the including page when the included page is
modified. However, the include directive does offer slightly better run-
time efficiency.
The included page can be a static document, a CGI program, a servlet or
another JSP page.
4.5.2.2 <jsp:forward>
This action tag forwards a request from a JSP page to another location on the
local server. The processing of the request begins again at the new location.
The syntax looks like this:
4.5.2.3 <jsp:param>
This action allows you to specify additional request parameters for the included
document for both the <jsp:forward> and the <jsp:include> actions. It is
used within the body of the action being used. There is no limit to the number
of request parameters that may be specified in this way. The syntax looks like
this:
4.5.2.4 <jsp:plugin>
This action is used to include a plug-in for Java applets. This tag generates
browser-specific html for downloading the plug-in. This Java plug-in is only
available with Java version 1.3 and later.
4.5.3 Scope
The use of scope in the ColourSession.jsp example was seen in Example 30
when using the getAttribute() and setAttribute() methods. Similar coding
can be used to control the scope using the pageContext, request or
application objects. This coding is useful when you want to control the scope
from within scriptlets or servlets, or wish to transfer data to a forwarded or
included page.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 65 of 309
The following table shows the lifespan of the different scopes:
4.5.4 Cookies
4.5.4.1 Introduction
The use of the session implicit object, which represents the user’s interaction
with the Web server, has been discussed in section 4.5.1.2.2. This object is
used by any JSP page that participates in session management. The idea of
session management stems from the attempt to maintain the same state
across multiple HTTP requests, in that all of a user’s requests from a Web
server during a given period of time are part of the same interactive session.
JSP includes built-in support for session management by taking advantage of
the capabilities provided by the Java servlet API. Servlets can use either
cookies or URL rewriting to implement session management but the details of
session management are hidden at the JSP level.
Although cookies are not strictly a JSP technology, they are very useful and
can be implemented through JSPs.
The following will explain and show you how to implement cookies in JSP:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 66 of 309
4.5.4.2 Creating a cookie
The first step in using cookies is to create an instance of the cookie class. The
two-argument constructor of the cookie class is used. For example:
The first argument is the name of the cookie and the second argument is the
value you assign to the cookie. It is important to note that while the value of a
cookie can be changed after creation, its name cannot. Because the HTTP
protocol imposes certain restrictions on the characters that may be sent by a
cookie, you need to use the java.net.URLEncoder.encode() method which
converts the string to an application specific URL-encoded format. For
example:
The next step is to tell the cookie where it is valid. This is done using the
setDomain() method. If we take the earlier aCookie example, we would set its
domain as:
aCookie.setDomain("www.pihe.ac.za");
The cookie’s domain name must have at least two periods. This is to ensure
that a cookie is not accessible by an entire domain, e.g. .com. When creating
cookies for this unit, you should set the domain name to your IP address (you
can also use localhost or 127.0.0.1). For example:
aCookie.setDomain("192.168.1.86");
The next important step is to tell the cookie for how long (in seconds) it is
valid. A cookie will last only as long as its validity period. To set a cookie for a
week (7 days * 24 hours * 60 minutes * 60 seconds) use the following:
aCookie.setMaxAge(7*24*60*60);
You also need to tell the cookie which version it is. To ensure maximum
browser compatibility, it is best to set it to version 0 as follows:
aCookie.setVersion(0);
A cookie can be sent either securely or openly. If you set the cookie to be sent
securely, you will need to have a secure connection. Data encryption is beyond
the scope of this unit so we will only be using a non-secure connection, and
this should be set as:
aCookie.setSecure(false);
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 67 of 309
4.5.4.3 Sending the cookie to a browser
Sending your cookie to the client’s browser is as simple as adding it to the
response object as follows:
response.addCookie(aCookie);
The cookie is sent automatically. You do not have to worry about what
happens once it reaches the client’s browser because the browser will store it
automatically.
<html>
<head>
<title>Add Cookie</title>
</head>
<body>
<%
String cookieName = "myCookie";
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 68 of 309
</body>
</html>
Example 32 – SetCookie.jsp
The next JSP checks to see if the cookie set in SetCookie.jsp is included in
the header sent to it by the client. In order to get any cookies sent to it, it
uses the getCookies() method of the request object. This method returns an
array of cookies which must be searched to see if the specific cookie is
present. If the cookie is not present, the user is prompted to enter his or her
name, which is forwarded to SetCookie.jsp:
<%
String cookieName = "myCookie";
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 69 of 309
<!-- give user option to delete cookie -->
<form action="DeleteCookie.jsp">
<input type="Submit" value="Remove Cookie">
</form>
<% } %>
</body>
</html>
Example 33 – MyCookie.jsp
The final example in this unit demonstrates how to delete a cookie. Once the
server recognises the cookie in MyCookie.jsp, the user is presented with a
welcome message and the option to delete the cookie.
It is actually not possible to delete cookies over the Internet (do you want
someone to be able to delete files from your computer?), so we use another
technique. You simply set the maxAge property of the cookie to 0 (implying that
it will expire immediately) and add it to the response object again:
<html>
<head>
<title>Delete Cookie</title>
</head>
<body>
<%
String cookieName = "myCookie";
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 70 of 309
}
}
%>
</body>
</html>
Example 34 – DeleteCookie.jsp
Access the MyCookie.jsp page from your browser. Enter your name and
submit it. If you return to MyCookie.jsp you will be greeted with the option to
delete the cookie. If you delete the cookie and return to MyCookie.jsp, you
will be prompted to enter your name again.
In practical terms, you have not yet done anything that a session bean could
not do. If, however, you submit your name to SetCookie.jsp and then stop
and restart the server, it will still remember you. Your session has just been
extended to cover multiple sessions!
If you are using Google Chrome or Edge in Windows 10, a cookie folder will be
created with a file that contains the name of the cookie under your profile on
the C: drive. Its exact location can be determined by searching for the cookie
folder.
4.5.4.7 Summary
Cookies can be very useful when building JSPs. You should, however, be
mindful of the security implications and the restrictions imposed on cookies.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 71 of 309
4.5.5 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
Implicit object
Request object
Response object
Out object
Page context
Session
Application
Page
Configuration
Exception
Actions
Scope
Cookies
4.5.6 Exercises
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 72 of 309
4.6 JavaBeans and JDBC
It is difficult for the designer and developer to work on the same page at
the same time.
If you need 10 pages with the same functionality, you need to write the
same script 10 times. If, at a later stage, the script needs to be changed,
you need to change it on 10 pages.
Clearly, scripting as a tool does not completely comply with the object-oriented
model. We need code which is reusable, independent of the JSP and easy to
use. This is why JavaBeans are so advantageous.
You have already used JavaBeans in the course thus far. The JButton is a
good example of a JavaBean because it adds useful functionality to your
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 73 of 309
programs. You can click on a JButton as a form of input, but you do not know
the details of what is happening inside the JButton except that it has various
properties which you can set or get using accessor methods. For example:
package unit4;
import java.util.*;
import java.text.*;
/* Beans are always public, the class as well as the get and set
methods */
public class TimeBean implements java.io.Serializable {
// No argument constructor
public TimeBean() {
// This is standard Java, nothing new here
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = new Date();
timeString = sdf.format(date);
}
All JavaBeans must be compiled before they can be accessed. The applications
will be packaged and deployed to the server in the usual manner.
After you have compiled the JavaBean, the next step is to access it from a JSP.
In order to do this, you need a bean property sheet. Look at the following
example of a bean property sheet:
A bean property sheet lists all the accessible properties of a bean. For each
property, the following is listed:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 74 of 309
The name of the property.
The access that users have to the property, which can be one of the
following: read-only, write-only or read/write.
The Java type of the property (e.g. String, int, char).
An example of a valid value.
The access of a bean depends on its get and set properties. The access modes
are as follows:
getProperty() – read-only
setProperty() – write-only
getProperty() and setProperty() – read/write
NOTE You will be expected to be able to write property sheets for all the
beans that you make.
In order to use the above bean, you must incorporate the three actions that
apply to beans:
<jsp:useBean ....../>
<jsp:setProperty ....../>
<jsp:getProperty ....../>
Before the bean can be used, it must be instantiated. To do this, you would
use the following tag:
This tag creates an instance of TimeBean named time for use on the JSP. The
id attribute sets the name by which the object will be known, and the class
attribute sets the type of object (note the full package name). During creation,
the constructor method is called and thus timeString is set to the current
time when the object is created.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 75 of 309
being created. Any configuration commands within the <jsp:useBean> tag will
be ignored.
The default scope is page and does not need to be specified. The other scope
types will be discussed later.
To get the value of timeString onto a JSP page, the following tag must be
used:
name is the name of the object you wish to access. The name attribute must
correspond with the id attribute in the useBean tag. property is the specific
property you wish to access inside the object.
NOTE You will find the property name on the property sheet.
Alternatively, if you have imported the class and instantiated it you can call the
getTimeString() method of TimeBean. For example:
Regardless of data type, all properties are cast to strings before being sent to
the page. This casting takes place in the JRE and does not affect you as a bean
programmer or JSP designer.
The following example accesses the time bean from a JSP page:
<html>
<head>
<title>TimeBean</title>
</head>
<!-- This is the JSP tag which instantiates the Bean, note the
full package name-->
<jsp:useBean id="time" class="unit4.TimeBean"/>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 76 of 309
<!-- This is the JSP tag which gets the time from the Bean-->
<B> <jsp:getProperty name="time" property="timeString"/> </B>
</body>
</html>
Example 36 – Time.jsp
Save this file as Time.jsp. Make sure that TimeBean.java is compiled into
the right directory, namely …/ROOT/WEB-INF/classes/unit4. Package and
deploy the example and then run Time.jsp. You should see the current time
displayed on screen.
Figure 12 – Time.jsp
package unit4;
import java.util.*;
import java.text.*;
// No argument constructor
public TimeBean2() {
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 77 of 309
// Introspection will reveal these methods to the jsp
public String getTimeString () {
return timeString;
}
In order to set the name variable you must use the following tag:
name is the name of the object that you wish to access. The name attribute
must correspond with the id attribute in the useBean tag. property is the
specific property you wish to access inside the object. You will find the
property name on the property sheet. The JRE uses introspection to identify
which set() method of the bean to use. Value is the value, as a String, that
you want to assign to the property.
Alternatively, if you have imported the class and instantiated it, you can call
the setTime() method of TimeBean2. For example:
Hard-coding values into the JSP may not always be the best approach. You
could also pass the bean a parameter obtained by the page. For example, if
the parameter username was sent to the JSP, you could use the following tag:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 78 of 309
<html>
<head>
<title>TimeBean</title>
</head>
<!-- This is the JSP tag which instantiates the Bean, note the
full package name-->
<jsp:useBean id="time" class="unit4.TimeBean2"/>
<br/><br/>
<!--This JSP tag sends the parameter from the JSP to the Bean-->
</body>
</html>
Example 38 – TimeName.jsp
When you access this page from the browser remember to add
?username=Sheunesu to the end of the URL that you type in order to send
the parameter. The URL will now be similar to:
http://localhost:3128/myb/TimeName.jsp?username=Sheunesu.
Figure 13 – TimeName.jsp
You will notice in the above example that the name is set after the object is
created. If you wish to set properties during the creation of the object, you
should use the <jsp:useBean> tag in a slightly different way and send the
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 79 of 309
parameters in its body. This method is usually used for initialising values. For
example:
<html>
<head>
<title>TimeBean</title>
</head>
time.setName(request.getParameter("username"));
%>
The TimeBeanScript JSP can now also be accessed through your browser. You
will notice that instantiating and using the bean in scriptlets is almost exactly
the same as instantiating and using a class in pure Java. In fact, this is exactly
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 80 of 309
what you are doing. The request.getParameter() call is to an implicit object
that returns a page parameter.
Figure 14 – TimeBeanScript.jsp
<html>
<head><title>Holiday Program</title></head>
<body style="background-color:cyan">
<center>
<table style="background-color:lightblue”>
<tr>
<td>First Name<input type="text" name="clientFirstName"></td>
<td>Surname<input type="text" name="clientSurname"></td>
</tr>
<tr>
<td>Location :<br/>
<input type="radio" name="location" value="ocean"
checked=”true”>Ocean<br/>
<input type="radio" name="location" value="lake">Lake<br/>
<input type="radio" name="location" value="nature">
Nature Reserve<br/>
<input type="radio" name="location" value="casino">Casino<br/>
</td>
<td>Accommodation Type :<br/>
<input type="checkbox" name="hotel" value="1">Hotel<br/>
<input type="checkbox" name="camping"
value="1">Camping<br/>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 81 of 309
<input type="checkbox" name="caravan"
value="1">Caravan<br/>
<input type="checkbox" name="bungalow" value="1">Bungalow
</td>
</tr>
<tr>
<td colspan="2">
<center>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</center>
</td>
</tr>
</table>
</center>
</form>
</body>
</html>
Example 40 – InputForm.html
package unit4;
import java.io.Serializable;
// No argument constructor
public HolidayBean() {}
firstName = tempName;
surname = tempSurname;
location = tempLocation;
hotel = tempHotel;
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 82 of 309
camping = tempCamping;
caravan = tempCaravan;
bungalow = tempBungalow;
}
if (location.equals("ocean"))
loc = "Umhlanga Beach ";
else if(location.equals("lake"))
loc = "Vaal lake ";
else if(location.equals("nature"))
loc = "Kruger Park Nature Reserve";
else if(location.equals("casino"))
loc = "SunCity Casino ";
if (hotel == 1)
tempString.append(loc + " Hotel<br/>");
if (camping == 1)
tempString.append(loc + " Camping Grounds<br/>");
if (caravan == 1)
tempString.append(loc + " Caravan Park<br/>");
if (bungalow == 1)
tempString.append(loc + " Self Catering
Bungalows<br/>");
return tempString.toString();
}
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 83 of 309
this.hotel = temp;
}
The parameters used by this bean are set by the JSP page which retrieves the
values from the InputForm.html when the user presses Submit. The JSP
page follows:
<html>
<head>
<title>Holiday Choice</title>
</head>
<center>
<!-- Instantiate Bean and set properties from inside useBean tag
pair -->
<jsp:useBean id='holiday' class='unit4.HolidayBean'>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 84 of 309
<jsp:setProperty name='holiday' property='hotel' param='hotel'/>
<jsp:setProperty name='holiday' property='camping'
param='camping'/>
<jsp:setProperty name='holiday' property='caravan'
param='caravan'/>
<jsp:setProperty name='holiday' property='bungalow'
param='bungalow'/>
</jsp:useBean>
</center>
</body>
</html>
Example 42 – HolidayChoice.jsp
Notice that the parameters are sent to the bean from inside the <jsp:useBean
... > </jsp:useBean> tag pair, indicating that the parameters are being set
during the creation of the object.
Make sure that the files are saved in the correct place and that
HolidayBean.java is compiled. Open your Web browser and access
InputForm.html. When you click the Submit button, your holiday
destinations should come up.
Figure 15 – InputForm.html
When you enter values and click on Submit, the result will look like this:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 85 of 309
Figure 16 – HolidayChoice.jsp
To use scriptlets instead of JavaBean action tags, the setProperty tags inside
the useBean tag pair will be replaced by a constructor. The scriptlet code will
look like this:
<html>
<head>
<title>Holiday Choices</title>
</head>
<body style="background-color:cyan">
<%
/* These parameters could possibly be null, therefore when
scripting
you must check for this and assign values if necessary to avoid
errors */
String hotel =
(request.getParameter("hotel") == null)? "0":
request.getParameter("hotel");
String camping =
(request.getParameter("camping") == null)? "0":
request.getParameter("camping");
String caravan =
(request.getParameter("caravan") == null)? "0":
request.getParameter("caravan");
String bungalow =
(request.getParameter("bungalow")==null)? "0":
request.getParameter("bangalow");
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 86 of 309
HolidayBean holidayBean = new HolidayBean(
request.getParameter("clientFirstName"),
request.getParameter("clientSurname"),
request.getParameter("location"),
Integer.parseInt(hotel), // These values must be parsed
to int
Integer.parseInt(camping),
Integer.parseInt(caravan),
Integer.parseInt(bungalow));
</body>
</html>
Example 43 – HolidayChoiceScript.jsp
When using beans through scripting, it is important to remember that the JSP
container does not take care of null values and parsing for you. You have to
check all parameters that could possibly be null, and explicitly cast the string
used by the parameter to the data type used by the Bean’s set() method.
In this unit you have learnt what a JavaBean is and how to create one. You
have also learnt how to embed a bean into a JSP using tags and scriptlets. You
should now be able to create a bean and set and retrieve its properties from
within a JSP.
4.6.3.1 Page
This is the default scope value. Each time the page is requested an instance
of the bean is created. This bean will not be accessible from outside the
page.
If you reference another page using the <jsp:include> or the
<jsp:forward> tags, this bean will not be available.
Specifying a new bean with the same id in a forwarded or included page will
result in a new instance of the bean being created. A bean with page scope
is stored in the pageContext object.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 87 of 309
4.6.3.2 Request
If a bean has request scope, the container will attempt to retrieve the bean
from the request itself.
The beans are stored in the request as request attributes.
Request-level scope allows you to access the bean from pages referenced
with the <jsp:include> or <jsp:forward> tags. This can be useful if you
wish to include several smaller component pages to build a large, complex
page.
4.6.3.3 Session
The JSP container maintains a unique session object for each user visiting
the site.
If a bean has session scope it is stored in the session object with the value
of the id attribute as its identifier.
Calling a bean with the <jsp:useBean> tag will refer to the existing instance
of the bean, rather than create a new one.
Sessions are useful if you wish to store information collected through a
user’s visit to the site, or cache information that is frequently needed at
page level.
The JSP container determines the length of time that a session bean exists.
4.6.3.4 Application
A JSP application is a collection of JSP pages, HTML pages, images and
other resources that are bundled together under a particular URL hierarchy.
Application beans exist throughout the life of the JSP container and are
reclaimed only when the server is shut down.
These beans are also shared by all users of the application with which they
are associated and can be used by pages throughout the site.
Only one instance of the bean is created per server – therefore, any
changes made to the properties of the bean will affect all of the JSP pages
that reference the bean.
To use the session scope attribute in JSP beans you would use the following:
<%
MyBean mybean = new MyBean();
session.setAttribute("SessionName", mybean);
%>
Example 44 – Using the session attribute
You need to set a session attribute with an instance of the bean. The
SessionName can have any value.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 88 of 309
Using the above scriptlet, the object SessionName can now be used on more
than one page during the session. You could safely use the object
SessionName on another page to access one of its properties, for example:
It may, however, be easier to just use the <jsp:useBean> tag on every page
that may access the bean. If a bean exists that has the same id and is in
scope, the JSP container will use this instance of the bean and not create a
new instance.
Note that the above example illustrates the use of the session implicit object
when using a bean with session scope. When using page, request or
application scope, you could use a similar syntax when referencing the
pageContext, request and application implicit objects respectively.
4.6.4 JDBC
The following diagram displays how a JSP accesses a database using a JDBC
driver:
JSP page
JDBC Driver
Request
Database
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;datab
aseName=Bakery;user=admin;password=1234;");
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 89 of 309
4.6.4.3 Setting up your database
The examples in this unit work towards building an online bakery. Firstly, you
will create the database Bakery with one table called products. You must use
Microsoft SQL Server to create your database.
Name your database Bakery and the table products. Set up the Microsoft
JDBC Driver for SQL Server the same way you did in Unit 3. Make sure you
add the required jar files in order to use the driver.
Make id a primary key by right-clicking in the margin next to the id field and
selecting Primary Key.
You can now save the database and close the database program.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 90 of 309
NOTE For your practicals and exams, you will be provided with an SQL
database file. You need to attach this database to SQL Server first
before you can access it in NetBeans. To do so, open Microsoft SQL
Server Management Studio and connect to your server. Right-click
on the Databases node and click “Attach”. Navigate to where your
database is located and attach it. If you have administrative rights,
you can copy and paste the database file under C:\Program
Files\Microsoft SQL
Server\MSSQL13.MSSQLSERVER\MSSQL\DATA, then afterwards
attach it using the same procedure explained above.
4.6.4.4 ConnectionBean
The given examples will use a class called ConnectionBean to create and store
a connection to the database. The reason for using this approach is that the
bean will have session scope and thus the connection will remain open and will
not have to be reopened each time the database is accessed. Reusing the bean
also cuts down on coding, ensuring the JSPs are uncluttered.
package unit4;
import java.io.*;
import java.sql.*;
public ConnectionBean() {
makeConnection();
}
/* Set up connection */
public void setCloseConnection(boolean close){
if (close) {
try {
connection.close();
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 91 of 309
} catch(Exception e) {
connection = null;
}
}
}
You will need to set up the SQL Server username and password for you to use
when connecting to the database. Make sure the password meets the minimum
password complexity requirements required by SQL Server.
Enter the following into your text editor and save it as usual:
<html>
<head>
<title>SQL Query Form</title>
</head>
<body style="background-color:teal">
<center>
<h1>Query Screen</h1>
</center>
<center>
<!-- Basic form used to retrieve a SQL select
statement and submit it to an action page -->
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 92 of 309
<form action="QueryResult.jsp">
<font color="white">Enter search query:</font>
<input type="text" name="sql">
<input type="submit" value="Search">
</form>
</center>
</body>
</html>
Example 46 – SimpleExample.html
The above page sends a parameter (the SQL query) to another JSP that will
perform the query.
The listing below contains the JSP that queries the database. Note that the
ConnectionBean class is instantiated with scope="session". This connection
will remain valid throughout the session. Enter it in a text editor and save it as
usual.
<!-- Import the java.sql package for database tools needed in this
page -->
<%@ page import="java.sql.*" %>
<html>
<head>
<title>SQL Results Table</title>
</head>
<body style="background-color:teal">
<center>
<h1>Results of query</h1>
</center>
<%
/* Get the sql query typed in the textbox on the previous
page */
String sql = request.getParameter("sql");
Statement statement;
ResultSet result;
try {
/* Create an SQL statement by accessing the
ConnectionBeans
getConnection() method to retrieve a Connection and
then
call the relevant createStatement() method */
statement =
connection.getConnection().createStatement();
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 93 of 309
/* Uses the sql statement entered in the text box to
execute
the query */
result = statement.executeQuery(sql);
%>
<center>
<table border="1" style="background-color:white">
<tr>
<td><b>ID</b></td>
<td><b>Description</b></td>
<td><b>Price</b></td>
</tr>
<%
/* iterate through search results and display results
in tabular format */
while (result.next()) {
out.println("<tr>");
out.println("<td>" + result.getInt("id") +
"</td>");
out.println("<td>" +
result.getString("description") +
"</td>");
out.println("<td>" + result.getFloat("price") +
"</td>");
out.println("</tr>");
}
%>
</table>
</center>
<%
} catch (SQLException sqle) {
/* print an error if a bad SQL statement is sent */
out.println("<center>Bad SQL statement</center>");
}
%>
</body>
</html>
Example 47 – QueryResult.jsp
Open your browser and start with SimpleExample.html. This will present you
with an input box in which you can enter standard SQL SELECT statements.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 94 of 309
Figure 18 – SimpleExample.html
The following is what should be displayed when you enter SELECT * FROM
products:
Figure 19 – QueryResult.jsp
The following are some examples that you can type into the input box:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 95 of 309
4.6.5 Key terms
Make sure that you understand the following key terms before you
start with the exercises:
JavaBeans
GET
SET
Serialisation
Properties
Accessors
JDBC
4.6.6 Exercises
4. Create a JSP that will use the Bakery database. The user should be able to
enter just the name of the product they are trying to find. The parameters
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 96 of 309
of the HTML form must be sent to the JSP, which must, in turn, search the
database for a match (hint: Search the description column of the Products
table). Ensure that the user can type in a partial item description, such as
Loaf, which returns all items with “loaf” in the description.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 97 of 309
4.7 Custom tag libraries
<jsp:useBean>
<jsp:getProperty>
<jsp:setProperty>
The functionality of these tags is limited, but if the needs of your application
cannot be met using the standard JSP bean tags, you are not forced to use
scripting elements, like scriptlets or expressions. If there is enough
development time available, JSP provides a way of extending tags, allowing
developers to create libraries of application-specific or custom tags that can be
loaded into a JSP page as easily as standard JSP tags. Custom tags can
provide new actions designed to add functionality to JSP pages. Note that it is
only practical to develop custom tag libraries when those tags will be used
repeatedly and when there is enough development time available.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 98 of 309
Provide a means of extending the JSP language to support programming
constructs like conditionals and loops, as well as additional functionality
such as direct access to databases.
Are typically used for controlling presentation and translating between bean
properties and methods, and the page markup language.
A set of Java classes implementing the custom actions of the tag library.
A Tag Library Descriptor (TLD) file that provides mapping between the
library’s tags and the implementation classes.
1. Firstly, define a Java class or tag handler that tells the system what to do
when it encounters the tag.
2. Secondly, identify the class to the server and associate it with a particular
XML tag name using a TLD file in XML format.
3. Thirdly, write a JSP file that makes use of the tag using the taglib directive
to locate and load your custom tag library.
An empty tag does not contain any body and is written as follows:
<mt:mytag/>
Although you will not be using the server’s web.xml file, the structure of a
web.xml body is given for your interest and for purposes of comparison:
<web-app>
<taglib>
<taglib-uri>
MyTags
</taglib-uri>
<taglib-location>
/WEB-INF/tlds/MyTags1.tld
</taglib-location>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 99 of 309
</taglib>
</web-app>
Example 48 – web.xml structure
Type the following code for your first tag handler into a text editor and save it
as FirstTag.java in your …/myb/source/unit4 directory. Then compile it to
your …/myb/WEB-INF/classes/unit4/mt directory.
package unit4.mt;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
4.7.5.2 Step 2 – Identify the Java class for the server using a TLD
This Tag Library Descriptor (TLD) file contains a short name for your library, a
short description and a series of tag descriptions. It also contains a <tag>
element which defines the main name of the tag and identifies the class that
handles the tag. The various elements and sub-elements of the TLD file will be
discussed in more detail later. Take note that the <tag> element defines the
main name of the tag (suffix) and identifies the class that handles the tag.
The tag handler class is in the unit4.mt package, so the full class name of
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 100 of 309
unit4.mt.FirstTag is used. Save the following TLD file as MyTags1.tld in the
…/myb/WEB-INF/tlds subdirectory:
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>mt</shortname>
<info>
Mixed Example Tags
for Pearson JSP course
</info>
<tag>
<name>first</name>
<tagclass>unit4.mt.FirstTag</tagclass>
<bodycontent>tagedependent</bodycontent>
</tag>
Example 50 – MyTags1.tld
For this unit we will be using the same TLD file for all custom tags. We will
simply add a <tag> entry for each new tag.
4.7.5.3 Step 3 – Write a JSP file that uses the custom tag
When writing a JSP file that makes use of a custom tag, make sure that you
use the taglib directive somewhere before the first use of your custom tag.
Remember, the tag library directive is used to notify the JSP container that a
page relies on one or more custom tag libraries. Once this tag has linked a
page to a specific custom tag library, all the tags in that library are available
for use on that page. The syntax of the tag library directive is as follows:
Or:
Remember the value of the uri attribute indicates the location of the TLD file
for the library, and the prefix attribute specifies the identifier that will be
added in front of all occurrences of the library’s tags on the page.
To use a tag library whose TLD is accessible through the URL /WEB-
INF/tlds/MyTags1.tld, you would use:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 101 of 309
A tag from this library, called TagName, would be referenced within the page as
<mt:TagName/>. The tag prefix is specified outside the library itself, and on a
page-specific basis. This means several custom tag libraries can be loaded by a
single page without conflict between tag names. Even if two libraries contain
tags with the same name, they are differentiated by their prefixes because
each tag library must be assigned a unique prefix. Save the following JSP as
CustomTag.jsp in your .../myb/jsp/unit4 directory:
<html>
<head>
<%@ taglib uri="/WEB-INF/tlds/MyTags1.tld" prefix="mt" %>
<title><mt:first/></title>
</head>
<body>
<h1>Custom Tag Demonstration</h1>
<hr/>
<p>Notice your custom tag inserts text in the title bar above.</p>
<p>Your custom tag also inserts text between the lines below:</p>
<hr/>
<h1><mt:first /></h1>
<hr/>
<p>Tags that insert text are the simplmybest kind of custom
tags.</p>
<h4><mt:first /></h4>
<p>The above text is the last insertion by your custom tag!</p>
<hr/>
<h1>Custom tags are easy!</h1>
</body>
</html>
Example 51 – CustomTag.jsp
The following screen will be displayed when you run the CustomTag.jsp page:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 102 of 309
Figure 20 – CustomTag.jsp
javax.servlet.jsp.tagext.Tag
javax.servlet.jsp.tagext.BodyTag (an extension of the Tag interface)
JSP makes it easier to develop tag handlers by providing two tag handler base
classes:
TagSupport
BodyTagSupport (a subclass of TagSupport)
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 103 of 309
These tag handler base classes are found in the javax.servlet.jsp.tagext
package. They provide default implementation for all the methods in the
corresponding interfaces, which means all you have to do is redefine those
methods that require custom behaviour in order to implement the desired
action. The tag handler base class you will use depends on the kind of custom
tag being developed.
The tag handler obtains an instance of the appropriate class (either from
the resource pool or by creating one).
The JSP container calls the tag handler’s doStartTag() method. This
method indicates how processing should proceed by returning one of two
values:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 104 of 309
The handler’s doEndTag() method is called (see step 1). This method
indicates how the handler should proceed by returning one of two values,
either Tag.SKIP_PAGE or Tag.EVAL_PAGE:
The final step in the processing of a tag handler is for the JSP container to
call the handler’s release() method. The tag handler performs cleanup
operations before it is sent to the shared resource pool.
obtain
handler
set
properties setPageContext
()
setParent()
set
attributes
EVAL_BODY_INCLUDE
doStartTag
()
process
SKIP_BODY body
SKIP_PAGE
doEndTag() EVAL_PAGE
release() release()
stop continue
The life cycle for tag handlers implementing the BodyTag interface is similar to
the process for implementing the Tag interface, but adds steps for accessing
and manipulating the tag’s body content. The process is exactly the same until
the result of the doStart() method is returned. Note that for tag handlers
implementing the BodyTag interface, the doStartTag() return values are:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 105 of 309
BodyTag.EVAL_BODY_BUFFERED – Indicates that the body content should be
processed and the results stored for further manipulation by the tag
handler.
The results of processing the body content are stored by means of the
BodyContent class. BodyContent is a subclass of JspWriter, an instance of
which is used to represent the output stream for the content generated by a
JSP page. Instead of buffering its output for sending to the browser like the
JspWriter, the BodyContent class stores its output for use by the tag handler,
which then decides whether that output should be discarded or sent to the
browser.
The JSP container then calls the tag handler’s doInitBody() method to
allow the tag handler to perform additional initialisation steps after the
BodyContent instance has been assigned.
The body is then processed. All its output is sent to the BodyContent
instance. The JSP container then calls the tag handler’s doAfterBody()
method. The action performed by this method is typically tag-dependent,
and often includes interactions with the tag’s BodyContent instance. Like
the doStartTag(), this method is expected to return either Tag.SKIP_BODY
or BodyTag.EVAL_BODY_BUFFERED. Repeated processing of the body
continues until the doAfterBody() method returns Tag.SKIP_BODY. Custom
tags that process their body content repeatedly can be implemented in this
way.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 106 of 309
obtain
handler
setPageContext() set
setParent() properties
EVAL_BODY_TAG
set
attributes
initialize setBodyContent()
body setInitBody()
doStartTag( content
)
process
body
SKIP_BODY
EVAL_BODY_TAG
SKIP_BODY
doAfterBody(
)
SKIP_PAGE EVAL_PAGE
doEndTag()
release() release()
stop continue
The first tag handler property set by the JSP container, when applying a tag
handler, is its PageContext object. The methods of the PageContext class
provide access to all the implicit objects available to JSP scripting elements
and to all the standard attribute scopes.
Tag handlers are passed a reference to the local PageContext instance during
initialisation. Therefore, they have access to all these objects and attributes
through that instance.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 107 of 309
The PageContext object is the tag handler’s main access into the workings of
the JSP container. For tag handler classes that extend either TagSupport or
BodyTagSupport, the local PageContext instance will be available through an
instance variable named pageContext. This instance variable is set when the
JSP container calls the handler’s setPageContext() method, which is one of
the first steps in the tag handler’s life cycle.
All tag handler methods are specified as potentially throwing instances of the
JspException class but, by convention, when an error is actually thrown it
takes the form of a JspTagException (which is a subclass of JspException)
instance. This specifically indicates that the error originates in a tag handler.
The first line is standard XML header information which the TLD file must
contain because it is an XML document.
Next we encounter the <taglib> element. This is the main element for a TLD,
and contains several sub-elements. The five <taglib> sub-elements that can
be used to describe your tag library are:
The next important component is the <tag> element. The main <taglib>
element of a TLD is required to specify one or more <tag> elements which
specify the library’s tags. There is a <tag> specification for each custom tag in
the library.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 108 of 309
The <tag> element supports six sub-elements: five for specifying the
properties of the tag and one for specifying the attributes. The five <tag>
property sub-elements are:
<name> – Specifies an identifier for the tag – used with a library prefix in a
JSP call (required).
<tagclass> – Specifies the name of the class that implements the tag
handler (required).
<teiclass> – Specifies the helper class for the tag.
<bodycontent> – Indicates the type of body content.
<info> – Supplies information about a specific tag.
Finally, if a custom tag takes attributes, they are specified using the
<attribute> element, which has three sub-elements:
<required>false</required>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 109 of 309
NOTE When naming the TLD stored in the WEB-INF/tlds subdirectory,
the convention is to use the library name, the current version
number and the .tld extension. For version 1 of a library named
MyTags, the TLD would be named MyTags1.tld.
<taglib>
<tlibversion></tlibversion>
<jspversion></jspversion>
<shortname></shortname>
<info></info>
<uri></uri>
<tag>
<name></name>
<tagclass></tagclass>
<teiclass></teiclass>
<bodycontent></bodycontent>
<attribute>
<name>id</name>
<required>true</required>
<rtexprvalue>false</rtexprvale>
</attribute
<info></info>
</tag>
</taglib>
Example 52 – Elements of a TLD file
NOTE The essential items in Example 52 are in the tag angle brackets.
The only other thing you need to include is the taglib directive. Remember, it
must appear in the JSP before the custom tag is referenced. The taglib
directive loads the custom tag library by referencing the library’s TLD file in its
URI attribute.
When the JSP container compiles a page using a custom tag library, it
determines whether or not it needs to load the corresponding TLD. If it is the
first time the specified library has been requested, the JSP container reads the
TLD from the indicated URI. If the library has been encountered before, the
TLD is not loaded again.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 110 of 309
4.7.7 Examples
A well-designed custom tag library typically contains a set of interrelated tags
that provide integrated functionality, but the example tag library used in this
learning manual is aimed at demonstrating a variety of tags, and therefore
does not group related tags as a well-designed library should. In the examples
that follow, you will use the MyTags library that you have already constructed.
For each new custom tag, simply add the corresponding <tag> entry to the
TLD file and save each tag handler and JSP in the appropriate directory.
package unit4.mt;
import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
try{
JspWriter out = pageContext.getOut();
out.println("<font ");
if (importance == 1){
out.println("color =\"red\" size=\"5\"");
} else if(importance == 2){
out.println("color =\"green\" size=\"4\"");
}else if(importance == 3){
out.println("color =\"black\" size=\"2\"");
}else{
out.println("color =\"gray\" size=\"1\"");
}
out.print(">");
} catch(IOException ioe) {
throw new JspTagException("I/O exception " +
ioe.getMessage());
}
return EVAL_BODY_INCLUDE;
}
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 111 of 309
try {
JspWriter out = pageContext.getOut();
out.print("</font>");
} catch (IOException ioe) {
System.out.println("Error");
}
return (EVAL_PAGE);
}
}
Example 53 – ImportanceTag.java
Tag attributes are presented in the tag handler class as JavaBean properties;
therefore, the ImportanceTag class must define an appropriate instance
variable and method for the importance attribute.
When the JSP container encounters the importanceTag, the value specified for
the importance attribute will be passed to the corresponding ImportanceTag
instance via its setImportance() method.
If the tag handler will be accessed from other classes, it is a good idea to
provide a getAttribute() method in addition to the setAttribute() method.
For example:
For the ImportanceTag class, two of the tag handler life cycle methods must
be implemented: doStartTag() and doEndTag(). The doStartTag() method
opens an HTML <font> tag and defines the colour and size according to the
importance value sent as an attribute. It then returns EVAL_BODY_INCLUDE
which allows for the included body content of the JSP custom tag, namely the
text between the tags. the doEndTag() method then closes the HTML </font>
tag. You will understand this better once we have run the JSP file and viewed
the page source.
If you wanted to reset default values, you could use the release() method
which is used to restore the tag handler instance to its original state before
returning it to the shared resource pool, so that it may be reused during
subsequent JSP requests. For this particular tag, you could reset the value of
the importance instance variables to 0 as follows:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 112 of 309
public void release() {
super.release();
importance = 0;
}
Example 55 – Resetting the default values
<tag>
<name>importanceTag</name>
<tagclass>unit4.mt.ImportanceTag</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>importance</name>
</attribute>
</tag>
Example 56 – Tag element in TLD
Add the above code to the MyTags1.tld file after the last </tag> tag.
JSP elements may appear in the tag’s body. This tag supports an attribute
named importance which will be used to control how the body content is
displayed.
<html>
<head>
<%@ taglib uri=”/WEB-INF/tlds/MyTags1.tld” prefix=”mt” %>
<title>Importance Tag</title>
</head>
<body>
<h1>Daily schedule </h1>
<mt:importanceTag importance=’1’>Sleep</mt:importanceTag><br/>
<mt:importanceTag importance=’3’>Do the washing
</mt:importanceTag><br/>
<mt:importanceTag importance=’2’>Study
</mt:importanceTag><br/>
<mt:importanceTag importance=’3’>Clean the house
</mt:importanceTag><br/>
<mt:importanceTag importance=’1’>Go shopping
</mt:importanceTag><br/>
<mt:importanceTag importance=’3’>Feed pets
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 113 of 309
</mt:importanceTag><br/>
<mt:importanceTag importance=‘2’>Watch TV</mt:importanceTag><br/>
<mt:importanceTag importance=’2’>Cook dinner
</mt:importanceTag><br/>
<br/>
This line will not have any formatting because it is not included
in the body of a tag.
<br/><br/>
In the above JSP, body content is included within the custom tag, using the
following form:
<mt:importanceTag>body</mt:importanceTag>
Compile, package, deploy and run this example. The following should be
displayed in your browser:
Figure 24 – DailySchedule.jsp
When you run this JSP, right-click on the page and select View page source
from the drop-down menu. This will help you to understand how the
ImportanceTag works. The following text file should be displayed:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 114 of 309
<html>
<head>
<title>Importance Tag</title>
</head>
<body>
<h1>Daily schedule </h1>
<font
color ="red" size="5"
>Sleep</font><br/>
<font
color ="black" size="2"
>Do the washing</font><br/>
<font
color ="green" size="4"
>Study</font><br/>
<font
color ="black" size="2"
>Clean the house</font><br/>
<font
color ="red" size="5"
>Go shopping</font><br/>
<font
color ="black" size="2"
>Feed pets</font><br/>
<font
color ="green" size="4"
>Watch TV</font><br/>
<font
color ="green" size="4"
>Cook dinner</font><br/>
<br/>
This line will not have any formatting because it is not included
in the body of a tag.
<br/><br/>
<font
color ="gray" size="1"
>
This line will have the default formatting because the tag has
no attributes.
</font><br/>
</body>
</html>
Example 58 – DailyShedule’s HTML source
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 115 of 309
Modify the previous tag handler’s doStartTag() method as follows:
try{
JspWriter out = pageContext.getOut();
out.println("<font ");
if (importance == 1){
out.println("color =\"red\" size=\"5\"");
} else if(importance == 2){
out.println("color =\"green\" size=\"4\"");
} else if(importance == 3){
out.println("color =\"black\" size=\"2\"");
} else {
out.println("color =\"gray\" size=\"1\"");
}
out.print(">");
} catch(IOException ioe) {
throw new JspTagException("I/O exception " +
ioe.getMessage());
}
http://localhost:3128/Example/jsp/unit4/DailySchedule.jsp.
You will notice that, because the URL does not contain a request parameter,
SKIP_BODY is returned and the body content of the custom tag is not
evaluated. All you will see is the following:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 116 of 309
Figure 25 – DailySchedule.jsp with no parameters
http://localhost:3128/Example/jsp/unit4/DailySchedule.jsp?param=
1.
This example is aimed at showing how the BodyContent of a custom tag can
be manipulated. We will be using a connection to our database created in the
previous unit. The select statement will be the body of the tags, and the
attribute will be the database’s name.
The GetResultsTag is designed to execute the body of the tag which will
specify a select statement. The results will be displayed to the user in a table.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 117 of 309
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>mt</shortname>
<info>
Mixed Example Tags
for Pearson JSP course
</info>
<tag>
<name>getResults</name>
<tagclass>unit4.mt.GetResultsTag</tagclass>
<bodycontent>tagdependent</bodycontent>
<info>
Uses the body to execute a select statement and return the
results.
</info>
</tag>
</taglib>
Example 60 – GetResultsTag.tld
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.sql.*;
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 118 of 309
String bodyString = body.getString();
bodyContent.clearBody();
try{
JspWriter out = pageContext.getOut();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con =
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;datab
aseName=Bakery;user=admin;password=1234;");
st = con.createStatement();
out.println("<tr><th>Description</th><th>Price</th></tr>");
while(rs.next()){
out.println("<tr>");
out.println("<td>"+rs.getString("description")+"</td>");
out.println("<td>" + rs.getFloat("price") +
"</td>");
out.println("</tr>");
}
out.println("</table>");
}catch(Exception e){
System.out.println("Error " + e);
} finally{
/* closes the statement, resultset and the connection
*/
try{
if(rs != null)
rs.close();
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 119 of 309
if(st != null)
st.close();
if(con != null)
con.close();
} catch(SQLException sqle){
System.out.println("Error " + sqle);
}
}
}
}
Example 61 – GetResultsTag.java
The GetResultsTag:
Type, save and compile the code for the GetResultsTag class in the usual
way.
<body style="background-color:silver">
<center>
<mt:getResults>SELECT * FROM products</mt:getResults>
</center>
</body>
</html>
Example 62 ‒ DatabaseResults.jsp
When you run the JSP, you will notice that the body content within the opening
and closing getResults tags is manipulated by the GetResultsTag. The
results are then displayed to the browser by the tag handler. The following
should be displayed:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 120 of 309
Figure 26 – DatabaseResults.jsp
The results that are displayed are the same as the results displayed when you
used the ConnectionBean and the QueryResult.jsp in the previous example.
Both examples perform the same function, and therefore it is up to you
whether your program should use beans, custom tags or, for that matter,
scripting.
while (result.next()) {
out.println("<tr>");
out.println("<td>" + result.getInt("id") + "</td>");
String desc = result.getString("description");
out.println("<td><a href=\"MyNextPage.jsp?description=" +
desc + "\">" + desc + "</a></td>");
out.println("<td>" + result.getFloat("price") + "</td>");
out.println("</tr>");
}
Example 63 – Returning hyperlinks
Create the MyNextPage.jsp which uses the description value added to the
hyperlink:
<html>
<body bgcolor="yellow">
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 121 of 309
<%
String description = request.getParameter("description");
%>
</body>
</html>
Example 64 – MyNextPage.jsp
You will also need to change the TLD so that the body content tag is JSP and
not tagdependent. For example:
<bodycontent>JSP</bodycontent>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 122 of 309
Figure 28 – Retrieving parameters
Having worked through this section, you should see the great potential for
using custom tags to avoid using scripting in JSPs, and therefore separating
the design and development. Although they are laborious to create, they are
quick and easy to use, avoiding repetitive coding. The potential for custom JSP
tags is vast, and only the basic concepts are covered here.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 123 of 309
4.7.8 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
Tag handlers
TLD
taglib directive
tagext package
TagSupport
BodyTagSupport
bodyContent
JspException
4.7.9 Exercises
1. Create a JSP custom tag that takes no attribute and simply changes all text
included in the tag’s body to a red, bold, italics font with a size of 5.
2. Create a JSP custom tag to display the current date to the browser. This
tag must take the format attribute to set the date. The tag must not
include any body content. For example:
<mt:date format=”dd/MM/yyyy”/>
3. Include an extra page in the last example so that the user can enter the
Select statement in an input box. You will need to change the TLD so that
the body content is JSP and not tagdependent.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 124 of 309
4.8 Creating a Web application
JSP files:
BakeryErrorPage.jsp
MainPage.jsp
DeleteFromCart.jsp
Java files:
BakeryTag.java
DatabaseConnectionBean.java
CartBean.java
ProductsBean.java
Other:
TLD entry
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 125 of 309
Figure 29 – Adding a server (1)
In the Add Server Instance window, select Apache Tomcat and click on
Next.
Click Next.
On the next screen, on Server Location, browse to the folder you
extracted the TomCat version you downloaded.
For username and password type “admin” for both.
Click Finish
You will noptice that Apache Tomcat is now listed as one of the servers.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 126 of 309
Figure 31 – Adding a server (3)
If you right-click on Apache Tomcat, you will notice a list of options available.
From here you can start, stop, refresh the server, etc.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 127 of 309
Figure 33 – New Project
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 128 of 309
NetBeans will create the new project files and directory structure you will need.
An index file (index.html) will also be created for you and it will be opened in
the main window. Most Web applications you will create will have an index
page but, in this example, we will not be using an index page.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 129 of 309
Figure 36 – New JSP file
<%-- This page acts as the error page for all JSP pages in the
example --%>
<html>
<head>
<title>An error has occured</title>
</head>
<body style="background-color:black" text="red">
</body>
</html>
Example 65 – BakeryErrorPage.jsp
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 130 of 309
Figure 37 – BakeryErrorPage.jsp
<html>
<head>
<title>JSP Bakery</title>
</head>
<body style="background-color:lightblue">
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 131 of 309
<center>
<bakery:mt:BakeryTag size="6"/>
<form action="MainPage.jsp">
<%
String prodName = null;
/* Checks to see if there is a value in the textfield, if
not
all records will be retrieved from the database. */
if((prodName = request.getParameter("searchName")) ==
null){
prodName = "";
}
ResultSet rs;
try{
statement = connect.getConnection().createStatement();
rs = statement.executeQuery(“SELECT * FROM products “
+ “ WHERE description LIKE '%” + prodName + “%'”);
%>
<%
while(rs.next()){
out.println("<tr>");
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 132 of 309
out.println("<td>" + rs.getInt("id") + "</td>");
String desc = rs.getString("description");
out.println("<td><a href=\"MainPage.jsp?addProd="
+ desc + "\">" + desc +
"</a></td>");
out.println("<td>R " +
df.format(rs.getFloat("price"))
+ "</td>");
}
} catch(SQLException sqle){
throw new Exception("SQLException " + sqle);
}
%>
</table><br/>
<%
String addProd = null;
boolean exists = false;
ResultSet rs2;
try {
rs2 = statement.executeQuery("SELECT * FROM
products “
+ “WHERE description='" + addProd +
"'");
rs2.next();
int addId = rs2.getInt("id");
if(prodBean.getId() == addId){
//Adding to the quantity
prodBean.setQuantity(1);
exists = true;
break;
} else {
exists = false;
}
}
if(!exists){
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 133 of 309
//Adding a new item
ProductsBean p = new
ProductsBean(addId,rs2.getString(“description"),
rs2.getFloat("price") , 1);
cart.setAddProduct(p);
}
} catch(SQLException sqle){
throw new Exception("SQLException " + sqle);
}
}
%>
<%
for(int i = 0;i < productsVector.size();i++){
ProductsBean pb =
(ProductsBean)productsVector.get(i);
%> <tr>
<td><%= pb.getId() %></td>
<td><%= pb.getDescription() %></td>
<td>R <%= df.format(pb.getPrice()) %></td>
<td><%= pb.getQuantity() %></td>
<form action="DeleteFromCart.jsp">
<td><input type="submit" value="Delete"/></td>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 134 of 309
</form>
</tr>
<% } %>
<br/><hr/>
<%-- Displays the custom tag with the size of the font as
attribute --%>
<bakery:mt:BakeryTag size="2"/>
<bakery:mt:BakeryTag size="4"/>
<bakery:mt:BakeryTag size="2"/>
<bakery:mt:BakeryTag size="4"/>
<bakery:mt:BakeryTag size="2"/>
</center>
</body>
</html>
Example 66 – MainPage.jsp
NOTE You may receive an error from NetBeans saying that the
TagLib.tld file cannot be found. Ignore this error as we will add
this file later.
If the search text field is left empty, or if a value has been added to the cart,
all the records will be retrieved from the database. If one of the hyperlinks is
clicked in the search table, that product will be added to the URL, which then
adds it to the shopping cart. If the product already exists in the cart
(CartBean), then one is added to its quantity. If the product is not in the cart a
new ProductBean is created and this ProductBean is added to the cart.
All the ProductBeans found in the CartBean vector are displayed to the user
with a Delete button to delete them. The Delete button includes a hidden
value which is the product’s id. When the Delete button is pressed, the
DeleteFromCart.jsp searches the CartBean for a product with the same id.
If there is more than one of the specified products in the CartBean then one is
removed from the quantity, otherwise the whole ProductBean is removed from
the CartBean.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 135 of 309
The custom tag simply displays the name of the bakery and the font size in
which it must be displayed.
To set up your project so that the MainPage.jsp will be run when you execute
your application, do the following:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 136 of 309
Figure 39 – New TLD
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 137 of 309
Figure 41 – Creating a tag handler
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 138 of 309
Click Next.
On the next screen, ensure that the Add Corresponding Tag to The
Tag Library Descriptor checkbox is selected. This will add the tag entry
to the TLD file.
Click on Browse... next to the TLD file text field.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 139 of 309
In the Browse Files window, expand the WEB-INF and tlds nodes.
Select TagLib.tld and click on Select File.
For the Body Content, select empty.
Next to the Attributes table, click on New....
Click on Finish.
The BakeryTag.java file will be created and opened in the main window.
Modify the file to look like this:
package bakery.mt;
import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 140 of 309
ServletRequest request = pageContext.getRequest();
try{
JspWriter out = pageContext.getOut();
out.println("<font size=\"" + size + "\"> “ + “Just So
Perfect Bakery </font>");
} catch(IOException ioe) {
throw new JspTagException("IO exception " +
ioe.getMessage());
}
return SKIP_BODY; // Tag contains no body
}
}
Example 67 – BakeryTag.java
package bakery;
import java.io.*;
import java.sql.*;
public DatabaseConnectionBean() {
makeConnection();
}
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 141 of 309
}
return connection;
}
/* set up connection */
public void setCloseConnection(boolean close){
if (close) {
try {
connection.close();
} catch(Exception e) {
connection = null;
}
}
}
NOTE You will need to set up the SQL Server username and password
to use when connecting to the database. Make sure the password
meets the minimum password complexity requirements required
by SQL Server.
package bakery;
import java.io.Serializable;
import java.util.*;
public CartBean () {
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 142 of 309
allProducts = new Vector();
}
package bakery;
import java.io.Serializable;
/* no argument constructor */
public ProductsBean() {
}
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 143 of 309
public ProductsBean(int id,String description,float
price,int quantity){
this.id = id;
this.description = description;
this.price = price;
this.quantity = quantity;
}
This bean creates an instance for each product that is added to the cart. The
following is the property sheet for this bean:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 144 of 309
DeleteFromCart.jsp uses the id value sent from the hidden input value on
the MainPage.jsp to delete the specified product, or remove one from the
product’s quantity.
<html>
<body>
<%-- delete item from cart --%>
<%
Vector allProducts = cart.getProducts();
boolean delete = true;
/* uses the id value sent as a parameter to delete the
item */
int deleteId =
Integer.parseInt(request.getParameter("id"));
ProductsBean pb = (ProductsBean)allProducts.get(deleteId);
} else {
%>
<jsp:setProperty name="cart" property="deleteItem"
param="id" />
<%
}
Now we just need to connect to the database and compile the project:
Use the same database, Bakery, that you used in section 4.6.4.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 145 of 309
Press <F11> to build your project.
Press <F6> to run the project.
When you run the project, NetBeans will deploy it to the Tomcat and open the
MainPage.jsp file in your browser. The output should look like this:
Test the application and make sure everything is working. Ensure that you
understand what is happening behind the scenes with each operation.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 146 of 309
4.9 Compulsory exercise
Exercise 1
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 147 of 309
4.10 Test your knowledge
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 148 of 309
12. Which one of the following is legal JSP syntax to print the
value of i?
a) <%int i = 1;%> <%= i; %>
b) <%int i = 1%> <%= i %>
c) <%int i = 1;%> <%= i %>
d) <%int i = 1%> <%= i; %>
<%=x%>
a) <jsp:expression=x/>
b) <jsp:expression>x</jsp:expression>
c) <jsp:statement>x</jsp:statement>
d) <jsp:declaration>x</jsp:declaration>
<%x=1;%>
a) <jsp:expression x=1;/>
b) <jsp:expression>x=1;</jsp:expression>
c) <jsp:statement>x=1;</jsp:statement>
d) <jsp:scriptlet>x=1;</jsp:scriptlet>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 149 of 309
d) Instead of using the character %> inside a scriptlet, you
may use %\>.
a) 1
b) 2
c) 3
d) The program generates a compilation error.
a) session
b) request
c) httpsession
d) page
a) <jsp:setColor id="fruit"
property="color" value="white"/>
b) <jsp:setProperty name="fruit"
property="color" value="white">
c) <jsp:setProperty name="fruit"
property="color" value="white"/>
d) <jsp:setProperty id="fruit"
property="color" value="white">
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 150 of 309
<jsp:usebean id="fruit" class="Fruit"/>
22. Which two of the following represent the correct syntax for
usebean?
a) include
b) scope
c) errorPage
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 151 of 309
d) debug
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 152 of 309
Unit 5 – Delivering Web Services
Introduction to XML.
Installing the Web Service package.
Writing your own application using Web services.
Using JAXP.
Using the SAX and DOM API.
Using the RESTful API.
ebXML.
Using JavaMail.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 153 of 309
5.1 Introduction to XML
Understand XML.
Understand the differences between HTML and XML.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 154 of 309
XML is a project of the World Wide Web Consortium (W3C). XML has all the
power of SGML but does not use the more complex features. It has a more
clearly defined syntax and structure, making it easier to learn and to use.
XML is a powerful technology that is used to define your own custom markup
language which can be understood by computers and people. It is used as a
way to structure, store and pass information between applications.
This course is designed to give an overview of the XML syntax and associated
technologies.
5.1.1.4 SOAP
SOAP is an abbreviation for Simple Object Access Protocol. SOAP is XML based
and is used in the development of Web services. Because SOAP is XML-based,
it therefore becomes platform-independent.
<?xml version=1.0?>
<movie>
<name>Romeo and Juliet</name>
<description>Love story between two people where their
families are torn apart by hate
</description>
<stars>
<starsname>Leonardo Dicaprio</starsname>
<starsname>Claire Danes</starsname>
</stars>
<producer>Baz Lurhman</producer>
<length>97 minutes</length>
<genre>Romance</genre>
<agerestriction>16</agerestriction>
<released>Late 1997</released>
<rating>8/10</rating>
</movie>
Example 72 – movie.xml
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 155 of 309
Data orientation enables the data to be read easily by machines and XML
can be created by a machine.
5.1.1.6 Well-formedness
To ensure that XML performs as it is supposed to, it is necessary for the XML
document to be well formed. The rules for a well-formed XML document are:
<?xml version=“1.0”?>
<age>3</age>
<Gender>Male</Gender> Tag pairs are all the same case
Once an XML document is well formed it can be displayed by the Web browser.
To display this XML, open up a text editor and only type in the tags. Save
the file as zoo.xml. Open up your Web browser and locate the zoo.xml file.
The following XML tree structure should be displayed by your Web browser:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 156 of 309
Figure 47 ‒ zoo.xml
When you click on the minus (-) sign next to the zoo or the animal element the
entire element collapses and the minus sign changes to a plus (+) sign. You
can click on the plus sign to expand the element again. If the XML document is
not well formed an error page will come up informing you of where an error
has occurred.
Each and every XML document requires the declaration as its first line. The
version must be included in the declaration. If the XML document uses an
external document such as a DTD or XMLSchema, its standalone value will be
set to “no”. The encoding attribute specifies which character encoding the XML
document uses.
Elements:
Non-empty elements contain some body content, either text or other child
elements:
<tagName>some content</tagName>
Empty elements do not contain any body content, although they can include
attributes:
</tagName>
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 157 of 309
Or:
<tagName></tagName>
<tagName attribute=value></tagName>
Five recognisable character entities which are recognised as part of XML and
are not parsed as code by the XML parser are:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 158 of 309
5.1.3 Key terms
Make sure that you understand the following key terms before you
start with the exercises:
XML
HTML
Well-formed
XML Declaration
5.1.4 Exercises
<!-- -->
a) Empty element
b) Comment
c) Open tags
d) Place holder
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 159 of 309
5.2 Web Applications technologies
JSF contains:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 160 of 309
Table 14 ‒ JavaServer Faces phases
Phases Description
Restore view When Java receives a request due to an event being
triggered, the restore view begins.
Request values When a component has been restored or created it uses
a decode method to get its value from the request
parameters. An error message will be queued on the
FacesContext if a conversion fails; the JSF then moves
to the render response phase.
Process validation All validators that are registered on a component tree
are now being processed by the JSF. The JSF adds an
error message to the FacesContext instance and jumps
the life cyle to the render phase if by any occurrence the
local value is invalid.
Update model The bean properties will be updated to be in line with
values the inout component’s value attribute.
Invoke application This is the phase where all handling of application-level
events is done, for example, submitting a form.
Render response In this phase, the server application is queried to render
a page by JSF if the application is using JSP pages. The
JSP container will then excute the page after the
components represented on the page are added to the
component’s tree. The components will then render
themselves as the JSP application server goes through
the page.
JSP JSF
JSP writes to the response as soon as JSF would like to do some pre/post
it encounters template text content. processing with it.
JSP syntax with <% %> embedding
raw Java code in a JSP is considered
Facelets pages use well-formed XML.
a very poor practice, and does not
conform to the MVC ideology.
JSF Facelet pages are not compiled into
Every time you edit, save and reload
servlets, but are interpreted using SAX
a JSP page, the server’s JSP compiler
since they are XML-based. Facelets can
generates Java servlet code and
be configured to detect changes to
compiles it into a servlet.
pages immediately.
The JSP translation process costs a Facelets can be configured to render
few seconds, depending on server changes to pages immediately,
performance. speeding up development.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 161 of 309
5.2.3 The Spring framework
This is another framework that makes working with JSP easier.
While JSF was still being developed from 1.0 to 2.0, Spring became
the most popular view technology.
Faces Spring
Component based Request based
Supports MVC UI only, to be used Supports MVC UI and framework-
with back-end EJBs and a transaction specific encapsulation (using POJOs)
management framework without using EJBs
XML based XML based
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 162 of 309
5.2.5 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
JSF
JSF architecture
JSF lifecycle
5. 2. 6 Revision questions
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 163 of 309
5.3 Using JAXP
<price>3.50</price>
However, imagine a file that is several pages long. Looking for data manually
is rather tedious and so is writing a program which looks for the <price> tags.
Java offers a simple way of processing XML data. This API, called Java API for
XML Processing (JAXP), provides two ways of parsing data, i.e. SAX
(Simple API for XML) and DOM (Document Object Model). Java Web
Services Developer Pack 2.0 includes JAXP which supports XSLT (XML
Stylesheet Language Transformations).
As you can see, the parser calls the startElement event when it comes across
the < sign. The </ sign calls the endElement event. When there is text
between the tags, the character event is called. You need to tell the parser
what to do when these events occur. The default action is to do nothing. To
change this, you need to write a class extending DefaultHandler (default
implementation) which specifies actions to be taken once certain events occur.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 164 of 309
The following diagram shows the structure of the SAX package:
Content
handler
SAX parser
factory
Error
SAX handler
reader
SAX parser DTD handler
Entity
resolver
Figure 48 – SAX
To be able to parse an XML file, you need to create a SAXParser object from a
SAXParserFactory object. For example:
The SAXParser object wraps a SAXReader. Usually, you will mainly deal with
the SAXParser object, not the underlying SAXReader object. The
DefaultHandler implements the ContentHandler. You need to extend the
DefaultHandler to perform tasks when documents are being parsed.
ErrorHandler objects may be used to deal with errors that may occur while
parsing.
The following table lists the packages that are included in SAX (table from
Sun):
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 165 of 309
Table 15 – SAX packages
Package Description
Defines the SAX interfaces. The name org.xml is the
org.xml.sax package prefix that was settled on by the group that
defined the SAX API.
Defines SAX extensions that are used when doing
more sophisticated SAX processing, for example, to
org.xml.sax.ext
process Document Type Definitions (DTD) or to see
the detailed syntax of a file.
Contains helper classes that make it easier to use
SAX, for example, by defining a default handler that
org.xml.sax.helpers has null methods for all of the interfaces, so you only
need to override the ones you actually want to
implement.
Defines the SAXParserFactory class which returns the
javax.xml.parsers SAXParser. Also defines exception classes for
reporting errors.
DocumentBuilder
Factory
Document
Object Model
objects
Document
XML
Builder
document
// Method number 1
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("priceList.xml");
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 166 of 309
// Method number 2
Document document = DocumentBuilder.newDocument();
Example 75 – Creating Document objects
Transformer factory
Transformer
Source Result
object
Transformation
instructions
Figure 50 – XSLT
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 167 of 309
Table 17 – XSLT packages
Package Description
Defines the TransformerFactory and
Transformer classes which are used to find
an object capable of doing transformations.
javax.xml.transform After creating a transformer object, you can
invoke its transform() method, providing it
with an input (source) and an output
(result).
Classes to create input (source) and output
javax.xml.transform.dom
(result) objects from a DOM.
Classes to create input (source) from a SAX
javax.xml.transform.sax parser and output (result) objects from a
SAX event handler.
javax.xml.transform.stream Classes to create input (source) and output
(result) objects from an I/O stream.
<name>Lunch Bar</name>
<price>3.50</price>
<name>Simba chips</name>
<price>2.50</price>
</quote>
Example 76 – quote.xml
The following is your first SAX parser program. Save it in the same directory
as the XML file:
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 168 of 309
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
Example 77 – FirstParser.java
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
StringBuffer buffer ;
private void out(String s) { // Utility methods
System.out.print(s);
}
private void outLine(String s) { // Utility methods
System.out.println(s);
}
public void startDocument() throws SAXException { //
startDocument event
outLine("Starting document!");
}
public void startElement(String namespacesURI, //
startElement event
String sName, // simple name
String qName, // qualified name
Attributes attrs) // possible attributes
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 169 of 309
throws SAXException {
outLine("Opening element: <" + qName + "> ");
}
public void endElement(String namespaceURI, // endElement
event
String sName,
String qName) throws SAXException {
if (!(buffer == null)) {
outLine("Closing element </" + qName + ">");
outLine("Value was " + buffer.toString().trim());
buffer = null;
}
}
public void characters(char buf[], int offset, int len)
throws SAXException { // characters
event
String s = new String(buf, offset, len);
javac *.java
java –cp .;FirstParser.class FirstParser quote.xml
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 170 of 309
Figure 51 – SAX output
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 171 of 309
public void setDocumentLocator(Locator l) {
out("Locator method :");
outLine("system ID " + l.getSystemId());
}
Example 79 – setDocumentLocator()
Take note that the “Locator method” line is printed before “Starting
document!”
<name>Simba chips</name>
<?my.tuckshop.program QUERY="discount"?>
<price>2.50</price>
</quote>
Example 80 – quote.xml
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 172 of 309
public void processingInstruction(String target, String data)
throws SAXException {
outLine("\t\tProcess instruction for application : " +
target);
outLine("\t\tAction to be taken : " + data);
}
Example 81 – processingInstruction()
When the program is compiled and run again, you can see the output dictated
by the processingInstruction() method whenever the price element is
found:
.......
Value was FizzPops
Process instruction for application : my.tuckshop.program
Action to be taken : QUERY="discount"
Opening element: <price>
Closing element </price>
Value was .50
......
In this case, the only steps specified by the programmer were to print out the
strings. If it were a proper application, the code can, for example, pop up a
dialogue box to ask the operator how much discount is to be applied or send
an email to the supervisor.
<name>Lunch Bar</name>
<price>3.50</price>
<name>Simba chips</name>
<price>2.50</price>
</quote>
Example 82 – quote.xml
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 173 of 309
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAX
ParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalErro
r(Unknown Source)
.........
When the parser program is run again, you should see a different output:
.........
Oops! Not a well-formed document!!
Error occured in line 11 process number file:C:/Webservices/SAX/quote.xml error
message The element type "name" must be terminated by the matching end-tag "</na
me>".
&entityName;
Using this syntax, insert a new entity (in this case, an opening and a closing
angle bracket) into the existing quote.xml file:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 174 of 309
<!-- entity called lt (less than) and gt (greater than)
included -->
<name>< FizzPops ></name>
<price>.50</price>
......
Example 84 – Adding entities
When you run the parser program again, you will notice that < has been
replaced by an opening angle bracket (<) and > has been replaced by a
closing angle bracket (>):
......
Opening element: <name>
Closing element </name>
Value was < FizzPops >
Opening element: <price>
......
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 175 of 309
<?xml version="1.0" encoding="utf-8" ?>
<quote>
<name>FizzPops</name>
<price>.50</price>
<name>Lunch Bar</name>
<price>3.50</price>
<name>Simba chips</name>
<price>2.50</price>
<![CDATA[
Thank you!!
]]>
</quote>
Example 85 – Including CDATA
When the parser program is run, you should see the following output:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 176 of 309
follow in order to be valid. The following is a simple DTD document for the
quote.xml file:
The document defines four elements – quote, logo, name and price. logo,
name and price are all #PCDATA (parsed character data). quote is slightly
different.
This definition specifies that a quote can contain one logo element, and one or
more name and price elements may or may not appear.
Because the advert entity is defined, it can be used within the quote.xml file.
Modify the quote.xml file to include a reference to the DTD file, as well as
a reference to the advert entity:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE quote SYSTEM "quote.dtd">
<quote>
<logo>&advert;</logo> <!-- new element! Reference to the
advert entity -->
<name>FizzPops</name>
<price>.50</price>
<name>Lunch Bar</name>
<price>3.50</price>
<name>Simba chips</name>
<price>2.50</price>
</quote>
Example 87 – Including a custom entity through DTD
When you run the parser program you should see that the entity has been
replaced:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 177 of 309
.......
Opening element: <quote>
Opening element: <logo>
Closing element </logo>
Value was Your Wonderful Tuckshop Store!!
Opening element: <name>
Closing element </name>
.......
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder =
factory.newDocumentBuilder();
Document document = builder.parse( new File(argv[0])
);
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 178 of 309
The program creates a DocumentBuilderFactory and, using the factory,
creates a new DocumentBuilder object. In turn, this object is used to return a
Document object. Consult the Java API for various methods you can use with
the Element, NodeList and Node objects. In the example, only a few methods
are used such as getChildNodes() and getTagName().
<name>Lunch Bar</name>
<price>3.50</price>
<name>Simba chips</name>
<price>2.50</price>
</quote>
Example 89 – quote2.xml
When the program is run using quote2.xml, the following is printed out:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 179 of 309
The following example creates a Document object which is similar to the
structure of the quote.xml file:
import javax.xml.parsers.*;
import org.w3c.dom.*;
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
try {
// Create a new document
DocumentBuilder builder =
factory.newDocumentBuilder();
Document document = builder.newDocument();
// Add children!
Element root = (Element) document.createElement("root");
document.appendChild(root);
root.appendChild(document.createTextNode("Root text1"));
Element child1 = (Element)
document.createElement("child1");
Element child2 = (Element)
document.createElement("child2");
Element child3 = (Element)
document.createElement("child3");
child1.appendChild(document.createTextNode("Child
text1"));
child2.appendChild(document.createTextNode("Child
text2"));
child3.appendChild(document.createTextNode("Child
text3"));
root.appendChild(child1);
root.appendChild(child2);
root.appendChild(child3);
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 180 of 309
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example 90 – MyDom.java
Compile and run the program. You should see the following output:
Alternatively, you can type out the created DOM object as an XML file using
the javax.xml.transform package. The following example creates a Document
object and prints out the transformed result (XML) to the screen:
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
DocumentBuilderFactory factory
=DocumentBuilderFactory.newInstance();
try {
// Create a new document
DocumentBuilder builder =
factory.newDocumentBuilder();
Document document = builder.newDocument();
// Add children!
Element root = (Element) document.createElement("root");
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 181 of 309
document.appendChild(root);
root.appendChild(document.createTextNode("Root text1"));
child1.appendChild(document.createTextNode("Child
text1"));
child2.appendChild(document.createTextNode("Child
text2"));
child3.appendChild(document.createTextNode("Child
text3"));
root.appendChild(child1);
root.appendChild(child2);
root.appendChild(child3);
Compile and run the program. You should see the following output:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 182 of 309
Figure 55 ‒ Output of MyDom2
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 183 of 309
5.3.4 Key terms
Make sure that you understand the following key terms before you
start with the exercises:
JAXP
SAX
DOM
XSLT
SAXParserFactory
SAXParser
SAXReader
ContentHandler
ErrorHandler
DocumentBuilderFactory
DocumentBuilder
TransformerFactory
Transformer
5.3.5 Exercises
The following exercises must be checked by your lecturer and marked off on
the checklist at the back of this learning manual.
1. Create an XML file which describes an order, and write two programs to
parse the file using SAX and DOM respectively. Print out the elements and
values of the file.
2. Include the CDATA section in the program that was created in the previous
question to display an invoice.
3. Write a DTD document with which you can validate the XML file. Include a
copyright entity and insert it into the XML file.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 184 of 309
4. Which one of the following is not true regarding JAXP?
a) SAXParser wraps a SAXReader.
b) The DefaultHandler implements the ContentHandler.
c) The “>” sign calls the endElement event.
d) ErrorHandler objects are used to deal with parsing errors.
5. True/False: SAX can be used to create modifiable object representation of
XML data.
6. Which one of the following is the correct syntax for importing an entity?
a) *entityName
b) &entityName
c) %entityName;
d) &entityName;
7. True/False: DOM objects can be written as XML files using DTD definitions.
Read the topics that have been covered in this section in your textbook.
It is recommended that you read the topics that have been covered in this
section in the Java WS Tutorial. The tutorial can be found at:
https://docs.oracle.com/javaee/7/tutorial/jaxws.htm
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 185 of 309
5.4 Introduction to RESTful Web Services
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 186 of 309
5.4.1.3 HTTP methods
As briefly highlighted in the previous section, the Push, Get, Post and Delete
are operations used in the architectures based on REST. The following table
will explain what each of the operations is responsible for.
Jersey comprises a REST server and a REST client. It uses a servlet to scan
predefined classes to identify RESTful resources on the server via the web.xml.
http://domain:port/title/display-name/url-pattern/class-path
The below table has listed annotation which are mostly used in JAX-RS.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 187 of 309
Table 20 ‒ JAX RS annotations
Annotation Description
@PATH Path is set to base URL + /your_path to which the base URL is
based on the application name, the servlet and the URL
pattern from the web.xml configuration file.
@POST Shows the following method will respond to an HTTP POST
request.
@GET Indicates that the following method will answer to an HTTP
GET request.
@PUT Indicates that the following method will answer to an HTTP
PUT request.
@DELETE Indicates that the following method will answer to an HTTP
DELETE request.
@Produces @Produces defines which MIME type is delivered by a method
annotated with @GET. In the example, text ("text/plain") is
produced. Other examples would be "application/xml" or
"application/json".
@Consumes @Consumes defines which MIME type is consumed by this
method.
@PathParam Used to inject values from the URL into a method parameter.
This way you inject, for example, the ID of a resource into the
method to get the correct object.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 188 of 309
Figure 56 ‒ Other selection
In the next window, select Simple Root Resource and click Next.
Now do the following (and you should have a similar screenshot to the one
below):
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 189 of 309
For MIME Type, select text/html.
Click Finish.
If you now check in the projects pane, a new resource, HelloWorld.java, which
has a template for RESTful Web Services has been succefully created. Now you
will have to tweak the code in the getHtml() method in the HelloWorld.java
file to get the desired results. You will see there is a //TODO comment and an
exception. Remove the two and replace them with the line of code appearing
below.
After you have changed the line of code, right-click on the project and click
Test RESTful Web Services.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 190 of 309
Figure 59 ‒ Testing RestFul WebServices
Click OK.
The application will be deployed and the browser will show the test client.
Make sure you choose the “Glassfish server” as your server to deploy the
Web service on. This is because Java EE projects typically require the GlassFish
server to deploy and run properly.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 191 of 309
Figure 60 ‒ RestFul Web Services page
Select the helloworld in the left-hand pane and then click the Test button
in the right pane.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 192 of 309
Set the Relative URL to the location of the REST you just
created and the Context Path.
Setting this property will help you to prevent the file index.jsp from
showing as the default each time you run the application.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 193 of 309
5.4.3 Key terms
Make sure that you understand the following key terms before you start with
the exercises.
5.4.4 Exercises
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 194 of 309
5.5 Writing Web services using JAX-WS
5.5.1 Introduction
Java API for XML Web services (JAX-WS) is used in the building of Web
services and clients that communicate through XML. JAX-WS makes use of
XML-based protocols such as SOAP and gives developers the platform to write
Remote Procedure Call (RPC) Web services.
JAX-WS has the advantage that it hides the complexity of SOAP messages
from the developer. The developer has the role of specifying the Web service
operations by making use of methods coded in Java. The developer has to
code both the application and server side. Another advantage of JAX-WS Web
services is that they are platform independent. JAX-WS can also communicate
with another Web service that is not developed in Java; hence they also give
unrestricted access. JAX-WS makes use of W3C technologies such as SOAP,
HTTP and WSDL.
A tool called Ant is commonly used to write a build file which specifies how
programs should be compiled and deployed. You can think of build files as
batch files in Windows or routine shell scripts in Linux, for Java.
C:\>ant -v
Buildfile: build.xml does not exist!
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 195 of 309
Build failed
You may get the following response if Ant is not set up correctly:
This could be because the path has not been set up properly. If it seems that
Ant is not installed (i.e. you cannot find the installation directory of Ant),
download Ant from http://ant.apache.org/bindownload.cgi and unzip the file to a
suitable directory on your hard drive.
Under the System variables box, check if you have the JAVA_HOME variable
setup. If not, do the following:
Type in JAVA_HOME as the Variable name, and for the Variable value
include the path to your JDK folder. Typically it is C:\Program
Files\Java\jdk1.8.0_151.
NOTE The JDK version might vary depending on the JDK version you
have installed on your system.
Click OK.
Click the New button under System variables again and enter the
Variable name as ANT_HOME, and for the Variable value include the
path to where you extracted your Ant folder. In this learning manual we
extracted it to C:\Sun\apache-ant-1.10.1, so it will be put as the
variable value.
Look for the Path variable under System variables. Once you find it, click on it
and click Edit.
Add ;%ANT_HOME%\bin to the end of the path, as shown below. This will
enable us to make use of Ant anywhere.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 196 of 309
Figure 62 ‒ Setting up Ant environment variable
Now to test if Ant is working, run the ant –v command again. You should get
the response:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 197 of 309
Select Java Web from the categories window. Select Web Application
from the projects window then Click Next as shown below.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 198 of 309
On Server, choose GlassFish Server. For the Java EE Version, choose
Java EE 7 Web. Click Finish.
In the projects panel, right click on the ComputeSum node and select New>
Web Service.
If you do not see Web Service go to Other> Web Services> Web Service
Click Finish.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 199 of 309
Figure 67 – Web Service Name
Now, we need to create an operation for our service. The operation we want to
create is to calculate the sum of two integers. Do the following:
Under the Projects tab, expand the ComputeSum node then expand
Web Services. Right click on the ComputeSumService you created
and click “Add Operation”
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 200 of 309
Figure 68 – Adding operation to web service
Our operation will take two integers and calculate the sum of the integers and
return the result as an int.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 201 of 309
Click the Add button and enter the Name as num1 and Type select int from
the list of options. Click the add button again and enter the name as num2
and type as int as shown in Figure 69. Click OK.
package com.advancedjavacourse.webservice;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
/**
*
* @author Sheunesu Makura
*/
@WebService(serviceName = "ComputeSumService")
public class ComputeSumService {
/**
* This is a sample web service operation
*/
@WebMethod(operationName = "hello")
public String hello(@WebParam(name = "name") String txt) {
return "Hello " + txt + " !";
}
/**
* Web service operation
*/
@WebMethod(operationName = "CalculateSum")
public int CalculateSum(@WebParam(name = "num1") int num1,
@WebParam(name = "num2") int num2) {
//TODO write your implementation code here:
return 0;
}
}
Example 92 – ComputeSumService.java
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 202 of 309
It is important to note that in annotating the implementation class, you must
make use of the javax.jws.WebService or the
javax.jws.WebServiceProvider annotations.
@WebMethod(operationName = "CalculateSum")
public int CalculateSum(@WebParam(name = "num1") int num1,
@WebParam(name = "num2") int num2) {
int sum = 0;
sum = num1 + num2;
return sum;
Example 93 - CalculateSum operation
From the code, you can see that the CalculateSum operation we created. We
have added the code which returns the sum. The two parameters num1 and
num2 will be entered on the webpage and after the operation executes, the
sum of the two integers is returned.
The next phase will be to deploy and test our web service. Do the following:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 203 of 309
Figure 70 – Deploying web service
Under the ComputeSum project node, expand Web Services then right
click on ComputeSumService and click Test Web Service.
A tester client gets created by Glassfish having the URL shown. Note that the
default listening port for GlassFish Server is 8080. The URL for the tester has a
WSDL link which links to the file created for the ComputeSumService Web
Service.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 204 of 309
Now we can test to see if our CalculateSum operation works. Enter any two
integers as shown below and click calculateSum.
After clicking the button the sum gets computed and the result returned as an
integer under “Method returned”.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 205 of 309
Figure 74- Method invocation
The SOAP Request shows the request for the ComputeSumService Web
Service which sent in the form of xml. It is sending the num1 and num2
values to be used for the sum method.
The SOAP responds shows the response coming from the
ComputeSumService Web Service, returning the output of sum of num1 and
num2.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 206 of 309
5.5.4 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
JAX-WS
Ant
Web Service
GlassFish Server
@WebMethod
5.5.5 Exercises
Read the topics that have been covered in this section in your textbook.
It is recommended that you read the topics that have been covered in this
section in the Java WS Tutorial. The tutorial can be found at:
https://docs.oracle.com/javaee/6/tutorial/doc/gijti.html
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 207 of 309
5.6 ebXML and the Future of Web services
The arrival of Internet and e-commerce sites has overcome some of the
problems. However, the solution also entailed having to surf for the correct site
and fill in custom-made forms.
The Web services discussed in this learning manual overcame the problems
even further. Still, there were proprietary Web service specifications in addition
to infrastructure specifications. The following sections will discuss how ebXML
differs from the current Web services specification.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 208 of 309
5.6.2 Basic ebXML architecture
The ebXML architecture is composed of:
ebXML builds on existing standards such as HTTP, TCP/IP, MIME, SMTP, FTP,
UML and XML.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 209 of 309
Business process and information models
Repository
TPA
Biz Biz
service service
interface ebXML transport interface
Package
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 210 of 309
Table 21 – Differences between the ebXML and current Web services
architectures
Type Web services ebXML
Communication Request/response Collaboration
RPC-style synchronous
communication between
tightly coupled services,
Synchronous, asynchronous
Business service or document-style
communication
asynchronous
communication between
loosely coupled services
Interface CPP, CPA (a superset of
WSDL
description WSDL, contains WSDL)
ebXML Message Service
Protocol and
SOAP, XML (over SOAP), XML, BPSS (as
formats
“business” protocol)
ebXML registry (UDDI
How to find registry may point to an
UDDI registry
business partners ebXML registry or registry
objects, e.g. CPA)
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 211 of 309
5.6.4 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
ebXML
EDI
CPP
CPA
Repository
Collaboration
5.6.5 Exercises
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 212 of 309
5.6.7 Suggested reading
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 213 of 309
5.7 JavaMail
When you compose a message and send it, your mail server picks it up and,
using Simple Mail Transfer Protocol (SMTP), sends the mail to the recipient’s
mail server. The recipient can then retrieve the message from their mail server
using protocols such as Post Office Protocol (POP) or Internet Message Access
Protocol (IMAP).
Emails are made of two parts – header and body. The header contains
information such as the sender, the recipient, title, etc., while the body
contains the actual data sent. Initially, emails could only send ASCII text.
However, this limitation has been largely overcome with the introduction of
Multipurpose Internet Mail Extensions (MIME). MIME provides the functionality
to send emails (including the headers) in different languages (i.e. non-US
ASCII), and to send very long messages.
The following program takes in five arguments and sends an email message:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 214 of 309
boolean sending = true;
if (args.length != 5){
try{
Properties props = System.getProperties();
props.put("mail.smtp.host", args[0]);
message.setText(args[4]);
message.setSubject(args[3]);
message.setFrom(new InternetAddress(args[2]));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(args[1]));
System.out.println("Message sending");
Transport.send(message);
}catch(MessagingException e){
sending = false;
System.out.println("Sorry you are not connected. Make sure
your SMTP Server is correct!!!");
}
if (sending == true){
System.out.println("Message sent");
}else{
System.out.println("Message was not sent");
}
}
}
Example 94 – SimpleSender.java
The first argument is the name of the SMTP host. You can check this from your
email client or your system administrator. Once you have found the SMTP
server, add it to the system properties list:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 215 of 309
instance, use the getInstance() method. The second argument (null) passed
to the constructor is an Authenticator object. Therefore, we are not using
any security measures in this example.
After a session object has been created, you can proceed to create an email.
The MimeMessage object is the only subclass of the Message class which
represents a standard MIME mail message. There are five constructors, but we
are using the default constructor which accepts session as the only
parameter.
message.setText(args[4]);
message.setSubject(args[3]);
message.setFrom(new InternetAddress(args[2]));
message.addRecipient(Message.RecipientType.TO, new
InternetAddress(args[1]));
The Transport class is used to send the message created. This class is used to
communicate in a specific protocol (usually SMTP). It is an abstract class, and
you can simply call the static send method to send a message. It is also
possible to get a specific instance from the session for the protocol you are
using (i.e.SMTP) and pass the username and password, send the message and
close the connection:
This method is preferable when there is more than one message to be sent
because the Transport object will keep the connection with the mail server
active.
Compile the file and run the program, passing five arguments – SMTP server,
recipient address, sender address, subject and text. If you have Internet
access and have used the correct SMTP Server, the output will be:
If you do not have Internet access or did not use the correct SMTP Server, the
output will be:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 216 of 309
Figure 77 – Sending mail failed
NOTE If you are not connected to a network with an SMTP host the
application will throw an exception.
The first example assumes that the user has access to the Internet. When the
message is displayed, if the user does not have Internet access, or if the URL
referred by the mail is not present, the user will not see anything:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
try {
Session session = Session.getDefaultInstance(props,
null);
MimeMessage message = new MimeMessage(session);
message.setSubject("Hello");
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new
InternetAddress(to));
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 217 of 309
String htmlText = "<H1>Hello</H1>" +
"<img
src=\"http://www.google.com/images/logo.gif\">";
message.setContent(htmlText, "text/html");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Example 95 – SendHTMLMail.java
Compile and run the program. Remember to pass three parameters (host,
recipient, sender) to the program:
Instead of setting the text of the body using the setContent() method, you
must create different parts of the message, add them to a MimeMultipart
object and set the MimeMultipart object as content for the message.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 218 of 309
The following example sends a multi-part message:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import javax.activation.*;
messageBP.setContent(msg, contentType);
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 219 of 309
message.setContent(multipart);
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
try{
Session session = Session.getDefaultInstance(props,
null);
MimeMessage message = new MimeMessage(session);
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 220 of 309
new InternetAddress(to));
multipart.addBodyPart(messageBP);
message.setContent(multipart);
Transport.send(message);
}catch(MessagingException e){
sending = false;
System.out.println("Sorry you are not connected!");
}
if (sending == true){
System.out.println("Message sent");
}else{
System.out.println("Message not sent");
}
}
}
Example 97 – SendAttachedMail.java
To create an object which houses the two parts of the message, you need to
use the MimeMultipart class. Previously, you used the MimeMultipart
constructor which accepts one argument (the MIME subtype). This was
because you were using different body parts (i.e. imag, and text) to form a
compound message. However, the attachment is not integrated into the
message in the example above. The subtype is multitype/mixed and since
this type is the default for the constructor you do not need to pass it to the
constructor:
Now you can add the first of the body parts to the MimeBodyPart object using
the addBodyPart() method. The last thing to do is to create the body part
which contains the attachment file you wish to use and add it to the
MimeMultipart object. The data handler used is FileDataSource because we
are attaching a file. If you are reading from a URL, you would use a
URLDataSource object. When you have created a DataSource object, pass it to
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 221 of 309
the DataHandler constructor and then attach it to the BodyPart with
setDataHandler():
messageBP.setFileName(fileName);
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
try {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props,
null);
Store store = session.getStore("pop3");
store.connect(host, username, password);
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 222 of 309
store.close();
} catch (MessagingException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example 98 – GetMail.java
Usually, your mail server will be running POP3 or IMAP. In our example above,
we have used POP3. To see whether you can connect to the POP server, type
the following at the command prompt:
you will be able to run the example above which uses POP3. If your computer
setting does not allow telnet, it does not mean your mail server is not running
(check the Windows Services).
From then on, you can delete messages, reply to messages, etc.
In your mailbox there are usually a few folders such as Inbox, Sent Items
and Deleted Items. To access a specific folder, create a Folder object.
Because it is an abstract class, you cannot use the new keyword to instantiate
a Folder object. Instead, you need to invoke the getFolder() method of the
Store object:
The folder can be opened using the open() method. The Folder.READ_ONLY
parameter was passed, but you can also specify Folder.READ_WRITE:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 223 of 309
folder.open(Folder.READ_ONLY);
Once you have retrieved all the messages, methods such as getFrom() and
getSubject() can be used. The writeTo() method throws an IOException,
and a catch block catching the exception must be added.
When you are done browsing emails, you should close the Folder and Store
objects. The close() method accepts one boolean value which indicates
whether to delete any messages marked for deletion. Deleting messages will
be covered in the next section.
Return-Path: <joe@hotmail.com>
Received: from hotmail.com (f103.law9.hotmail.com [64.4.9.103])
by first-lx3.storage.co.za (8.11.6/8.11.6) with ESMTP id
h4S8MnS13107
for <joe@cti.co.za>; Wed, 28 May 2013 10:22:50 +0200
Received: from mail pickup service by hotmail.com with Microsoft
SMTPSVC;
Wed, 28 May 2013 01:20:56 -0700
Received: from 196.31.129.138 by lw9fd.law9.hotmail.msn.com with
HTTP;
Wed, 28 May 2013 08:20:56 GMT
X-Originating-IP: [196.31.129.138]
X-Originating-Email: [joe@hotmail.com]
From: "joe" <joe@hotmail.com>
To: joe@cti.co.za
Subject: Another email testing
Date: Wed, 28 May 2013 08:20:56 +0000
Mime-Version: 1.0
Content-Type: text/plain; format=flowed
Message-ID: <Law9-F103VSFlYthhUx00058d4a@hotmail.com>
X-OriginalArrivalTime: 28 May 2013 08:20:56.0707 (UTC)
FILETIME=[10160530:01C324
F2]
X-MailScanner: Found to be clean
X-MailScanner-Information: Please contact the ISP for more
information
messages[i].setFlag(Flags.Flag.DELETED, true);
However, there are two more things to change – you need to open the mail
folder with a READ_WRITE option, and when you close the folder you must
notify the server to delete all messages marked for deletion:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 224 of 309
folder.open(Folder.READ_WRITE);
folder.close(true);
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
public class DeleteMail {
public static void main(String args[]) {
if (args.length!= 3) {
System.out.println("Usage : host username password");
System.exit(1);
}
String host = args[0];
String username = args[1];
String password = args[2];
try {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props,
null);
Store store = session.getStore("pop3");
store.connect(host, username, password);
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 225 of 309
}
Example 100 – DeleteMail.java
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
String recipient =
messageArr[i].getFrom()[0].toString();
System.out.println(recipient);
System.out.println(i + " : " + recipient
+ "\t" + messageArr[i].getSubject());
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 226 of 309
if ("Yes".equals(line)) {
try {
MimeMessage message = new
MimeMessage(session);
message.setText("Replying...");
message.setSubject("Replying to your
message!");
message.setFrom(new
InternetAddress("bill@microsoft.com"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(recipient));
System.out.println("Replied!");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
} else {
break;
}
}
folder.close(false);
store.close();
}
}
Example 101 – ReplyMail.java
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 227 of 309
5.7.5 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
SMTP
POP3
IMAP
MIME
Session
MimeMessage
Transport
HTML emails
5.7.6 Exercises
The following exercises must be checked by your lecturer and marked off on
the checklist at the back of this learning manual.
1. True/False: MIME enables you to send messages which are not simple
ASCII text messages.
2. Which one of the following is a protocol used to transfer emails?
a) SMTP
b) IMAP
c) POP3
d) MIME
3. True/False: Emails are made of two parts – header and body.
4. True/False: The SMTP host and the POP3 host are always the same.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 228 of 309
5.8 Creating a Web service in Netbeans
Note: Make sure the Apache TomCat server is started and is running. You
can check this by going to the services tab in NetBeans, and checking servers.
Create a new Web application project and name it Hello. Make sure you
select Apache Tomcat as your server.
Right-click on the Hello project node in the Projects window and select
New -> Other....
Select Web Services in the Categories window and select Web Service
in the File Types window. Click on Next.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 229 of 309
In the next window, type in “HelloService” as the name of the Web
service and type in “helloservice” in the Package field. Click on Finish.
The Web service will be created for you. An implementation class named
HelloService.java will be opened in the Source Editor for you.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 230 of 309
Figure 81 – Add Operation
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 231 of 309
If you look at the HelloService.java code in the Source Editor window, you
will see that a method (operation) has been added.
The @ characters in the generated code are called annotations. You only need
to know that it is used to describe code (much like comments) for the
compiler.
@WebMethod
public String sayHello(@WebParam(name = "name") String name) {
return "Hello " + name;
Example 102 – sayHello()
In the menu, select Tools -> Options and select your browser in the Web
Browser drop-down box. Click on OK.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 232 of 309
Figure 84 – Select Web browser
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 233 of 309
Right-click on the Hello node in the Projects window and select Run
Project.
The Web service will be deployed and the description of the service will be
opened in your browser.
When you click on the WSDL link, the WSDL file for the Web service will be
displayed:
NOTE Web applications which consume the Web service can be made in
more or less the same manner.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 234 of 309
In the Categories window, select Java. In the Projects window, select
Java Application and click on Next.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 235 of 309
Figure 89 – Project name
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 236 of 309
In the WSDL and Client Location window, select the WSDL URL radio
button and enter the Web service location in the WSDL URL field (in this
case http://localhost:8080/Hello/HelloService?wsdl).
Select “helloclient” in the Package drop-down menu.
Click on Finish.
The WSDL file will be downloaded from the provided URL and the client will be
created under the Web Service References node in the Projects window.
Expand the Web Service References node until the sayHello node is
exposed.
Drag the sayHello node below the HelloClient.java main code.
The following will be displayed:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 237 of 309
Now we need to add some implementation code to the class to use the Web
service.
Add the following code so that we just assign the result from the Web
service to a String and then print out the String.
When you run the program, you should receive the following output:
Figure 94 – Output
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 238 of 309
5.8.3 Key terms
Make sure that you understand the following key terms before you
start with the exercises:
Expose
Implementation
Consume
5.8.4 Exercises
Write a simple Web application to consume the Web service created in this
chapter.
There are no revision questions for this section. However, ensure that you are
comfortable with the objectives of this section.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 239 of 309
5.9 Test your knowledge
SAXParserFactory fac =
new SAXParserFactory.newInstance();
SAXParser parser = fac.newSAXParser();
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 240 of 309
5. Which one of the following statements regarding SAX and
DOM is incorrect?
a) SAX is more efficient.
b) SAX can be used to add or delete nodes.
c) DOM can be used to create an object which represents
a whole XML document.
d) A DOM object must stay in memory as one object.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 241 of 309
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 242 of 309
Unit 6 – Android Application Development
Android Development Kits and Installation – You will install the Java
Wireless Toolkit and you will be introduced to other available toolkits.
Android Studio Introduction and Environment – You will be introduced to
the Android Studio IDE.
Managing Application Resources – You will learn to use the resources in an
Android application.
Building Android application – You will learn how to create an Android
application.
Designing Graphical User Interface – You will learn how to customise an
Android application
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 243 of 309
6.1 Android Studio installation
Android names its various operating systems through sweet foods. Examples
of previous Android operating systems include Ginger Bread (Android 2), Jelly
Bean (Android 4), Lollipop (Android 5), etc. The latest version of Android is
Oreo.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 244 of 309
6.1.2 Installing and setup
Android developers write and test their applications on computers and then
deploy them onto an actual device for further testing. In this section, we look
at how the setup is done and explore Android Studio.
As you are using Android Studio to write Android apps, Android Studio will be
using the SDK as it is the one used to create, debug and run Android
applications. The SDK and AVD Manager will be used to keep the SDK updated
with every new release of Android. In developing Android aps, the Minimum
Required SDK is used to designate to the Google Play Store the oldest version
of Android that the app can run on. The Target SDK is the version of Android
the app is designed to run on and will compile with.
As you are writing your apps, you can test them on your Android
phone/device. You will need to enable USB debugging on the Android device.
On your home screen, select Menu, System Settings/Settings, then Developer
options and enable the USB debugging option.
You will need about 10 GB of free disk space and 4 GB RAM to be able to install
Android Studio. If you were using NetBeans and had already installed the Java
Development Kit, you would not have to re-install the JDK.
The JAVA Development Kit (JDK) version 8 or the latest version is available
for download at:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-
downloads-2133151.html
Android Studio, available for download at:
https://developer.android.com/studio/index.html
6.1.2.2 Installing
The following steps should be taken on the host computer which will be used
for development.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 245 of 309
4. You will be presented with the Welcome page of the setup wizard.
Click Next.
On the next page, select “Standard”, then click Next.
On the next page, select the desired theme – in this case, IntelliJ
Click Next.
You will be presented with all the SDK components that need to be
downloaded. Click Finish.
Android Studio will start downloading the SDK components.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 246 of 309
Figure 96 ‒ Android Studio Welcome page
Now your environment should be configured and ready for Android application
development and able to run on the emulator or an actual Android device. In
the next section we will discuss how to create a new Android project.
You can open SDK Manager from the Welcome page by clicking “Configure”
on the bottom right of the screen (see
Figure 95 above).
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 247 of 309
6.1.3 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
Android Studio
SDK
SDK Manager
JDK
Android application
6.1.4 Exercises
Day 21 - Writing Android Apps with Java in the book, Sams Teach
Yourself Java in 21 days, Seventh Edition, by R. Cadenhead, ISBN:
9780672337109
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 248 of 309
6.2 Exploring the Android Studio environment
6.2.1 Introduction
Now that you have installed all the necessary applications and plug-ins, you
are going to begin writing apps. You will go through the steps involved in using
the Android Studio environment.
Open Android Studio from the Start menu -> All Apps -> Android Studio.
Before creating a new project, you have to know the following about your
application:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 249 of 309
The features of your application
The activities required
Let’s create a simple “Hello World” application. What it simply does is display
Hello World to the user, just to get the feel of programming in Android
Studio.
To create a new project, Click “Start a new Android Studio project”. This
displays a new Android Project creation screen. Type HelloWorld as the
application name and com.example as the Company domain.
Click Next.
On the Target Window, if you want to select another target under Phone
and Tablet, you can choose from the drop-down menu, but preferably leave
it as the default API 15: Android 4.0.3 (IceCreamSandwich).
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 250 of 309
Figure 99 ‒Target
Click Next.
Select “Empty Activity”, then click Next.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 251 of 309
Type HelloWorldActivity, as the ActivityName, then leave the rest and
click Next.
Click Finish.
You will be presented with the Android Studio IDE. A folder named HelloWorld
should be automatically added to the Project Explorer. Click the little arrow on
the left of the HelloWorld project folder to expand it,
helloWorld/app/src/main/java/example/com/helloworld/, and then
double-click the HelloWorldActivity.java file.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 252 of 309
Figure 102 ‒ HelloWorldActivity.java
package example.com.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world);
}
}
Example 103 ‒ HelloWorldActivity.java
This is the code generated when you open the HelloWorldActivity.java file.
This class is responsible for the interface of the application, i.e. this is the
activity that is going to display the “Hello World” text. This is what Java code
looks like. Make no changes to the code.
NOTE To expand the import section from the code above, click the little
+ circle on the left close to the import statement.
Now, alter the strings.xml file and expand the res folder from the main folder,
res/values/strings.xml.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 253 of 309
Figure 103 ‒ strings.xml
First, give the string a name, and secondly write the value of the string within
the <string> tags.
Let’s look at the following strings.xml code for the HelloWorld project:
<resources>
<string name="app_name">HelloWorld</string>
</resources>
The string from the code is the name of the application. Add another string
“hello”. This string will display the “HelloWorld” message.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 254 of 309
Save the file after you have made the changes.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 255 of 309
If you look at the interface (emulator), your application name and the “Hello
World” text is displayed. This is how your application is going to look if you run
it. On the left of the emulator on “Pallette” are all the controls you will need to
create your interface. Simply drag and drop controls to the interface or you
can add them programmatically. In this case make no changes to the file.
A window will appear which asks you to select a Deployment Target. We did
not create one before, so to create a device where our app will run, click
“Create New Virtual Device”.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 256 of 309
On the next window, select the 3.3” WQVGA Phone, and click Next.
On the Next Window, we are to select the System image we would like to use.
In our case, we will use the latest Android OS, Android 8 Oreo. Download this
Image
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 257 of 309
Once it has downloaded, select the image, and then click Next.
On the next window, you can name your Virtual Device that you created. Let
us name it MyAVD on AVD Name, as shown below:
Click Finish
NOTE If you receive a message saying “HAXM is not installed”, you can
install this using the SDK Manager. Go to Tools-> Android->SDK
Manager. Click SDK tools and find the HAXM package from list.
HAXM (Hardware accelerated execution manager) is required to
enable the emulator to run properly on your computer.
You will be returned to the Deployment target window, which will display the
Virtual Device that we created. Click OK.
The Android Emulator will launch. Wait until it finishes launching. This process
could take time, depending on the speed of your computer. Once it has
finished loading, our app will be displayed, as below:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 258 of 309
Figure 109 ‒ HelloWorld app running on emulator
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 259 of 309
6.2.3 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
Layout
Strings
Strings.xml
Target
6.2.4 Exercises
1. True/False: You can design the layout of your application from the layout
resources.
2. True/False: You can drag and drop controls on your interface when creating
an interface.
3. True/False: String resources are used when you want to display text in your
application.
Read Day 21 - Writing Android Apps with Java in the book, Sams
Teach Yourself Java in 21 days, Seventh Edition, by R. Cadenhead,
ISBN: 9780672337109
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 260 of 309
6.3 Managing application resources
As all resource types are defined by XML special tags, /res subdirectories are
created by default when a new Android project is created, for example,
/drawable, while others are added by developers when required.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 261 of 309
6.3.2 System resources
Many system resources are shared across multiple applications for a common
look as developers can access Android system resources. To retrieve a
resource string, for instance OK, you will use the static method of the Resource
class called getSystem() to retrieve the global Resource object. You will now
call the getString() method with the correct string name, as shown below:
You could use the system string by setting the appropriate string attribute as
follows:
@android:string/ok
BitmapDrawable logoBitmap =
(BitMapDrawable)getResources().getDrawable(R.Drawable.logo)
You can also create special formatted XML files to define other Drawable
subclasses such as ShapeDrawable. You will then use this subclass to define
different shapes such as circles and squares. For referencing more on the
android.graphics.drawable package you can look in the Android
documentation.
6.3.4 Files
Android projects also contain files as resources. These files are in any format
and some formats may be better than others.
For any structured data the application requires, the XML file resources is the
preferred format.
The table below shows some available XML utilities as part of the Android
platform.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 262 of 309
Table 22 ‒ XML utilities
Package Description
android.sax.* Framework to write standard SAX handlers
android.utility.Xml.* XML utilities, including the XMLPullParser
Org.xml.sax.* Core Sax functionality (see www.saxproject.org)
Javax.xml.* SAX and limited DOM, Level 2 core support
Org.w3c.dom Interfaces for DOM Level 2 core
Org.xmlpull.* XMLPullParser and XMLSerializer interfaces
(see www.xmlpull.org)
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 263 of 309
6.3.5 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
Application resources
System resources
Drawable resources
Files
Raw files
6.3.6 Exercises
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 264 of 309
6.3.8 Suggested reading
Day 21 - Writing Android Apps with Java in the book, Sams Teach Yourself
Java in 21 days, Seventh Edition, by R. Cadenhead, ISBN: 9780672337109
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 265 of 309
6.4 Building an Android application
6.4.5 Intents
A task request used by the Android operating system is encapsulated in an
intent object. The intent parameter will call the startActivity() method, and the
Android system will match the intent action with appropriate activity on the
Android system.
Intents can be used to pass data between activities and also through the use
of additional data referred to as extras.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 266 of 309
A method called putExtra() is used to package extra pieces of data, as its
name suggests, with the appropriate type of object you want to include. You
can create intent actions to initiate applications such as:
Applications may also create their own intents and give permissions to other
applications to call them, leaving room for integrated application suites.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 267 of 309
6.4.6 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
Application context
Application resources
Activities
Intents
putExtra()
6.4.7 Exercises
Read Day 21 - Writing Android Apps with Java in the book, Sams
Teach Yourself Java in 21 days, Seventh Edition, by Rogers
Cadenhead, ISBN: 9780672337109
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 268 of 309
6.5 Emulator and virtual devices
AVDs are very flexible and powerful in the sense that you can start multiple
devices at once. These devices can have different configuration settings,
making it easier and quicker for you to test your application on different
devices all at once.
The following image gives an example of what an emulator looks like when you
start to run it. This is from the example we created in section 6.2:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 269 of 309
Figure 110 ‒ Emulator loading
After it has finished loading, the emulator will look like the following
screenshot:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 270 of 309
The following table will list some of the shortcuts you can use while working
with AVDs.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 271 of 309
In the next Window, click Show Advanced Settings. You will be presented with
a variety of settings that can be edited, including the RAM size and also if you
would like to change the emulator performance.
After you press Finish you will see that a new AVD has been configured and it
is now listed under your available devices, as seen in the following screenshot.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 272 of 309
Figure 114 ‒ Available emulators
You can edit the settings of the virtual devices you created by following the
instructions described in the earlier section.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 273 of 309
6.5.3 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
Emulator
AVDs
Emulator speed
Intel emulator
Use Host GPU
6.5.4 Exercises
The following exercises must be checked by your lecturer and marked off on
the checklist at the back of this learning manual.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 274 of 309
book is available for download at: http://files.hii-
tech.com/book/Android/Beginning%20Android%20Programming%20with%20Android%20
Studio,%204th%20Edition.pdf
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 275 of 309
6.6 Designing a Graphical User Interface
Click Finish.
I interface for Android apps does not make use of Swing as Android has its
own library for widgets. Each screen displayed to a user can have a single
layout or multiple layouts. Layouts organise widgets into a table, stacking
them horizontally or vertically.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 276 of 309
An app could be represented as multiple screens:
On the left side of the screen editor is a Palette pane with subpanes that can
be expanded when you click their names. The interface widgets can be
dragged to the screen. The Form Widgets subpane has several widgets. Three
graphical buttons, named ImageButton in Android, should be added to the
screen using the following steps:
Click the widget that contains the text “Hello World”. A blue rectangle will
appear around the widget.
Press the Delete key and the widget will be removed.
Click the Images subpane to expand it.
Drag an ImageButton widget from the Palette to the screen and a
Resource Chooser dialog will appear
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 277 of 309
Choose a resource “stat_sys_phone_call” and click OK. An image button
with a dialler appears
Drag another ImageButton to widget to the screen. Assign it the resource
“ic_menu_help” and click OK.
Drag a third ImageButton to the screen. Assign it resource “ic_dialog
map” and click OK.
Click the Phone button and the properties pane appears next to the editor
with this widget’s properties displayed.
Look for “onClick” property. In its Value field enter “processClicks”.
Repeat this for the maps button.
Click the Save button.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 278 of 309
6.6.1.1 Event listeners
Event listeners are an interface in the View class that contains a single call
back method. These methods will be called by the Android framework when
the View to which the listener has been registered is triggered by the user.
Included in the event listeners interfaces are:
Onclick() – From View. OnClickListener which is called when the user either
clicks the item.
OnFocusChange() – From View.OnFocusChangeListener is called when the
user navigates onto or away from the item.
onCreateContenxtMenu().
Now on the Pallette window, click Widgets, and then drag the Button widget to
the screen. Once you have created a button, as shown in the figure below, you
can rename the title of the button by typing a different name in the text box,
under the Properties name, as shown. Let us rename the button “Click Me”.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 279 of 309
The changed value of the button will be stored in the “@string/button_nam”
but show the actual value on the button which is “Click Me”. You can refer to
the code below to see how the code will look in the xml file. This xml file can
be viewed by right-clicking on the button and selecting “Go to XML”.
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
tools:layout_editor_absoluteX="129dp"
tools:layout_editor_absoluteY="187dp" />
The button can also be called by a reference from the activity by calling
“findViewById”. The button will be retrieved from the activity since an ID is
unique in an acivity and not unique among all activities. For example, the
following is a code snippet for a closeButton.
this.closeButton = (Button)this.findViewById(R.id.close);
6.6.6.3 StringBuilder
The StringBuilder is a java class used in modifying strings. It provides a variety
of methods which might be useful in the development of Android Apps. Many
developers use the StringBuilder class in cases they want to concatenate a lot
of strings or when they want a varying length of arrays.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 280 of 309
6.6.6.4 Activity example
The example below will show how you can use a button to show your name.
The code will demonstrate how to call the text when the button is clicked. The
first snippet of code will be for the Java file showing the methods. Note that
the StringBuilder class is used.
package example.com.showname;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
Show.setOnClickListener(new View.OnClickListener() {
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 281 of 309
Example 105 ‒ ShowActivity.java
The xml file will have the button attributes as given below.
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
tools:layout_constraintTop_creator="1"
android:layout_marginStart="34dp"
android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="@+id/editText"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="34dp" />
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
tools:layout_constraintTop_creator="1"
android:layout_marginStart="34dp"
android:layout_marginTop="104dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="34dp" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your name"
tools:layout_constraintTop_creator="1"
android:layout_marginStart="34dp"
android:layout_marginTop="35dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="34dp" />
<TextView
android:id="@+id/result"
android:layout_width="108dp"
android:layout_height="48dp"
tools:layout_constraintTop_creator="1"
android:layout_marginStart="51dp"
android:layout_marginTop="18dp"
app:layout_constraintTop_toBottomOf="@+id/button"
tools:layout_constraintLeft_creator="1"
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 282 of 309
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="34dp" />
Given the above sample code, the outcome you should get after running the
code is as follows. Figure 119 below will show what the first screen where you
enter the values looks like.
After entering your name and clicking ok, the following screen will display your
name under the button “Ok”.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 283 of 309
Figure 120 ‒ Name displayed
Now that the button has been added, let’s add a toast message to it. A toast is
a message that appears for a short time and disappears without the user’s
interaction. A toast message, due to its default time which quickly makes it
disappear, can be set to a given time to display so the users can read the
message. A toast can be displayed at the bottom, middle or top of the device
screen.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 284 of 309
Toast.makeText(this,"please insert a word",Toast.LENGTH_LONG).show()
Example 107 ‒ ButtonClick example
Once you have implemented the toast message code, you should see the
illustration below of a toast message which says, “Please insert a word”.
Create a new Android Studio Project and name the app NumCombiner.
Choose Target as API 15 and click Next.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 285 of 309
Select Empty Activity, and then click Next.
Type NumberCombiner as the ActivityName, and then click Finish.
We are making use of the constraint layout. Make sure you click “infer
constraints” for your widgets to be fixed on their respective positions where
you have placed them. The icon is the one circled in Figure 112 above.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 286 of 309
You can increase the text size of the widgets you have added by using the
Android text size, as shown below:
android:textSize="20dp"
The above will set the text size for the respective widget to 20 dp. The xml file
will have the button attributes as given below.
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="39dp"
android:layout_marginStart="39dp"
android:layout_marginTop="62dp"
android:text="Enter the first number"
android:textSize="20dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1"
tools:text="Enter the first number" />
<EditText
android:id="@+id/num1"
android:layout_width="123dp"
android:layout_height="49dp"
android:ems="10"
android:inputType="number"
app:layout_constraintRight_toLeftOf="@+id/btncombine"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toTopOf="@+id/textView2"
android:layout_marginTop="23dp"
app:layout_constraintTop_toBottomOf="@+id/textView1"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="23dp"
app:layout_constraintLeft_toLeftOf="@+id/textView1"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintVertical_bias="0.0"
tools:layout_editor_absoluteY="98dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="244dp"
android:layout_height="46dp"
android:layout_marginBottom="83dp"
android:layout_marginEnd="1dp"
android:layout_marginRight="1dp"
android:layout_marginTop="84dp"
android:text="Enter the second number"
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 287 of 309
android:textSize="20dp"
app:layout_constraintBottom_toTopOf="@+id/btncombine"
app:layout_constraintLeft_toLeftOf="@+id/num1"
app:layout_constraintRight_toRightOf="@+id/btncombine"
app:layout_constraintTop_toBottomOf="@+id/textView1"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1"
tools:text="Enter the second number"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="@+id/num2"
android:layout_width="119dp"
android:layout_height="42dp"
android:ems="10"
android:inputType="number"
app:layout_constraintRight_toLeftOf="@+id/result"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="@+id/textView2"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintVertical_bias="0.501" />
<Button
android:id="@+id/btncombine"
android:layout_width="173dp"
android:layout_height="51dp"
android:layout_marginBottom="47dp"
android:layout_marginTop="53dp"
android:text="Combine"
android:textSize="20dp"
app:layout_constraintBottom_toTopOf="@+id/result"
app:layout_constraintHorizontal_bias="0.369"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@+id/num2"
app:layout_constraintVertical_bias="0.0"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1"
tools:text="Combine" />
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 288 of 309
android:layout_marginStart="21dp"
android:textSize="20dp"
tools:layout_editor_absoluteY="109dp"
tools:layout_editor_absoluteX="304dp" />
Example 108 ‒ XML file
After setting up the respective widgets on our app, it is now time to write the
code. Edit your NumberCombiner.java to be shown as follows.
package example.com.numcombiner;
//its necessary to import the widgets so as to make use of the
them in the code.
import android.app. support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 289 of 309
}
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 290 of 309
Figure 123 ‒ NumCombiner app
Depending on your computer speed, you will have to wait a few minutes for
the emulator to boot up.
Enter the two numbers, and click Combine. The output will be as follows:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 291 of 309
Figure 124 ‒ Testing NumCombiner app
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 292 of 309
Figure 125 ‒ Toast message displayed
As an exercise, you could try to include a method to add or subtract the two
numbers. This would mean that you have to modify the NumberCombiner.java
file in a way that the numbers get added or subtracted.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 293 of 309
6.6.3 Key terms
Make sure that you understand the following key terms before you
start with the exercises.
Widgets
Event listeners
Layouts
Component tree
6.6.4 Exercises
1. With the Number App you have just created, modify it so that the
background is an image. The image can be any image of your choice.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 294 of 309
6.7 Test your knowledge
4. Look at the following code and re-write it correcting the error in the code.
<string name>Matthew</string>
7. Which of the following resources are compiled into the application package
at build time and are available to the application?
a) Drawable resources
b) Application resources
c) System resources
d) Files
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 295 of 309
Projects
This project will test your understanding of all the sections covered in
this unit and the previous units. You can choose any one of the
projects given (consult your lecturer). A mark sheet for each project will also
be provided.
You do not have to supply user documentation for your project, only
documentation on how to set up and run your program. All your project
content must be handed in digitally (you do not need to print anything out) on
a CD or flash disk (which will be handed back to you after marking).
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 296 of 309
Project 1 – Forum
Website specification:
This part must be written in JSPs and servlets, and should present the user
with interfaces to satisfy the following needs:
The user must be able to sign up by providing their email address and a
password, and other personal information. If their password is forgotten,
they must be able to securely change their password.
A logon facility is required. In case the user has forgotten their password,
they must have the option to change it, as long as they can prove that they
are the original user.
Once the user has logged on, a facility to view topics and comments must
be provided. If a topic is selected, its relevant details and the comments
must be displayed, including any replies that were posted.
The user must be able to post a comment themselves, or post a reply to
another user’s comment.
The user must be able to change their personal information.
A logoff facility is required for the user to end their session.
Database specification:
The following functionality must be made available through the Web service:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 297 of 309
NOTE Do some research of your own to get an idea of how forum sites
work. Use your creativity as much as you can, but keep
everything professional and straightforward. The layout of each
interface should be simple enough to follow, yet include all the
required functionality.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 298 of 309
Project 1 Mark Sheet
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 299 of 309
Try/catch blocks used to catch exceptions 2
Subtotal: 10
User interface
Eye-pleasing form design – all controls neatly lined 2
up, no garish colour schemes
Appropriate controls used to present information 2
Navigation is intuitive and efficient 2
Information fits on screen properly (no horizontal 2
scrolling)
Errors are handled and presented properly 2
Subtotal: 10
Penalties
No Web service used or project incomplete Resubmit
Program does not compile -10
Program does not run or causes unhandled exceptions -10
during execution or user input
Project setup documentation not handed in -10
Project returned and resubmitted -10
Project copied -20
General comments
Total: 100
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 300 of 309
Project 2 – Antique Auctions
Antique Auctions is a company that deals in antiques. The owners would like to
develop a system that allows customers to bid on items of their choice, similar
to eBay. This would require a website for customers to use, a database
containing customer information, products and bid information, and a Web
service, used by the website, to interact with the database.
Website specification:
This part must be written in JSPs and servlets, and should present the
customer with interfaces to satisfy the following needs:
Database specification:
The following functionality must be made available through the Web service:
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 301 of 309
Bid information additions.
Any other functionality required by the website.
Each time a bid is made, write the applicable information to a log file.
NOTE Do some research of your own to get an idea of how auction sites
work. Use your creativity as much as you can, but keep
everything professional and straightforward. The layout of each
interface should be simple enough to follow, yet include all the
required functionality.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 302 of 309
Project 2 Mark Sheet
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 303 of 309
All variables and methods named in accordance with 2
JavaBeans naming standards
Try/catch blocks used to catch exceptions 2
Subtotal: 10
User interface
Eye-pleasing form design – all controls neatly lined 2
up, no garish colour schemes
Appropriate controls used to present information 2
Navigation is intuitive and efficient 2
Information fits on screen properly (no horizontal 2
scrolling)
Errors are handled and presented properly 2
Subtotal: 10
Penalties
No Web service used or project incomplete Resubmit
Program does not compile -10
Program does not run or causes unhandled exceptions -10
during execution or user input
Project setup documentation not handed in -10
Project returned and resubmitted -10
Project copied -20
General comments
Total: 100
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 304 of 309
Exercise Checklist
(MLAJ185-01)
A lecturer must sign next to each section to confirm that you have completed
all the exercises provided in this learning manual. The exams for the first two
units may only be written after the exercises for the respective units have
been checked. Only once the entire checklist is complete may you hand in your
project for marking and write the final unit’s examination.
Unit 4 sections
4.1 HTML Exercises
4.2 Introduction to Exercises
JavaServer Pages Revision questions
4.3 Servlets Exercises
Revision questions
4.4 Programming JSP Exercises
scripts Revision questions
4.5 Implicit objects, Exercises
actions and scope Revision questions
4.6 JavaBeans and JDBC Exercises
Revision questions
4.7 Custom tag libraries Exercises
Revision questions
4.9 Compulsory exercises Exercise
4.10 Test your knowledge Questions
Unit 5 sections
5.1 Introduction to XML Exercises
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 305 of 309
5.9 Compulsory exercises Exercise
5.10 Test your knowledge Questions
Unit 6 sections
6.1 Android Studio Exercises
installation
6.2 Exploring the Android Exercises
Studio environment
6.3 Managing application Exercises
resources Revision
questions
6.4 Building Android Exercises
applications
6.5 Emulator and Virtual Exercises
Devices Revision
questions
6.6 Emulator and virtual Exercises
devices Revision
questions
6.7 Test your knowledge Questions
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 306 of 309
Glossary
Term Description
HyperText Markup Language. Which is a set of
HTML symbols and codes used in creating web pages for
display on the World Wide Web.
Java Server Pages, is a technology that is used for
JSP the development of applications that generate
dynamic web content
Servlet Is a Java class used to extent the server
capabilities through a request-response model.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 307 of 309
References
Textbooks
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 308 of 309
Advanced Java Programming Evaluation Form
(MLAJ185-01)
How would you evaluate the (Advanced Java Programming) learning manual? Place a or in
one of the five squares that best indicates your choice. Your response will help us to improve
the quality of the syllabus and will be much appreciated.
Please note any errors that you found in the learning manual.
Please remove this evaluation form and return it to your lecturer or senior lecturer so that it
can be forwarded to the Division for Courseware Development.
Thank you.
MLAJ185-01 Advanced Java Programming Learning Manual | V1.0 April 2018 Page 309 of 309
CTI is part of Pearson, the world’s leading learning company. Pearson is the corporate owner, not a registered
provider nor conferrer of qualifications in South Africa. CTI Education Group (Pty) Ltd. is registered with
the Department of Higher Education and Training as a private higher education institution under the
Higher Education Act, 101, of 1997. Registration Certificate number: 2004/HE07/004. www.cti.ac.za.