Sie sind auf Seite 1von 108

Servlets and Java Server Pages(JSP)

Contents
• Pre-Requisites
• Introduction
• Servlets vs. JSP
• How to Setup the Server
• Servlets
-- Basics
-- Form Data
• JavaServer Pages(JSP)
-- Overview
-- Scripting
• MVC Architecture

Wednesday, December 08,


2021
Introduction to Servlets & JSP....

• Role of Servlets and JSPs


• Dynamic Web Page Building
• Example Codes
• Differentiating and Understanding
the Roles of Servlets and JSPs

Wednesday, December 08,


2021
Role of Servlets and JSPs:
One Word: Middleware

They perform the Following Tasks:

1. Read the explicit data sent by the client.


2. Read the implicit HTTP request data sent by the browser
3. Generate the results.
4. Send the explicit data (i.e., the document) to the client.
5. Send the implicit HTTP response data.

Wednesday, December 08,


2021
Role of Servlets and JSPs:

• Because of the Usage of Java

• Choice of Developing:
-- Online Stores
-- Web Applications
-- Dynamic Web Sites and Web Pages

• Because of the “Out datedness” of CGI


(Common Gateway Interface)

Wednesday, December 08,


2021
Role of Servlets and JSPs:
Out Datedness of CGI?

• What is CGI?
-- Stands for Common Gateway Interface
-- Is a Simple & Portable Interface for running Ext.
Programs on a Web Server

• Servlets, “Serve” as Replacements

Wednesday, December 08,


2021
Role of Servlets and JSPs:
-- > CGI is System Dependant, for Running Web Applications.
Servers CREATE “Child Processes” for their Respective CGI
Scripts
A Sample CGI Code, written in “Perl”, called by a HTML Page
1. The Calling HTML Page

<html>
<head><title>Cluster Analysis</title></head>
<body>
<form action="/cgi-bin/clusteranalysis.pl" method="GET“>
How many clusters?
<input type=text name="clusters" size=3>
<input type=submit value=" OK ">
</form>
</body>
</html>

Wednesday, December 08,


2021
Wednesday, December 08,
2021
Role of Servlets and JSPs:
Comparison between CGI and Servlets….
Java Servlets are more:

• Efficient

• Convenient

• Powerful

• Portable

• Safe & Secure

• Cheaper than Traditional CGI and Alternative-CGI Technologies

Wednesday, December 08,


2021
Dynamically Building Web Pages….
• Remember, Servlets and JSPs are NOT Web Pages.
• They’re Programs that CREATE Web Pages.
Example:

Wednesday, December 08,


2021
Wednesday, December 08,
2021
These are some of the Reasons citing below, the Use of
Dynamically Building Web Pages:

• The Web page is based on data sent by the client

• The Web page is derived from data that changes


frequently.

• The Web page uses information from corporate


databases or other server-side sources.

Wednesday, December 08,


2021
Example Code:
• A Basic Code of a Servlet
• Memorize First. Understand Later….
• But before you do, just Note the 4 “In-Particular Points”
About the Code that is below.

• It is regular Java code: There are new APIs, but no new syntax.

• It has unfamiliar import statements:


The servlet and JSP APIs are not part of the Java 2
Platform, Standard Edition (J2SE); they are a
separate specification (and are also part of the Java
2 Platform, Enterprise Edition—J2EE).

• It extends a standard class (HttpServlet): Servlets provide a rich infrastructure


for dealing with HTTP.

• It overrides the doGet method: Servlets have different methods to


respond to different types of HTTP commands.

Wednesday, December 08,


2021
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request ,HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String docType ="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "


+"Transitional//EN\">\n“;
out.println(docType +
"<HTML>\n" +"<HEAD><TITLE>Hello</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>Hello</H1>\n" +
"</BODY></HTML>");
}
}
/* Don’t you get the Feeling that a Servlet Code looks Exactly like a HTML
Page code, embedded into a Java Code? */

Wednesday, December 08,


2021
• This is how the Servlet looks like, when you Run it, on a
Server
• Through out this presentation, the Focus is on How, the
Web Pages are developed, in HTTP.

Wednesday, December 08,


2021
JSP Code….
Consider a Sample JSP Code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN“>


<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>

<BODY BGCOLOR="#FDF5E6“>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome, <!-- User name is "New User" for first-time visitors -->
<%= coreservlets.Utils.getUserNameFromCookie(request) %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A>
</SMALL>
<P>Regular HTML for rest of online store’s Web page</P>
</BODY>
</HTML>

Wednesday, December 08,


2021
Likenesses and Differences:

• Servlet Code : HTML Code, inside Java Code

• JSP Code: Java Code inside HTML Code

• Consider the Codes that we’ve seen: Both look COMPLETELY Different.

• The Servlet looks like a Normal Java Code and the JSP, like a
Normal HTML Page
• But, they are the SAME

• In fact, a JSP document is just another way of writing a servlet.

• JSP pages get translated into Servlets, the Servlets get compiled, and it is
the Servlets that run at request time.

Then, obviously, the Question MUST arise:


Wednesday, December 08,
2021
JSP? Or Servlets?

