Professional Documents
Culture Documents
Chapter 07
J2ME and Enterprise Computing
7.1 Objectives
In this section, we will be learning how to write Servlets, use JSP and JSTL, access a
database using JDBC and create and parse XML documents.
After finishing this lesson, the student should be able to:
write simple Servlets
write simple JavaServer Pages (JSP) using JSTL
write JSTL code using Expression Language (EL)
access a database using JDBC
generate XML
parse the XML on the Mobile client
7.2 Servlets
A servlet is a server-side Java class for implementing a request-response type transaction.
With servlets, Java provides a better and portable alternative to CGI (Common Gateway
Interface) scripts. Compared to CGI scripts (written in Perl, sheel scripts, or other scripting
languages), Java servlets provide a scalable, platform dependent technology that deliver
dynamic content.
A servlet has two methods for processing a request, the doGet() and doPost() methods.
These methods are called when the web client (browser) issues a "GET" or "POST"
command. These methods have identical parameters. These parameters are normally
handed off to a common method so that both GET and POST request are handled the same
way.
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// process request ...
}
J.E.D.I.
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SampleServlet</title>");
out.println("</head>");
out.println("<body>");
out.close();
}
J.E.D.I.
processRequest(request, response);
}
processRequest(request, response);
}
J.E.D.I.
To create a new Web Project, click File -> New Project... ->Web: Web Application. Select
and input a name for your project and click finish.
J.E.D.I.
To create a new Servlet, click on File -> New File.. -> Web: Servlet
J.E.D.I.
7.3 JSP/JSTL
The primary goal of the JavaServer Pages Standard Tag Library (JSTL) is to help authors
simplify scripting on JSP pages. JSTL briges the gap between programmers and (nonprogrammer) page authors by providing a simple expression language for JSP pages.
Aside from the expression language support actions and crontrol flow actions, JSTL also
provides functionality for accessing URL-based resources, internationalization and number
and date formatting, database access and XML processing.
JTSL is composed of several tag libraries, grouped by functional area.
Area
Prefix
URI
core
http://java.sun.com/jstl/core
<c:out value="${var}"/>
I18N formatting
fmt
http://java.sun.com/jstl/fmt
<fmt:formatNumber
XML processing
http://java.sun.com/jstl/xml
<x:forEach ...
Database (SQL)
sql
http://java.sun.com/jstl/sql
<sql:query var=...
Functions
fn
http://java.sun.com/jstl/functions <fn:
7.3.1
Configuration
To be able to use JSTL tags, the taglib directive should be included in the JSP page, one
each for every functional area that will be used in that page.
You should also include the jstl.jar into your project's library folder:
1. Right click on the Libraries folder of your project and select "Add Library" from the pop-
J.E.D.I.
up menu:
2. Select "JSTL 1.1" and click "Add Library". "JSTL 1.1 standard.jar" and "STL 1.1
jstl.jar" would be added to your projects library.
J.E.D.I.
7.3.2
Hello, world!
A JSP page is just an HTML page with codes and/or tags. Here is a very minimal JSP page.
Save this code snippet to hello.jsp under the Web Pages directory, right click on the
filename and choose "Run File" to display the output of this JSP page in your web browser:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<h1><c:out value="${message}"/></h1>
</body>
</html>
J.E.D.I.
7.3.3
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
J.E.D.I.
processRequest(request, response);
}
processRequest(request, response);
}
10
J.E.D.I.
7.3.4
7.3.4.1
Expression Language
Accessing Variables, Properties and Collections
<c:out value="${username}"/>
JSTL unifies access to Java bean properties and collection values. The expression varX.varY
is equivalent to varX[varY] in JSTL. The expression varX.varY (or varX[varY]) would
evaluate depending on the type of varX:
1. If varX is a JavaBean: varY would be converted to String. If varY is a readable property
of varX, it would return the result of the getter call: varX.getVarY()
2. If varX is a List: varY is coerced to int. Evaluates to: varX.get(varY)
3. If varX is an array: varY is coerced to int. Evaluates to: Array.get(varX, varY)
4. If varX is a Map: Evaluates to: varX.get(varY)
Variables can have page, request, session and application scope. The expression language
Mobile Application Development
11
J.E.D.I.
would look for the identifier in these scopes. If the identifier is not found, null is returned.
7.3.4.2
Implicit Objects
JSTL automatically initializes several Map variables with values from different sources.
These variables are available to the JSP pages without any initialization from the user. For
example, the variable param contains mappings of parameters' names and values from
the request. These names and values (param) are from HTML form submissions submitted
either via HTTP GET or POST methods.
Implicit Object
Contents
pageScope
requestScope
sessionScope
applicationScope
param
header
cookie
7.3.4.3
Operators
The JSTL Expression Language (EL) supports relational, arithmetic and logical operators.
The supported relational operators are:
== (or eq)
!= (or ne)
< (or lt)
> (or gt)
<= (or le)
12
J.E.D.I.
The additional empty operator is very useful for testing null or empty values.
7.3.4.4
To simplify JSP pages, simple errors will not generate exceptions. Displaying a variable
with a null value will simply display "(null)" instead of generating a
NullPointerException.
Username:
<input
type="text"
value="<c:out value="${param.username}"/>"
name="username" />
Undefined variables used in expressions take 0 (zero) as their default value. This
expression would evaluate to 1 if the parameter "start" is not set:
7.3.5
7.3.5.1
13
J.E.D.I.
Name
Dynamic Required
Type
Description
value
yes
yes
Object
escapeXml
yes
no
boolean If true, the characters <, >, &, ' and " are
converted to their character entity codes
(eg: > converts to >). Default value is
true.
default
yes
no
Object
Examples:
Description:
<pre>
<c:out value="${bookmark.description}" escapeXml="false" />
</pre>
7.3.5.2
c:set
<c:set
value="value"
var="varName"
[scope="{page|request|session|application}"]
/>
14
J.E.D.I.
Name
Dynamic Required
Type
Description
value
yes
yes
Object
var
no
yes
String
scope
no
no
String
Example:
7.3.5.3
c:remove
<c:remove
var="varName"
[scope="{page|request|session|application}"]
/>
Name
Dynamic Required
Type
Description
var
no
yes
String
scope
no
no
String
Example:
7.3.5.4
c:if
Conditional evaluation. Will process the body content if the test condition evaluates to
true.
Syntax:
15
J.E.D.I.
<c:if test="testCondition"
[var="varName"] [scope="{page|request|session|application}"]>
body content
</c:if>
or
<c:if test="testCondition"
var="varName" [scope="{page|request|session|application}"]
/>
Name
Dynamic Required
Type
Description
test
yes
yes
var
no
no/yes
String
scope
no
no
String
Example:
7.3.5.5
The c:choose is like the Java switch statement, providing a mutually exclusive conditional
execution. The body content of c:otherwise (if it exists) will be evaluated if no when
statement evaluates to true. The otherwise block must be the last in the choose statement
(cannot be followed by another c:when). It must also be preceded by at least one c:when
statement.
Syntax:
<c:choose>
<c:when test="condition">
body content
</c:when>
[
<c:when test="condition">
body content
</c:when>...
]
16
J.E.D.I.
[
<c:otherwise>
body content
</c:otherwise>
]
</c:choose>
Name
test
Dynamic Required
yes
yes
Type
Description
Example:
<c:choose>
<c:when test="${gender eq 'M'}">Male</c:when>
<c:when test="${gender eq 'F'}">Female</c:when>
<c:otherwise>Unknown</c:otherwise>
</c:choose>
7.3.5.6
c:forEach
c:forEach iterates over the contents of a collection. The collection can be any of the
subclasses of java.util.Collection and java.util.Map. Arrays of objects and primitive types
are also supported. A String of comma separated values ("True,False") can also be used
for the iteration. As long as there are items in the collection, the body content is processed.
c:forEach can also be used to iterated for a fixed number of times.
The varStatus is of type javax.servlet.jsp.jstl.core.LoopTagStatus. It has the
properties index (index of the current iteration, zero-based) and count (the count of the
current iteration, one-based, eg. if the begin index is 20, the end index is 80 and the step
is 10, the count would be 1,2,3,4,5,6,7). The boolean properties first and last denote if
the currrent iteration is the first or last, respectively. There are also the begin, end and
step properties which hold the values of the begin, end and step parameters of the
c:forEach loop.
Syntax:
<c:forEach
[var="varName"]
items="collection"
[varStatus="varStatusName"]
[begin="begin"] [end="end"] [step="step"]
>
body content
17
J.E.D.I.
</c:forEach>
or
<c:forEach [var="varName"]
[varStatus="varStatusName"]
begin="begin" end="end" [step="step"]
>
body content
</c:forEach>
Name
Dynamic Required
Type
Description
var
no
no
varies
items
yes
yes/no
varStatus no
no
String
begin
yes
no/yes
int
end
yes
no/yes
int
step
yes
no
int
Example:
<select name="gender">
<c:forEach var="gender" items="${genderList}">
<option value="<c:out value="${gender.code}"/>">
<c:out value="${gender.name}"/>
</option>
</c:forEach>
</table>
18
J.E.D.I.
7.3.5.7
c:forTokens
<c:forTokens
items="stringOfTokens"
delims="delimiters"
[var="varName"]
[varStatus="varStatusName"]
[begin="begin"] [end="end"] [step="step"]
>
body content
</c:forTokens >
Name
Dynamic Required
Type
Description
var
no
no
varies
items
yes
yes
String
String of tokens
delims
yes
yes
String
varStatus
no
no
String
begin
yes
no
int
end
yes
no
int
step
yes
no
int
Example:
<select name="gender">
<c:forEach var="gender" items="Male,Female" delims=",">
<option value="<c:out value="${gender}"/>">
<c:out value="${gender}"/>
</option>
19
J.E.D.I.
</c:forEach>
</table>
7.4 JDBC
In this section, we will be discussing how to persist data or objects. For this functionality,
we will need a (relational) database. The JDBC API lets you perform queries and updates
on a database. Before we can use JDBC, we need to make sure that three prerequisites
are met:
JDBC library - included in the JDK
The Database Server - we will use MySQL (mysql.com)
JDBC Driver - comes with your DBMS, install the jar mysql-connector-java-3.x.x-bin.jar
The table used in these examples can be recreated using this SQL CREATE AND INSERT
statements:
(`id`)
);
20
J.E.D.I.
(3,'update row',8,'you','0');
7.4.1
To use the JDBC driver for a particular database, we have to load it using Class.forName().
The driver name is dependent on the database driver that we will be loading. In our case,
we are loading the mysql jdbc driver:
7.4.2
Establishing a Connection
To establish a connection to the database, we will need the URL to the database. We will
also need access to that database. A working username and password are required to
establish a connection.
7.4.3
executeQuery returns a ResultSet object. To iterate on all the rows returned by the query,
we use the next() method. There are several methods that return the columns of the
current row, each for a specific datatype. In this example, we retrieved String and integer
variables using getString() and getInt():
statement = conn.createStatement();
String query = "SELECT task,duration,duration FROM task";
ResultSet rs = statement.executeQuery(query);
out.println("<table>");
out.println("<tr>");
out.println("<th>Task</th>");
out.println("<th>Duration</th>");
out.println("<th>Assigned to</th>");
out.println("</tr>");
while (rs.next()) {
21
J.E.D.I.
out.println("<tr>");
out.println("<td>" + task + "</td>");
out.println("<td>" + duration + "</td>");
out.println("<td>" + duration + "</td>");
out.println("</tr>");
}
out.println("</table>");
7.4.4
Updating tables
22
J.E.D.I.
statement.executeUpdate(updateQuery);
7.5 XML
XML, the eXtensible Markup Language, is a text-based markup language. With XML, you
can present data in a structured text document.
Just like HTML, XML tags are defined using the angled brackets: <>. Unlike HTML though,
XML is easier to parse. An XML document is structured, with entities forming a tree
structure.
You can use any appropriate tag name that you like, as long as all the applications using
the XML document will use the same tag names. Tags can contain attributes. In the
example below, the first "task" has an "id" attribute of "1" while the second "task" has an
"id" attribute of "2".
<tasks>
<task id="1">
<name>connect to database</name>
<duration>2</duration>
<assignedTo>alex</assignedTo>
<status>0</status>
</task>
<task id="2">
<name>list table rows</name>
<duration>4</duration>
<assignedTo>alex</assignedTo>
23
J.E.D.I.
<status>4</status>
</task>
</tasks>
7.5.1
Parsing XML
As of the time of this document's writing, there have been no standard libraries defined
by a JCP process for parsing XML in CLDC. However, there are several XML libraries that
work with CLDC. One of them is NanoXML (http://nanoxml.sourceforge.net/). The original
version of NanoXML does not work with CLDC. You must download the source code of the
modified version that works with CLDC at http://www.ericgiguere.com/nanoxml and
include it in your mobile project under the package name "nanoxml".
import java.io.*;
import java.util.*;
import nanoxml.*;
...
24
J.E.D.I.
kXMLElement prop =
(kXMLElement) taskProperties.elementAt(j);
String propTagName = prop.getTagName();
if (propTagName != null){
for (int p=0; p<fieldNames.length; p++){
if (propTagName.equalsIgnoreCase(
fieldNames[p])){
fields[p] = prop.getContents();
}
}
}
}
7.6 Exercises
7.6.1
Write a JSTL code that will iterate over the implicit Map "header" and display the header
key/name and value in an HTML table. Odd numbered rows should have the background
color of lightyellow (<tr bgcolor="lightyellow">...). Note that the varStatus index start
with zero. Note that the (header) Map has the property "key" and "value".
Sample Output:
acceptencoding
gzip,deflate
25
J.E.D.I.
connection
keep-alive
acceptlanguage
en-us,en;q=0.5
host
localhost:8084
accept-charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
user-agent
Mozilla/5.0 (Linux;
Firefox/1.2.3
accept
text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/pl
ain;q=0.8,image/png,*/*;q=0.5
keep-alive
300
7.6.2
U;
Linux
v0.99;
en-US)
Gecko/20050511
Create a servlet and JSTL application that will display in XML format an array of objects.
The object properties are: name and ip address. The Java class should look like this:
public class Host {
private String name;
private String ip;
Host[] hosts = {
new Host("localhost", "127.0.0.1"),
new Host("java.sun.com", "1.2.3.4")
};
26
J.E.D.I.
<hosts>
<host name="localhost">
<ip>127.0.0.1</ip>
</host >
<host name="java.sun.com">
<ip>1.2.3.4</ip>
</host >
</hosts>
27