Download Lecture 3: Introduction to JSP

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CPAN423 Enterprise Java Programming
Lecture #3: An Introduction to JSP
JSP is a server side scripting language based on Java language with support for
creating database driven application. It enables developers to insert Java code
inside HTML pages to generate Dynamic Web sites. The extension of such files
must be (.jsp) instead of (.html).
JSP pages are multi platform ,high level extension of servlets. They are finally
compiled into a servlet by the JSP engine and loaded into the web server
memory upon receiving the request to the JSP page for the first time.
Subsequent calls to that page will be served faster. The compilation process
happens once every time a new JSP page loaded.
javax.servlet.jsp package defines two interfaces: JSPPage and HttpJspPage.
The JspPage interface is implemented by all jsp servlet classes. It has two
methods: jspInit and jspDestroy. These methods are analogous to the init and
destroy methods of the servlet.
The HttpJspPage interface extends the JspPage interface. It has one method
_jspService. This method is called by the container to generate the content pf
the jsp. We cannot include this method in the jsp. The page content represents
this method. Programmer can define jspInit() and jspDestroy() methods, but the
_jspService(HttpServletRequest
request,HttpServletResponse
response)method is generated by the JSP engine.
The JspFactory class is an abstract class provides methods for obtaining other
objects needed for the jsp page processing.
The JspEngineInfo abstract class provides info about the jsp engine. Only one
method is available called getSpecificationVersion.
The abstract class PageContext provides methods used to create other objects.
For example: getSession, getRequest,getResponse,getServletConfig,
getServletContext
The JspWriter class is derived from the java.io.Writer class and represents a
writer to send info to the client. Other methods allow you to manipulate the buffer.
The page object represents the HttpJspPage interface. The config object
represent ServletConfig. pageContext represent the PageContext
JSP original style tags
There are four main tags in JSP:
1-Directive:
A JSP directive gives special information about the page to the JSP Engine.
1
Directives do not produce any visible output when the page is requested but
change the way the JSP Engine processes the page.
In the directives we can import packages, define error handling pages or the
session information of the JSP page.
There are three main types of directives:
1-1 Page directive: defines attributes that apply to a JSP page. The following
attribute appear in the page directive:
language: defines the language the file uses (currently always java). It has the
syntax:
<%@ page language=”java” %>.
extends: defines the super class used by the JSP engine for the translated
Servlet. It has the syntax:
<%@ page extends = “…” %>
import defines all the classes to be imported, separated by comma. For example
<%@ page import = “java.util.*,java.io.*” %>
session: Determines whether a session object will have to be defined, the default
is true. For example:
<%@ page session = “false” %>
buffer: Controls the size of the response output buffer. The size can be none or a
size, the default is 8kb.For example:
<%@ page buffer = “none” %>
autoFlash: Can be either true( the default) or false. If it is set to false an overflow
of the buffer will causes an exception. If it is set to true the buffer will be flushed
to the output stream when get full. This attribute must be set to false if buffet set
to none. For example:
<%@ page autoFlush = “true” %>
isThreadSafe: Determine whether the generated servlet deal with multiple
requests. It can be either true or false, the default is true. When set to false the
JSP engine will allow only one request to be processed at any time. When true
more than one request thread can run at the same time. For example:
<%@ page isThreadSafe="false" %>
The following code is note thread safe
<%! int i=0; %>
<%i=i+1 ;%>
To make it thread safe:
<%! int i=0; %>
<%
synchronize(this) {
i=i+1;
}
%>
2
Another example:
synchronized ( myVector)
{
myVector.removeElementAt(0);
}
By using synchronize(objectName) {} we indicate that no thread can
access the code until the current one exits.
info: Defines a string value that can be accessed in the code using
getServletInfo() method. Typiaclly used to add author information. For example:
<%@ page info = “ this is test page, copyright 2001. “ %>
errorPage: If present the value defines a URL of a resource that will be send
any Exception or Error object that is not caught in the java code of the page. For
example:
<%@ page errorPage = “error.jsp” %>
isErrorPage: If set to true the current page is the target of another page’s
errorPage URL and the page has access to the implicit object exception. For
example:
<%@ page isErrorPage = “true” %>
contentType:Set the MIME( multipurpose Internet media Extension) type and
character set of the JSP page as used in the ServletResponse setContentType
method. The default is “text/html:charset=ISO-8959-1”
<%@ page contentType = “text/html:charset=ISO-8959-1” %>
1-2 Include directive:
Allows a JSP developer to include contents of a file inside another. Typically
include files are used for navigation, tables, headers and footers that are
common to multiple pages. This file can be html, JSP or any thing else. for
example:
<%@ include file="hello.jsp" %>
1-3 Taglib directive:
The taglib directive allows you to define a library of custom action tags that will
be used in the page. Custom tags use interfaces and classes in the
java.servlet.jsp.tagext package. It has the following syntax :
<%@ taglib uri = “tag library URI” prefix = “tag Prefix” %>
Each tag-library will have its own tag-library specific documentation. In order to
use the tag library, you use the "taglib" directive to specify where your tag
library's "description" resides.
2-Declarations
This tag is used for defining the functions and variables to be used in the JSP.
3
Declarations are found within the <%! ... %> tag. Always end variable
declarations with a semicolon, as any content must be valid Java statements
Declarations do not generate output so are used with JSP expressions or
scriptlets.
JSP declarations let you define page-level variables to save information or define
supporting methods that the rest of a JSP page may need. For example:
<%! int i=0; public void someFunction(String arg)
{
// java code
}
%>
3-Scriplets
Between <% and %> tags, any valid Java code is called a Scriptlet. This code
can access any variable or bean declared. The code is placed in _jspService
method by the JSP engine.for example:
<%
// java codes
%>
You can mix scriptlets and HTML to make scriptlet generate HTML , for example
:
<%! int i=0; %>
<%
if ( i==0 ) {
%>
<P>it is true
<%
} else {
%>
<P>it is false;
<%
}
%>
By itself a scriptlet does not generate HTML. If a scriptlet wants to generate
HTML, it can use “ out.println" inside the scriptlet as shown in the following
example:
<%@ import="java.io.*,java.util.*" %>
<%
for (int i = 1; i < 6; i++)
{
out.println(i + "<BR>");
}
%>
4
4-Expressions
This tag allows the developer to embed any Java expression and is short for
out.println(). A semicolon does not appear at the end of the code inside the tag.
We can use this tag to output any data on the generated page. These data are
automatically converted to string and printed on the output stream.
Syntax of JSP Expressions are:
<%="Hello World" %>
Implicit Objects
The JSP container makes available implicit objects that can be used within
scriptlets and expressions. These objects act as wrappers around underlying
Java classes or interfaces typically defined within the Servlet API.
Note that these implicit objects are only visible within the system generated
_jspService(HttpServletRequest request,HttpServletResponse response )
method. They are not visible within methods you define yourself in declarations.
There are four levels of objects scope:
Application: Objects accessible from pages that belong to the same application.
Session: Objects accessible from pages belonging to the same session as the
one in which they where created
Request: Objects accessible from pages processing the request where they
were created
Page: Objects accessible only within pages where they were created.
The implicit objects are:
1-page
page object is of type java.lang.Object and has page scope .It represents the
current JSP page( synonym for the "this" operator).It is used to call any methods
defined by the servlet class.
2-config
config object is of type javax.servlet.http.ServletConfig and has page scope. It
represents the configuration data. It stores the servlet initialization parameter
name value pairs and the servletContext object
3-request
request object is of type javax.servlet.http.httpservletrequest and has request
scope. It represent the user request send through the browser to the server.
As a part of the request, various data is available, including the file the browser
wants from the server, and if the request is coming from pressing a SUBMIT
button, the information the user has entered in the form fields.
4-response
response object is of type
javax.servlet.http.httpservletresponse and has
page scope. It represent the output respond to the browser.
5-pageContext
pageContext object is of type javax.servlet.jsp.pagecontext and has page
scope. It Contain attribute about the page
6-session
5
session object is of type javax.servlet.http.httpsession and has session scope.
It contains arbitrary variables attached to the session user.
7-application
application object is of type javax.servlet.http.ServletContext and has
application scope. It contains attribute for the entire application
8-out
out object is of type javax.servlet.jsp.JspWriter that writes into the output
stream for the response. It has page scope.
9-exception
exception object is of type java.lang.Throwable .Only pages that are designated
as error pages in the page directive have this object. It has page scope.
Comments in JSP
JSP allows for different styles of comments:
<%-- JSP style comment %> this comment will appear in the JSP page but it
will be skipped by the JSP engine ,so it doesn’t appears in the resulting java
code.
<% // java style comment // %> or <% /* java style comment */ %> this
comment will appear in the JSP page and the resulting java code created by JSP
engine but not in the output page.
<!-- HTML style comment --> ,this comment will be transmitted with the output
page but not displayed.
A jsp:text element is used to enclose template data in the XML
representation. The interpretation of a jsp:text element is to pass its content
through to the current value of out For example:
<jsp:scriptlet>
I=0;
</jsp:scriptlet>
<jsp:text> This is a comment placed here </jsp:text>
<jsp:expression>I </jsp:expression>
The output would be
This is a comment placed here
Exception Handling
JSP provides a rather elegant mechanism for handling runtime exceptions.
Although you can provide your own exception handling within JSP pages, it may
not be possible to anticipate all situations. By making use of the page directive's
errorPage attribute, it is possible to forward an uncaught exception to an error
handling JSP page for processing. For example,
<%@ page isErrorPage="false" errorPage="errorHandler.jsp" %>
6
informs the JSP engine to forward any uncaught exception to the JSP page
errorHandler.jsp. It is then necessary for errorHandler.jsp to flag itself as a error
processing page using the directive:
<%@ page isErrorPage="true" %>
This allows the Throwable object describing the exception to be accessed within
a scriptlet through the implicit exception object.
Integrating Servlets and JSP
To let a servlet forward request to a JSP we have to obtain a
RequestDispatcher object by calling getRequestDispathcer method of
ServletContext, supplying a URL relative to the servlet root. Once we have a
requestDispatcher object we use forward method to completely transfer control
to the associated URL.
Using JavaBeans with JSP
JavaBeans can be also used on the serve side. Following is a review of
the requirement for a server side JavaBean class:
 The class must be public, and must implement Serilizable interface.
 The class must have a no argument constructor.
 The class must provide public set and get methods to access