• The Two primary Questions that MUST Arise are:


1. If both are the same, then which must Used?
2. If we’re looking for EFFICIENCY, then which is better among
the Two?

The Answer to Question 1 is: Both are EQUIVALENT, in terms of Power


But each has its Own PERSPECTIVE of Usage

The Answer to Question 2 is: The same Answer as of Above. Same in


Power. Each is Efficient Enough. But, EACH has its OWN Usage..

The issue is not POWER, but Convenience, Ease of Use and


Maintainability.

• The Difference comes, when we tend to Divide Our Applications into


Two Parts: The Logic Part and the Display Part. Here comes the
Difference of Usage, for the Two: Servlets and JavaServer Pages
Wednesday, December 08,
2021
Server Setup & Configuration....

Contents:
• Installing Java onto the System
• Setting up & Configuring a Server
• Difference between Development
and
Deployment
• Running Test Codes
• Developing Web Applications

Wednesday, December 08,


2021
Intro....

• First of all, you MUST have the Proper Software and KNOW
HOW, to Use it
• You must know first, whether you have the correct Version of
JDK to support the Codes that will be given for Compilation
• Then, comes Installing and Configuring the Server
• Setting up the Development Environment would Come down
as the Next Step
• Running Codes to test the Working of the Server and the
other Softwares involved.
• Then proceed to Configuring the “web.xml” file and then
Proceed to Developing a Web Application.

Wednesday, December 08,


2021
Installing JDK….
• Current versions of the servlet and JSP APIs require the Java 2 Platform (Standard
Edition—J2SE—or Enterprise Edition—J2EE).

• If J2EE features like Enterprise JavaBeans (EJB) or Java Messaging Service (JMS) are
NOT REQUIRED, the Standard Edition is recommend

• The Installed server will supply the classes needed to add servlet and JSP support to
Java 2 Standard Edition.

• The JDK Version, also depends on the Server. Like:


-- The Servlet/JSP API to be used
-- A Full J2EE-compliant application server (e.g., WebSphere, WebLogic, or JBoss)
or a standalone servlet/JSP container (e.g., Tomcat, JRun, or Resin).

• Then, we need to set the PATH like “set PATH=C:\j2sdk1.4.1_01\bin;%PATH%”


or use an Existing “autoexec.bat” file, by downloading it, NOT a Recommended Option.

Wednesday, December 08,


2021
Installing the SERVER….
The Available JDK Versions in the Market are:
• Servlets 2.3 and JSP 1.2 (standalone servers).
• Java 1.2 or later. J2EE 1.3 (which includes Servlets 2.3 and JSP 1.2).
• Java 1.3 or later. Servlets 2.4 and JSP 2.0 (standalone servers).
• Java 1.3 or later. J2EE 1.4 (which includes Servlets 2.4 and JSP 2.0).
• Java 1.4 or later.

• Step 1 comprised of Having the Correct JDK Installed into the System
• Step2: Download a server (often called a “servlet container” or “servlet
engine”)
that implements the Servlet 2.3 Specification (JSP 1.2) or the Servlet
2.4
Specification (JSP 2.0) for use on your desktop

The Server that is Downloaded and Loaded onto the System is called as a
Development Server/Test Server….

Wednesday, December 08,


2021
• The point that MUST be clear at this point is this:
-- Why should we HAVE a Server on the System (A Test Server),
when we have Inter and Intranet Servers available ?
Ans: Development server – Simplifies development in a number of
ways, Compared to deploying to a remote server each and every time
you want to test something.

Below, are the Reasons why:


• Faster to Test:
• Easier to Debug:
• Simple to Restart:
• Reliable to Benchmark
• Easy to Install
• Guaranteed to be Under Control

If you can run the same server on your desktop that you use for
deployment, all
the better

Wednesday, December 08,


2021
See http://java.sun.com/products/servlet/industry.html for a
more complete list of servers and server plugins that support
Servlets and JSP.

The Development Servers, that are Popular are:

• Apache Tomcat: Download from http://jakarta.apache.org/tomcat/


• Macromedia JRun: from http://www.macromedia.com/software/jrun/
• Caucho’s Resin: from http://caucho.com/products/resin/

Wednesday, December 08,


2021
Configuring the SERVER….
 Step 3: Configuring the Server….
 Life becomes Easier with the Usage of an IDE
 Configuring the Server is NECESSARY, to RUN the Server on the
System. And while it runs, note that it RUNS, as a STAND-ALONE-
SERVER
 The Following are the Steps for Configuring a Server:

1. Identifying the SDK Installation Directory: Like for instance, it can


be C:\jdk6.0
2. Specifying the Port: Mostly use the Standard Port of 80 (Like
8080 or 9080)
3. Making Server-Specific Customizations: Depends on the
Server’s Specifications, different from Server to Server

Wednesday, December 08,


2021
Setting Up a Development Environment....
• The Server has been Made Ready to Run Servlets and JSPs
in the Previous Slides
• What has been done, is Called the “Deployment Directory” i.e.,
a Place where the Final Running Part of the Web Pages Design
is Done.
• Now, a Personal DEVELOPMENT DIRECTORY has to be
setup/created; to store the Servlets and JSPs and the
Intermediary Data
• Consists of the Following Steps:
1. Creating a Directory: for Storing all the Files (Servlets, JSPs &
Supporting Classes), called Development Directory.
2. Setting your CLASSPATH: is about telling the Server, WHERE
the Servlet & JSP JAR Files and the Development Directory are.*
3. Making Shortcuts to START/STOP the Server: For the Sake of
Convenience…
4. Bookmarking or installing the servlet and JSP API
documentation: It may come in Handy…

* Can be specified in One path itself, which becomes


the CLASSPATH as %path1%;%path2%;%path3%
Wednesday, December 08,
2021
Test Codes....

• To confirm whether the Server has been Properly Configured, or not, before
We run Our Servlets and JSPs

• Verification involves 3 Summarized Steps, as below:

1. Verifying the SDK Installation

2. Checking the Basic Server Configuration

3. Compiling and Deploying some Simple Servlets/JSPs

Wednesday, December 08,


2021
1. Verifying the JDK Installation:

• Two simple Tests, for Verifying the Correct JDK Installation:

-- Open DOS Command Prompt or Unix Shell and type in the command
prompt:
1. java –version 2. javac –help
A Result must be seen BOTH times
NOT an Error Message about an Unknown Command

-- If an IDE is in use, then run a Simple “HelloWorld.java” program, to


see if its Class File is getting generated and its Result Appears..

• If either of these tests fails, review the installation instructions that came
with the SDK.

• A Depiction of a Successful Steps 1 and 2 is shown in the Next Page

Wednesday, December 08,


2021
Wednesday, December 08,
2021
If either of these tests fails, then there are Two
Possible Reasons:

• The PATH variable may NOT have been


set Properly, so go BACK and Correct the
Path Settings.
OR,
• The JDK must have been Improperly
Installed

Wednesday, December 08,


2021
2. Checking the Basic Server Configuration:
• Type: http://localhost/ (if the Port hasn’t been Configured Already)
or http://localhost:<port Number>/ if the Port has been Configured, say 9080
• The Result will be in the Following:
If you use an Apache Tomcat Server, then this is how the Result Looks like:

Wednesday, December 08,


2021
Wednesday, December 08,
2021
How Deployment & Development Directories are
Arranged…
IDE Under Use here: IBM Rational Application
Developer (RAD) 7.0,
using Eclipse

Wednesday, December 08,


2021
Wednesday, December 08,
2021
Wednesday, December 08,
2021
Wednesday, December 08,
2021
Test Codes....

• Run a Few Demo Programs like:


1. First, run a HTML Program
2. Then Run a JSP
3. Then go for a Servlet

• Once the Server’s Working and the JDK is showing NO Problems, then
the Above three Files are Supposed to Work without any problems.

• Things become Easier with an IDE.

Wednesday, December 08,


2021
Basic HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>

<body>
<H2>Hello! This is a Test Going On.. ;-)</H2>
</body>
</html>

Just Run the HTML File, by specifying its


Path, after “http://localhost:9080/”, in the
Address Bar.

The File MUST Run….

The same Applies for the Other Files as


well

Wednesday, December 08,


2021
//Running a Simple Text Servlet..

Wednesday, December 08,


2021
Wednesday, December 08,
2021
Wednesday, December 08,
2021
Wednesday, December 08,
2021
//Running a HTML
Servlet

Wednesday, December 08,


2021
Wednesday, December 08,
2021
Wednesday, December 08,
2021
A Simplified Deployment Method:

Deployment Implies Placing the Class Files of the Respective Java Files,
in the Server’s Respective Directory. Four Methods for that:

1. Copying to a shortcut or symbolic link.

2. Using the -d option of javac.

3. Letting your IDE take care of


deployment.

4. Using ant or a similar tool.

Wednesday, December 08,


2021
Developing Web Applications:

• The Next Step, Developing Web Applications

• It comes with configuring an XML file, called as “web.xml”

• Instead of Remembering the Complete URL of the Servlets or the JSPs,


we can NAME the path and Specify the Required Directions, as we have
Named, in the web.xml File.

• General Format of a URL: http://host/servlet/ServletName where the


“ServletName” is the Name of the Servlet “.java” file itself

• Web Applications require a web.xml file, which specify the Path, as


shown:

Wednesday, December 08,


2021
A Sample web.xml File:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp_ID">
<display-name>TestingWeb</display-name>

<servlet>
<servlet-name>Testing1</servlet-name>
<servlet-class>Package1.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Testing1</servlet-name>
<url-pattern>/Testing1</url-pattern>
</servlet-mapping>

</web-app>

Wednesday, December 08,


2021
Making a Web Application Directory:

To make a Web application, create a directory in your development


folder. That new directory should have the same general layout as the
default Web application:

• HTML and, eventually, JSP documents go in the top-level directory


(or any subdirectory other than WEB-INF).

• The web.xml file (sometimes called the “Web deployment


descriptor”) goes in the WEB-INF subdirectory.

• Servlets and other classes go either in WEB-INF/classes or, more


commonly, in a subdirectory of WEB-INF/classes that matches the
package name.