private member variables of the bean class.
 After you compile your class, you can use it in your JSP code, using
the <jsp:useBeans /> tag. The place to put your javabean classes
depends on the server you are running.
The bean scope attribute defines the accessibility and the life span of
the bean. Page value indicate that the bean is available only in the
current page after the point where the jsp:Bean is used. The request
value indicates that the accessibility of the bean is extended to the
forwarded and included pages. The session value indicates that the
bean is placed in the session object and continues to exist as long as
the session object is valid. The application value indicates that the bean
lives through the life cycle of the jsp container itself.
We can use jsp:getProerpty and jsp:setProperty as follows:
<jsp:useBean id=”b1”/>
<jsp:setProperty name=”b1” property=”” value=”” />
jsp:Bean allows us to write code that will execute after the bean is
initialized.
7
<jsp:useBean>
Some code
</jsp:useBean>
Examples
To run the following examples, refer to the deployment procedure described in
lecture 2.
Ex1: greeting.jsp:
In this example we will show greeting message and the current date and time.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSP page</title>
</head>
<body>
<%!
java.util.Date date = new java.util.Date();
String message="Greeting from JSP";
%>
<%
out.println(message);
out.println("The time is now "+date);
%>
</body>
</html>
Here variables date and message will be declared once and the output will be
the same for every request for the page..
The JSP file should be saved in the folder:
resin-x.x.x\webapps\cpan423
To invoke this JSP file from the deployment folder, type the following URL:
http://localhost:8080/cpan423/greeting.jsp
Ex2:greeting1.jsp:
In this example we are doing the same as Ex1 but using scriptlet:
8
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSP Page</title>
</head>
<body>
<%
java.util.Date date = new java.util.Date();
String message="Greeting from JSP";
%>
<%= message %>
<br />
The time is now <%= date %>
</body>
</html>
In Contrary to Ex1 the variables date and message will be re declared each time
the page will be requested, meaning the time specifically will be changing every
time the page will be requested.
The JSP file should be saved in the folder:
resin-x.x.x\webapps\cpan423
To invoke this JSP file from the deployment folder, type the following URL:
http://localhost:8080/cpan423/greeting1.jsp
Ex3:requestInfo.jsp:
In this example we will show some information about the request object:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>request information</title>
</head>
<body>
<%!
java.util.Date date = new java.util.Date();
%>
<%
out.println("The date is " + date );
out.println( "<BR>Your machine's address is " );
out.println( request.getRemoteHost());
9
out.println( "<BR>the name of the authentication scheme used to protect
the servlet is ") ;
out.println( request.getAuthType());
out.println( "<BR>the HTTP method is ") ;
out.println( request.getMethod());
out.println( "<BR>the request URI is ") ;
out.println( request.getRequestURI());
%>
</body>
</html>
The JSP file should be saved in the folder:
resin-x.x.x\webapps\cpan423
To invoke this JSP file from the deployment folder, type the following URL:
http://localhost:8080/cpan423/requestInfo.jsp
Ex4:tableGenerator.jsp:
In this example we will use JSP to generate a table dynamically
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Table generator</title>
</head>
<body>
<%@ page language="java" %>
<%!
String array[][]={{"first cell","second Cell","third Cell"},
{"1","2","3"},{"10","20","30"}};
String color[]={"#ff0000","#00ff00","#0000ff"};
%><%
out.println("<table border='1'>");
for(int i=0;i<array.length;i++)
{
out.println("<tr>");
for(int j=0;j<array[i].length;j++)
{
if(i==0)
out.println("<td bgcolor='#b4b4b4' >"+array[i][j]+"</td>");
10
else
out.println("<td bgcolor='"+color[j] +"' >"+array[i][j]+"</td>");
}
out.println("</tr>");
}
out.println("</table>");
%>
</body>
</html>
The JSP file should be saved in the folder:
resin-x.x.x\webapps\cpan423
To invoke this JSP file from the deployment folder, type the following URL:
http://localhost:8080/cpan423/tableGenerator.jsp
Ex5:browsers.jsp:
In this example we will examine the user browser
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled</title>
</head>
<body>
<%!
public int getBrowser(HttpServletRequest request)
{
String agent = request.getHeader("USER-AGENT");
if (agent!=null && agent.indexOf("MSIE")!=-1)
{
return 1;
}
else if (agent!=null && agent.indexOf("Mozilla")!=-1)
{
return 2;
}
else
return 0;
}
%><%
switch (getBrowser(request))
11
{
case 1:
%>
<p align="center">Hello, MSIE</p>
<%
break;
case 2:
%>
<p align="center">Hello, netscape</p>
<%
break;
default:
%>
<p align="center">unkown</p>
<%
}
%>
</body>
</html>
The JSP file should be saved in the folder:
resin-x.x.x\webapps\cpan423
To invoke this JSP file from the deployment folder, type the following URL:
http://localhost:8080/cpan423/browsers.jsp
Ex6:usingInclude.jsp:
In this example the following file (usinginclude.jsp) will include another JSP file
file.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled</title>
</head>
<body>
<%@ page language="java" %><%!
12
String site[]={"yahoo.com","hotmail.com"};
%><%@ include file="file.jsp" %>
</body>
</html>
and file.jsp is:
<%@ page language="java" %>
<%
for(int i=0;i< site.length;i++)
out.println(" <a href='http://www."+site[i]+"'>"+site[i]+"</a><br />");
%>
The JSP files should be saved in the folder:
resin-x.x.x\webapps\cpan423
To invoke this JSP file from the deployment folder, type the following URL:
http://localhost:8080/cpan423/usingInclude.jsp
Ex7: Database connectivity with JSP using JNDI
This example uses a form named custForm.html to query and manipulate
customers table. customers table is created using the following SQL
statement:
SQL> create table customers (CustID number(6), CustName varchar
(30),SalesRepresentative varchar (30), CustAddress varchar (30),
CustPhone varchar(12),DebtAmount number(6,2), primary key (CustID));
custForm.html document has the following :
 An HTML table that describes all the customer table’s fields and their data
types.
 An HTML form that will be submitted to a jsp file called cust_trans.jsp. This
form contain:
1. A drop down list containing all customer table fields’ names. The
user can select any field from the list to be appended to the end of
the SQL statement text field using JavaScript code.
2. A text field to type a SQL statement.
3. Submit and reset buttons.
custForm.html:
13
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SQL page</title>
</head>
<body style="background-color: #ccffff;">
<h1 align='center' style='color: #000066;' >Customers
details </h1>
Customers has the following fields <br />
<table border='1'>
<tr><td> <b>Field Name </b></td>
<td>CustID</td>
<td>CustName</td>
<td>salesRepresentative</td>
<td>custAddress</td>
<td>custPhone</td>
<td>debtAmount</td>
</tr><tr><td> <b>Field Type </b></td>
<td>NUMBER</td>
<td>VARCHAR</td>
<td>VARCHAR</td>
<td>VARCHAR</td>
<td>VARCHAR</td>
<td>NUMBER</td>
</tr></table>
<form action='cust_trans.jsp' method='post'>
Select field to be appended to the end of SQL statement<select size='1'
name='record'
onchange='stat.value+=record[record.selectedIndex].text' >
<option> ---Select filed---</option>
<option> custID</option>
<option>CustName</option>
<option>salesRepresentative</option>
<option>custAddress</option>
<option>custPhone</option>
<option>debtAmount</option>
</select>
<br />type SQL statemant(Keywords in lower case):
<input type='text' name='stat' size='100' /></br>
<input type='submit' value='Execute' />
<input type='hidden' name='table' value=Customers />
</form>
14
<p style='color: #cc0066;' ><br />
This form was designed to perform the following SQL
commands: <br />
<ul style='color: #cc0066;' >
<li>Select</il><li>Update</il><li>Insert</il><li>Delete</il>
</p> <br />
</body>
</html>
The user must types a SQL statement and clicks submit button in order to
execute this statement on the server by a jsp file called cust_trans.jsp.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SQL output page</title>
</head>
<body style="background-color:#ccffff;">
<%@ page
import="java.io.*,java.sql.*,javax.sql.*,javax.naming.*"
errorPage ="dberror.jsp"
%>
<%!
// Declare the connection
DataSource ds=null;
Connection con;
/*
overwrite jspInit to establish the connection with the
customer database the first time the jsp file will be requested
*/
public void jspInit()
{
super.jspInit();
try
{
Context ic =
(Context) new InitialContext();
ds = (DataSource) ic.lookup("java:comp/env/jdbc/test");
15
}
catch(NamingException ce)
{
}
}
/*
overwrite jspDestroy to colse the connection when the servlet object
generated by the engin is destroyed
*/
public void jspDestroy()
{
try
{
con.close();
}
catch(Exception sqle)
{
}
}
%>
<%
con = ds.getConnection();
// get the SQL statement passed from the form.
String ss=request.getParameter("stat");
if(!ss.equals(""))
{
try
{
Statement stmt = con.createStatement();
/*
test the SQL statement to determine if it is a select statement or not.
If it is a select statement then we use executeQuery method to query the
customer table
and return the result set. If not we use executeUpdate to execute insert,
update, or
delete statements.
*/
//if not select statement
if(ss.indexOf("select")<0)
{
16
stmt.executeUpdate(ss);
String sql = "select * from Customers";
ResultSet rs = stmt.executeQuery(sql);
/*
use ResultSetMetaData to obtain data about data
(information about the table itself) at runtime
*/
ResultSetMetaData metadata;
metadata=rs.getMetaData();
// find the number of fields in customer table
int col=metadata.getColumnCount();
out.println("<table border='1'><tr>");
for(int i=1;i<=col;i++)
// get the customer table fields' names
out.println("<td><b>"+metadata.getColumnName(i)+"</b></td>");
out.println("</tr>");
while (rs.next())
{
out.println("<tr>");
for(int i=1;i<=col;i++)
/*
get the records' data as strings.
*/
out.println("<td>"+rs.getString(i)+"</td>");
out.println("</tr>");
}
out.println("</table><br />");
}
// if select statement
else
{
ResultSet rs =stmt.executeQuery(ss);
/*
again use ResultSetMetaData to find information about
database table at runtime
*/
ResultSetMetaData metadata;
metadata=rs.getMetaData();
int col=metadata.getColumnCount();
out.println("<table border='1'><tr>");
for(int i=1;i<=col;i++)
17
out.println("<td><b>"+metadata.getColumnName(i)+"</b></td>");
out.println("</tr>");
while (rs.next())
{
out.println("<tr>");
for(int i=1;i<=col;i++)
out.println("<td>"+rs.getString(i)+"</td>");
out.println("</tr>");
}
out.println("</table><br />");
}
}
catch(SQLException e)
{
throw e;
}
}
// if the statement is blank
else
out.println("You have not entered anything in the statement field, no
transaction was performed");
out.println("<a href='custForm.html'>Go back to customers table </a>");
%>
</body>
</html>
Exceptions that occur in this file are handled by an error page called dberror.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Error Page</title>
</head>
<body>
<%@ page import="java.sql.*,java.io.*" isErrorPage="true" %><%
if (exception instanceof SQLException)
out.println("the program has encounter the following SQL Exception
"+exception);
else if (exception instanceof NamingException)
out.println("JNDI Exception ");
else
out.println("The exception "+exception);
18
%>
</body>
</html>
The two methods, jspInit() and jspDestroy(), are called by the JSP engine when
creating and destroying the servlet object respectively. So the perfect place to
establish the connection to the database is in jspInit() and closing the connection
is in jspDestroy(). We close the connection as follow:
Con.close();
The JSP and HTML files should be saved in the folder:
resin-x.x.x\webapps\cpan423
To invoke this JSP file from the deployment folder, type the following URL:
http://localhost:8080/cpan423/custForm.html
Make sure that the following section is present in your web.xml :
<database jndi-name="jdbc/test">
<driver type="oracle.jdbc.driver.OracleDriver">
<url>jdbc:oracle:thin:@munro.humber.ca:1521:msit</url>
<user>user</user>
<password>password</password>
</driver>
</database>
Example 8: Using javabeans
In this example, we will use javabeans. The user will fill his name in the
HTML form and select one of two options for lottery games (super7 or lotto
64/9).
LotteryForm.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
19
<title>Lottery Form</title>
</head>
<body>
<form action="process.jsp" method="get">User Name: <input
type="text" name="userName" /><br />
Select your lottery game :<br />
Super 7:<input type="radio" name="lotto" value="Super7"
checked="checked" /> 6/49:<input type="radio" name="lotto"
value="lotto649" /> <input type="submit" value="Submit" /> <input
type="reset" /></form>
</body>
</html>
As you can see the form will be submitted to JSP file called process.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Lottery Processing</title>
</head>
<body>
<jsp:directive page import="com.lotteryGenerator"/>
<jsp:useBean id="userBean" scope="page" class="lotteryGenerator"
>
</jsp:useBean>
<jsp:setProperty name="userBean" property="*" />
<jsp:expression> userBean.info()
</jsp:expression>
</body>
</html>
In the processing JSP page, we are using a javabean to represent the
lottery logic (generating the game numbers randomly) so all we are doing
here is initiating a javabean object and passing the form data to the
javabean class set methods through the using of the setProperty tag.
After that we are calling the method info of the javabean class to show the
result.
lotterygenerator.java
package com;
import java.io.*;
public class lotteryGenerator extends Object implements Serializable
20
{
private String userName;
private String lotto;
public lotteryGenerator ()
{}
public void setLotto(String lt)
{
lotto=lt;
}
public String getLotto()
{
return lotto;
}
public void setUserName(String nm)
{
userName=nm;
}
public String getUserName()
{
return userName;
}
public String info()
{
int lottery[];
StringBuffer sb=new StringBuffer();
sb.append("Hello "+userName);
if(lotto.equals("Super7"))
{
lottery=new int[7];
}
else
lottery=new int[6];
sb.append(generate(lottery,lotto));
return sb.toString();
}
public String generate(int arr[],String game)
{
String output="<br />The result for "+game +"is <br /> ";
for(int i=0;i<arr.length;i++)
{
arr[i]=1+((int)(Math.random()*49));
output+="\t"+arr[i];
}
21
return output;
}
}
The lotteryGenerator bean must be saved in the folder:
resin-x.x.x\webapps\cpan423\WEB-INF\classes\com. The HTML and JSP
files must be stored in the folder: resin-x.x.x\webapps\cpan423.
Notice that the javabeans class member variables names must be the
same as the fields names of the HTML form.
The info method will test the user selection of the game through the lotto
member variable and generate the required numbers randomly. The
example does not test the generated numbers to make sure that they are
unique. You can do that yourself to perfect the example.
The application can be tested using the following URL:
http://localhost:8080/cpan423/lotteryForm.html
Ex2: forwarding a request from Servlet to JSP
In this example we will use a form to submit an integer to a servlet. The
form is called Forward.html :
<html>
<head>
<title>Redirect Form</title>
</head>
<body>
<form method="get" action="http://localhost:8080/cpan423/forward">
<p>Please enter an integer:<input type="text" name="T1"
size="20"></p>
<p><input type="submit" value="Submit" name="B1"><input
type="reset" value="Reset" name="B2"></p>
</form>
</body>
</html>
forwardServlettoJSP servlet will forward the request to test.jsp
import javax.servlet.*;
import javax.servlet.http.*;
22
import java.util.*;
import java.io.*;
public class forwardServlettoJSP extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException
{
/*
To forward a servlet to JSP document we have to obtain a
RequestDispatcher by
calling getRequestDispatcher method of ServletContext,
supplying a URL relative to the
servlet root.
*/
String adr="/test.jsp";
RequestDispatcher
dispatcher=getServletContext().getRequestDispatcher(adr);
// we use forward to completely transfer control to the
associated URL
dispatcher.forward(req,res);
}
}
The final file that will process the request is test.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<title>JSP</title>
</head
<body>
<%
String name=request.getParameter("T1");
int co=Integer.parseInt(name);
for(int i=0 ;i<=co;i++)
out.println(i+"<br/>");
%>
</body>
</html>
23
The servlet in this example acts as a controller. It receives requests from clients
and forwards them to the proper JSP file (in this case test.jsp).
The servlet in this example must be saved in the folder:
resin-x.x.x\webapps\cpan423\WEB-INF\classes. The HTML and JSP files
must be stored in the folder: resin-x.x.x\webapps\cpan423.
You need to add the following server/server-mapping entry for the redirect servlet
to web.xml:
<servlet>
<servlet-name>forward</servlet-name>
<servlet-class>forwardServlettoJSP</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern> /forward</url-pattern>
<servlet-name>forward</servlet-name>
</servlet-mapping>
The application can be tested using the following URL:
http://localhost:8080/cpan423/Forward.html
24