Wednesday, December 08,


2021
The following list summarizes the steps; the subsections that follow
the steps give details:

1. Make a directory whose structure mirrors the structure of the


default Web application.

2. Update your CLASSPATH.

3. Register the Web application with the server.

4. Use the designated URL prefix to invoke servlets or HTML/JSP


pages from the Web application.

5. Assign custom URLs for all your servlets.

Wednesday, December 08,


2021
Servlets….

Contents:
• Life Cycle of a Servlet
• Form Data

Wednesday, December 08,


2021
Introduction....

• Have already seen How Servlets are Written, Compiled & Executed
• Here, We shall look at the LIFE-CYCLE of a Servlet

• The Life Cycle of a Servlet, consists of the Processes:


1. The Beginning or Initialization method, called “init” method
2. The Method, which calls the doGet, doPost and other do
methods,
called “service”
3. The Final Method, which closes the Servlet, called as
“destroy”
method

Wednesday, December 08,


2021
• When the servlet is first created, its init method is invoked

• After this, each user request results in a thread that calls the service
method of the previously created instance.

• Multiple concurrent requests normally result in multiple threads calling


service simultaneously

• But, that servlet can implement a special interface (SingleThreadModel)


that stipulates that only a single thread is permitted to run at any one time.

• The service method then calls doGet, doPost, or another doXxx


method, depending on the type of HTTP request it received.

• Finally, if the server decides to unload a servlet, it first calls the


Servlet’s destroy method.

Wednesday, December 08,


2021
init() Method:
• Most of the time, your Servlets deal only with per-request data, and
doGet or doPost are the only life-cycle methods you need.
• Occasionally, however, you want to perform complex setup tasks when
the servlet is first loaded, but not repeat those tasks for each request.
• The init method is designed for this case; it is called when the servlet is
first created, and not called again for each user request.
• So, it is used for one-time initializations, just as with the init method of
applets.
• The servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the servlet be
loaded when the server is first started

The init method definition looks like this:


public void init() throws ServletException {
// Initialization code...
}
The init method performs two varieties of initializations: general
initializations and initializations controlled by initialization parameters.

Wednesday, December 08,


2021
General Initializations:
With the first type of initialization, init simply creates or loads some data that will be
used throughout the life of the servlet, or it performs some one-time computation.

Consider the Following Example:

public class LotteryNumbers extends HttpServlet {


private long modTime;
private int[] numbers = new int[10];
/* The init method is called only when the servlet is first
* loaded, before the first request is processed.
*/
public void init() throws ServletException {
// Round to nearest second (i.e., 1000 milliseconds)
modTime = System.currentTimeMillis()/1000*1000;

for(int i=0; i<numbers.length; i++) {


numbers[i] = randomNum();
}
}
/** Return the list of numbers that init computed. */

// Continued Part 2…
Wednesday, December 08,
2021
Complete Program:
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Your Lottery Numbers";
String docType ="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+"Transitional//EN\">\n";

out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<B>Based upon extensive research of " +
"astro-illogical trends, psychic farces, " +
"and detailed statistical claptrap, " +
"we have chosen the " + numbers.length +
" best lottery numbers for you.</B>" +
"<OL>");

for(int i=0; i<numbers.length; i++) {


out.println(" <LI>" + numbers[i]);
}

out.println("</OL>"+"</BODY></HTML>");

} // Continued Part 3….


Wednesday, December 08,
2021
/** The standard service method compares this date against
* any date specified in the If-Modified-Since request header.
* If the getLastModified date is later or if there is no
* If-Modified-Since header, the doGet method is called
* normally. But if the getLastModified date is the same or
* earlier, the service method sends back a 304 (Not Modified)
* response and does <B>not</B> call doGet. The browser should
* use its cached version of the page in such a case.
*/

public long getLastModified(HttpServletRequest request) {


return(modTime);
}

// A random int from 0 to 99.

private int randomNum() {


return((int)(Math.random() * 100));
}
} // End of LotteryNumbers….

Wednesday, December 08,


2021
The web.xml Page would look like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp_ID">
<display-name>TestingWeb</display-name>

<servlet>
<servlet-name>Testing3</servlet-name>
<servlet-class>Package1.LotteryNumbers</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Testing3</servlet-name>
<url-pattern>/Testing3</url-pattern>
</servlet-mapping>

</web-app>

Wednesday, December 08,


2021
The Output:

Wednesday, December 08,


2021
service() Method:

• Each time the server receives a request for a servlet, the server spawns
a new thread and calls service.

• The service method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc., as
appropriate.

• A GET request results from a normal request for a URL or from an


HTML form that has no METHOD specified.

• A POST request results from an HTML form that specifically lists POST
as the METHOD.

• Other HTTP requests are generated only by custom clients.

Wednesday, December 08,


2021
• To handle both POST and GET requests identically, instead of Overriding doPost() method
Directly as Usual, do as below:

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Servlet code
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

• Although this approach takes a couple of extra lines of code, it has several advantages
over directly overriding service.

• Overriding service directly precludes this possibility.

• Second, you can add support for modification dates by adding a getLastModified method.

• Since getLastModified is invoked by the default service method, overriding service


eliminates this option.

Wednesday, December 08,


2021
destroy():

• There are many Reasons where a Server may be Removed or HAVE to be removed.

• Example: The server may decide to remove a previously loaded servlet instance,
perhaps because it is explicitly asked to do so by the server administrator or perhaps
because the servlet is idle for a long time.

• Before it does, however, it calls the Servlet’s destroy method.

• This method gives your servlet a chance to close database connections, halt
background threads, write cookie lists or hit counts to disk, and perform other such
cleanup activities.

Wednesday, December 08,


2021
Form Data: Reading Parameters through Servlets….
Take a Look at this Example:

Wednesday, December 08,


2021
Main motivations for building Web pages dynamically is so that the result can be based
upon user input.

Using Form tag(<FORM>….</FORM>), we shall see how to Achieve the Above Result:

• Reading individual request parameters

• Reading the entire set of request parameters

• Automatically filling in a data object with request


parameter values: FormBeans

Ever typed: “Java/J2EE Certification” in Google and seen What appears in the URL?

Wednesday, December 08,


2021
The part after the question mark (i.e.,hl=en&q=Java%2FJ2EE+Certification&meta=) is known
as form data (or query data) and is the most common way to get information from a Web
page to a server-side program.

Form data can be attached to the end of the URL after a question mark (as above) for GET
requests;

Form data can also be sent to the server on a separate line for POST requests.

The Basics of HOW-TO-CREATE Forms are below:

1. Use the FORM element to create an HTML form


<FORM METHOD =“….” ACTION="...">...</FORM>

2. Use input elements to collect user data


<INPUT TYPE="TEXT" NAME="...">

3. Place a submit button near the bottom of the form


<INPUT TYPE="SUBMIT“ ..>

For more on Forms, see HTML in http://www.w3schools.com/

Wednesday, December 08,


2021
This is how a Form Tag looks like:

<FORM ACTION=“…….“ > <!-- Remember that NO METHOD specified-->


<!-- means it’s a GET Request
First Parameter: <INPUT TYPE="TEXT" NAME=“~hall"><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME=“~gates"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME=“~mcnealy"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>

Which looks like:

This is where Java Servlets or JSP dominate over Traditional CGI

Wednesday, December 08,


2021
Form Data: Reading Parameters from Servlets….
The Standard Way of Passing Parameters, by using the Method:
“request.getParameter()”
Where “request” is a HttpServletRequest Parameter that is one of the
Parameters passed to the doGet and doPost methods.

Gets us a SINGLE Parameter.

Some of the Following, are the functions that are used for Retrieving Form
Data:
HttpServletRequest
- getParameter
- getParameterValues
- getParameterNames*
- getParameterMap

These are only some of the functions in


HttpServletRequest. More, can be explored, as
Applications are developed..

* Don’t count on getParameterNames to return the Parameters


Names in they Order in which they Appear in the Original Page.
Wednesday, December 08,
2021
A Simple Example, to Read Three Parameters:

Consider a HTML File, which has to pass Exactly 3 Parameters, to a


Servlet:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<!-- <%String context = request.getContextPath();%>-->


<HTML>
<HEAD>
<TITLE>Collecting Three Parameters</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Collecting Three Parameters</H1>

<!-- FORM ACTION="<%=context%>/servlet/Package1.ThreeParams"-->


<FORM ACTION="/TestingWeb/servlet/Package1.ThreeParams">
First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>

<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>
</BODY>
</HTML>

Wednesday, December 08,


2021
The Servlet which receives the 3 Parameters from the HTML File, is
shown now:
package Package1;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/*@author 258854*/
public class ThreeParams extends HttpServlet{

public void doGet(HttpServletRequest request,HttpServletResponse response)


throws ServletException,IOException{

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters“;

String docType ="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 “+"Transitional//EN\">\n“;

out.println(docType +"<HTML>\n" +"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +


"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title +"</H1>\n<UL>\n" +
" <LI><B>param1</B>: “+ request.getParameter("param1") +
"\n <LI><B>param2</B>: “+ request.getParameter("param2") +
"\n <LI><B>param3</B>: “+ request.getParameter("param3") +
"\n</UL>\n”+
“</BODY></HTML>");
}
} When the Servlet is compiled and the HTML Page is Run on the
Server, the Result is:

Wednesday, December 08,


2021
Clicking on “Submit
Query”, we obtain the
Next Page….

Wednesday, December 08,


2021
We can try another Example, to test a Servlet, which is Dynamically Designed,
to Handle any Number of Inputs, from a HTML Page:

package Package1;

import java.io.*;
import java.util.*; //For import java.util.Enumeration
import javax.servlet.*; // For import javax.servlet.ServletException;
Import javax.servlet.http.*; // For Http Servlet, ServletRequest and ServletResponse

/* @author 258854*/
public class ShowAllParameters extends HttpServlet{

public void doGet(HttpServletRequest request,HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String docType="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +"Transitional//EN\">\n";

String title = "Reading All Request Parameters“;

out.println(docType +"<HTML>\n" +"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +


"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");

Enumeration paramNames = request.getParameterNames();


//Continued…
Wednesday, December 08,
2021
//Continued Part 2….

while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");

String[] paramValues = request.getParameterValues(paramName);

if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<I>No Value</I>");
else
out.println(paramValue);
}
else{
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}

out.println("</TABLE>\n</BODY></HTML>");
}

public void doPost(HttpServletRequest request,HttpServletResponse response)


throws ServletException, IOException {
doGet(request, response);
}
}
Wednesday, December 08,
2021
JavaServer Pages….

Contents:
• Overview and Basics
• Scripting/Elements
• Java Beans

Wednesday, December 08,


2021
Overview:
We are going to Discuss the Following Topics:

• Basics
• Installing JSP Pages
• JSP Syntax

• A Combination of Static and Dynamic Text; Static being the HTML Part and
Dynamic being the Java Content.

• The HTML Part is written like a Normal HTML. The Dynamic Java Code, is
“Embedded” between: “<%” and “%>” respectively

• There’s No Difference between a JSP Page and a HTML Page, when No


Java Code is used in the Page

Wednesday, December 08,


2021
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>
<HEAD>
<TITLE>Order Confirmation</TITLE>
<LINK REL=STYLESHEET HREF="JSP-Styles.css” TYPE="text/css“>
</HEAD>
<BODY>
<H2>Order Confirmation</H2>
Thanks for ordering
<I><%= request.getParameter("title") %></I>!
</BODY>
</HTML>

• JSP are like Java Code Embedded in HTML


• Servlets are like HTML Embedded in Java Code
• Neither have the Necessity of Including HTML. Yet, they do. Hence, the Flexibility
• Remember that JSP are Servlets-BEHIND-THE-SCENES
• But each has its Own Advantages

Wednesday, December 08,


2021
Benefits of JSPs....
• It is easier to write and maintain the HTML

• You can use standard Web-site development tools

• You can divide up your development team

Installation of JavaServer Pages


Servlets:

• Require you to set your CLASSPATH,

• Use packages to avoid name conflicts,

• Install the class files in servlet-specific locations and

• Use special-purpose URLs.

Wednesday, December 08,


2021
JSP are NOT required to do so. On the other hand:

• JSP pages can be placed in the same directories as


normal HTML pages, images, and style sheets;

• They can also be accessed through URLs of the same


form as those for HTML pages, images, and style sheets.

NOTE: You are never allowed to use WEB-INF or META-INF


as directory names. When using the default Web application,
you also have to avoid a directory name that matches the
URL prefix of any other Web application.

Wednesday, December 08,


2021
Java Code using JSP Scripting Elements:
There are Different Ways, in which Java Code can be Invoked,
using Java Scriptlets:

• Call Java code directly.

• Call Java code indirectly.

• Use beans.

• Use the MVC architecture.

• Use the JSP expression language.

• Use custom tags.

Wednesday, December 08,


2021
Types of JSP Scripting Elements:

Are of 3 Forms:

1. Expressions : <%= Java Expression %>

2. Scriptlets: <% Java Code %>

3. Declarations: <%! Field/Method Declaration %>

Comments in JSP are put in the Following Format: <%-- JSP Code --%>

Note: Its always to have as Less Java Code in JSP Pages as Possible

Wednesday, December 08,


2021
Predefined Variables:
The available variables are request, response, out, session,
application, config, pageContext, and page.

An additional variable called exception is available, but only in error


pages.

• request: the HttpServletRequest


• response: the HttpServletResponse
• session: the HttpSession, associated with request
• out: the Writer, used to send output to the Client
• application: the ServletContext – available throught the Application
• config: the ServletConfig
• pageContext: for providing Single Point Access to many Page Attributes
• page: a Synonym for “this” in Java....

Wednesday, December 08,


2021
JSP Expressions:
Consider a JSP Page, which derives its Expressions from a Class in Package1 called as
“RunUtilities.java”

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<%--@page import="Package1.RanUtilities;"--%>

<html>
<head>
<title>RandomNums</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>
<H1>Random Numbers</H1>
<UL>
<LI><%= Package1.RanUtilities.randomInt(10) %>
<LI><%= Package1.RanUtilities.randomInt(10) %>
<LI><%= Package1.RanUtilities.randomInt(10) %>
<LI><%= Package1.RanUtilities.randomInt(10) %>
<LI><%= Package1.RanUtilities.randomInt(10) %>
</UL>
</body>
</html>

Wednesday, December 08,


2021
package Package1;

/** Simple utility to generate random integers. */


public class RanUtilities {
/** A random int from 1 to range (inclusive). */

public static int randomInt(int range) {


return(1 + ((int)(Math.random() * range)));
}
/*Test routine. Invoke from the command line with the desired range. Will print 100 values. Verify
* that you see values from 1 to range (inclusive) and no values outside that interval.*/

public static void main(String[] args) {


int range = 10;
try {
range = Integer.parseInt(args[0]);
}
catch(Exception e){
// Array index or number format
// Do nothing: range already has default value.
}
for(int i=0; i<100; i++) {
System.out.println(randomInt(range));
}
}
}
Wednesday, December 08,
2021
The Output:

Wednesday, December 08,


2021
2. JSP Scriptlets:
Now, an Example for Scriptlets, as of below, a Different JSP:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<%@page language="java" contentType="text/html; charset=ISO-8859-1” pageEncoding="ISO-8859-1"%>
<%@page import="Package1.*"%>
<html>
<head>
<title>RandomList1</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>
<H1>Random List (Version 1)</H1>
<UL>
<%
int numEntries = RanUtilities.randomInt(10);
for(int i=0; i<numEntries; i++) {
out.println("<LI>" + RanUtilities.randomInt(10));
}
%>
</UL>
Or…
</body>
</html>

Wednesday, December 08,


2021
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@page language="java" contentType="text/html; charset=ISO-8859-1” pageEncoding="ISO-
8859-1"%>
<html>
<head>
<title>RandomNums2</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>
<H1>Random List (Version 2)</H1>
<UL>
<%
int numEntries = Package1.RanUtilities.randomInt(10);
for(int i=0; i<numEntries; i++) {
%>
<LI><%= Package1.RanUtilities.randomInt(10) %>
<% } %>
</UL>
</body>
</html>

Wednesday, December 08,


2021
The Outputs:

Wednesday, December 08,


2021
3. JSP Declarations:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<%--@page import="Package1.RanUtilities"--%>

<html>
<head>
<title>SemiRandomNumber</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>
<%!private int randomNum = Package1.RanUtilities.randomInt(10);%>
<H1>Semi-Random Number:<BR><%= randomNum %></H1>
</body>
</html>

Wednesday, December 08,


2021
The Output:

Wednesday, December 08,


2021
MVC Architecture....

Java Servlets: Good at data Processing

JavaServer Pages: Good at Presentation

MVC Architecture: A Combination of Both Servlets and JSPs

MVC stands for Model-View-Controller Architecture

Controller - Servlet
View - JSP
Model - EJBs

Wednesday, December 08,


2021
The most Important point, about MVC Architecture is the Separation of
the Business Logic and Data Access Layers, from the Presentation
Layers.
It comes through the Following Steps:

1. Define beans to represent the data

2. Use a Servlet to handle requests

3. Populate the beans

4. Store the bean in the request, session, or servletcontext

5. Forward the request to a JSP page

6. Extract the data from the beans

Wednesday, December 08,


2021
Storing the Beans:

• Storing data that the JSP page will use only in this request

First, the servlet would create and store data as follows:

ValueObject value = new ValueObject(...);


request.setAttribute("key", value);

Next, the servlet would forward the request to a JSP page that uses the
following to retrieve the data.

<jsp:useBean id="key" type="somePackage.ValueObject"


scope="request" />

Wednesday, December 08,


2021
• Storing data that the JSP page will use in this request and in later requests
from the same client i.e., for a session

First, the servlet would create and store data as follows:

ValueObject value = new ValueObject(...);


HttpSession session = request.getSession();
session.setAttribute("key", value);

Next, the servlet would forward to a JSP page that uses the following to
retrieve the data in the following fashion:

<jsp:useBean id="key" type="somePackage.ValueObject"


scope="session" />

Wednesday, December 08,


2021
• Storing data that the JSP page will use in this request and in later requests
from any client i.e., for the entire duration of the application

First, the servlet would create and store data as follows:

ValueObject value = new ValueObject(...);


getServletContext().setAttribute("key", value);

Next, the servlet would forward to a JSP page that uses the following to
retrieve the data:

<jsp:useBean id="key" type="somePackage.ValueObject"


scope="application" />

Wednesday, December 08,


2021
Forwarding Request to JSPs from Servlets:
• Use forward method of RequestDispatcher (javax.servlet.)

• Use it to transfer to the address you want

• Consider the Example below:

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

String operation = request.getParameter("operation");

if (operation == null) { operation = "unknown”; }

String address;
if (operation.equals("order")) { address = "/WEB-INF/Order.jsp”; }
else if (operation.equals("cancel")) { address = "/WEB-INF/Cancel.jsp”; }
else { address = "/WEB-INF/UnknownOperation.jsp”; }

RequestDispatcher dispatcher = request.getRequestDispatcher(address);


dispatcher.forward(request, response);
}

Wednesday, December 08,


2021
Then comes the Question of Static or Dynamic Display Pages:

• Static Resources -- NO Active Java Content


Transferring Control to Static Pages, FORWARDING
-- Control transferred ENTIRELY to the Server. No network traffic is involved.
-- Destination Address Not User Visible

• Dynamic Resources would mean JSPs


Re-Directing using sendRedirect method, under response Variable
-- Control is transferred by sending the client a 302 status code and a
Location response header
-- Address is USER VIEWABLE and Bookmarkable

• asdasdas

Wednesday, December 08,


2021
Extracting Data from Beans:

• Once the request arrives at the JSP page, the JSP page uses jsp:useBean and
jsp:getProperty to extract the data.

• Depending on the type of scope, there are three ways:

<jsp:useBean id="key" type="somePackage.SomeBeanClass"


scope="request" />
<jsp:useBean id="key" type="somePackage.SomeBeanClass"
scope="session" />
<jsp:useBean id="key" type="somePackage.SomeBeanClass"
scope="application" />

Wednesday, December 08,


2021
An Example:

package BankingEg;

import java.util.HashMap;

public class BankCustomer {

private String id, firstName, lastName;


private double balance;

public BankCustomer(String id,String firstName,String lastName,double balance){


this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;
}

// Continued to Part 2..

Wednesday, December 08,


2021
// Part2….

//Getters
public String getId(){
return(id);
}
public String getFirstName(){
return(firstName);
}
public String getLastName(){
return(lastName);
}
public double getBalance() {
return(balance);
}
public double getBalanceNoSign(){
return(Math.abs(balance));
}

//One Setter...
public void setBalance(double balance){
this.balance = balance;
}

// Continued Part3….

Wednesday, December 08,


2021
// Makes a small table of banking customers.
private static HashMap customers;
static {
customers = new HashMap();
customers.put("id001",new BankCustomer("id001","John","Hacker",-3456.78));
customers.put("id002",new BankCustomer("id002","Jane","Hacker",1234.56));
customers.put("id003",new BankCustomer("id003","Juan","Hacker",987654.32));
}

/** Finds the customer with the given ID.


* Returns null if there is no match.
*/
public static BankCustomer getCustomer(String id) {
return((BankCustomer)customers.get(id));
}
}// End of the BankCustomer Class

Wednesday, December 08,


2021
package BankingEg;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/* @author 258854 */
public class ShowBalance extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException,IOException{

BankCustomer customer =BankCustomer.getCustomer("id003"); // Give any ID for testing Purpose: id,


id001,
// id002, id003
String address;

if (customer == null) {
address = "/Web-Docs/Banking Folder/UnknownCustomer.jsp“;
}
else if (customer.getBalance() < 0) {
address = "/Web-Docs/Banking Folder/NegativeBalance.jsp“;
request.setAttribute("badCustomer", customer);
}
else if (customer.getBalance() < 10000) {
address = "/Web-Docs/Banking Folder/NormalBalance.jsp“;
request.setAttribute("regularCustomer", customer);
}

// Continued on Part 2….


Wednesday, December 08,
2021
// Continued Part 3….
else {
System.out.println("Its > 10000 Balance");
address = "/Web-Docs/Banking Folder/HighBalance.jsp“;
request.setAttribute("eliteCustomer", customer);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}

Wednesday, December 08,


2021
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@page language="java" contentType="text/html; charset=ISO-8859-1” pageEncoding="ISO-8859-1"%>

<html>
<head>
<title>UnknownCustomer</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
Unknown Customer
</TABLE>
<P>Unrecognized customer ID.</P>
</body>
</html>

Wednesday, December 08,


2021
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
<TITLE>Your Balance</TITLE>
</head>
<body>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
Your Balance
</TABLE>
<P>
<jsp:useBean id="regularCustomer" type="BankingEg.BankCustomer” scope="request" />
<UL>
<LI>First name: <jsp:getProperty name="regularCustomer” property="firstName" />

<LI>Last name: <jsp:getProperty name="regularCustomer” property="lastName" />

<LI>ID: <jsp:getProperty name="regularCustomer” property="id" />

<LI>Balance: $<jsp:getProperty name="regularCustomer” property="balance" />


</UL>
</P>
</body>
</html>

Wednesday, December 08,


2021
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
<TITLE>You Owe Us Money!</TITLE>
<!-- LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"-->
</head>
<body>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">We Know Where You Live!
</TABLE>

<P>
<jsp:useBean id="badCustomer" type="BankingEg.BankCustomer" scope="request" />
Watch out,<jsp:getProperty name="badCustomer" property="firstName" />,
we know where you live.
</P>
<P>
Pay us the
$<jsp:getProperty name="badCustomer" property="balanceNoSign" />
you owe us before it is too late!
</P>
</body>
</html>

Wednesday, December 08,


2021
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@page language="java" contentType="text/html; charset=ISO-8859-1” pageEncoding="ISO-8859-1"%>
<html>
<head>
<TITLE>Your Balance</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">Your Balance
</TABLE>
<P>
<BR CLEAR="ALL">
<jsp:useBean id="eliteCustomer" type="BankingEg.BankCustomer” scope="request" />
It is an honor to serve you,
<jsp:getProperty name="eliteCustomer" property="firstName" />
<jsp:getProperty name="eliteCustomer" property="lastName" />!
</P>
<P>
Since you are one of our most valued customers, we would like
to offer you the opportunity to spend a mere fraction of your
$<jsp:getProperty name="eliteCustomer" property="balance" />
on a boat worthy of your status. Please visit our boat store for more information.
</P>
</body>
</html>

Wednesday, December 08,


2021
Depending on what you give as the Customer ID (Eg: “id001”), you get the Following Outputs:

ID = “id000”

ID = “id001”

Wednesday, December 08,


2021
ID = “id002”

ID = “id003”

Wednesday, December 08,


2021
Thank You!!

Wednesday, December 08,


2021

Das könnte Ihnen auch gefallen