You are on page 1of 153

UNIT III: SERVER SIDE

PROGRAMMING
UNIT III: SERVER SIDE
PROGRAMMING

Java Servlet Architecture – Servlet Life


Cycle– Form GET and POST actions –
Session Handling – Understanding
Cookies – Installing and Configuring
Apache Tomcat Web Server –
Understanding Java Server Pages –
JSP Standard Tag Library(JSTL)–
Creating HTML forms by embedding
JSP code (9 Hrs)
• Servlet technology is used to create a web
application (resides at server side and generates a
dynamic web page).
• What is a web application?
• A web application is an application accessible
from the web. A web application is composed of
web components like Servlet, JSP, Filter, etc. and
other elements such as HTML, CSS, and
JavaScript. The web components typically execute
in Web Server and respond to the HTTP request.
What is a Servlet?
Servlet can be described in many ways, depending on the context.

• Servlet is a technology which is used to create a web application.

• Servlet is an API that provides many interfaces and classes including


documentation.(Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.)

• Servlet is an interface that must be implemented for creating any


Servlet.

• Servlet is a class that extends the capabilities of the servers and


responds to the incoming requests. It can respond to any requests.

• Servlet is a web component that is deployed on the server to create


a dynamic web page.
CGI technology enables the web server to call an
external program and pass HTTP request information to
the external program to process the request. For each

request, it starts a new process.


Disadvantages of CGI

• There are many problems in CGI technology:


• If the number of clients increases, it takes
more time for sending the response.
• For each request, it starts a process, and the
web server is limited to start processes.
• It uses platform dependent language e.g. C,
C++, perl.
Advantages of Servlet
• There are many advantages of Servlet over CGI.
• The web container creates threads for handling the
multiple requests to the Servlet. Threads have many
benefits over the Processes such as they share a
common memory area, lightweight, cost of
communication between the threads are low. The
advantages of Servlet are as follows:
• Better performance: because it creates a thread for
each request, not process.
• Portability: because it uses Java language.
• Robust: JVM manages Servlets, so we don't need to
worry about the memory leak, garbage collection, etc.
• Secure: because it uses java language.
Servlets & JSPs

• Servlet Architecture
• Servlet lifecycle
• Request and Response
• Being a Web Container
• Session management
• Overview of JSP
• JSP Elements
Introduction – request-response model

• Request-response model.
HTTP
Request

request
Server

<html>
<head>
<html>
<body>
<head>

<body>

Client
response
HTTP

HTML
Introduction – what is a request and response

HTTP Request HTTP Response

Key elements of a “request” Key elements of a “response”


stream: stream:

 HTTP method (action to be  A status code (for whether


performed). the request was successful).

 The page to access (a URL).  Content-type (text, picture,


html, etc…).
 Form parameters.
 The content ( the actual
content).
Introduction – What is a Servlet

Where does Servlet come into the picture?


I can serve only
static HTML
pages
Web Server
Application

Not a problem.
I can handle
dynamic
requests.
Helper
Application
Web Server machine

“The Helper Application is nothing but a SERVLET”


Servlet Architecture -Web Container

• What is a Web Container?

request
GET.
GET. GET.
….. ….. …..

Web Web Servlet


Server Container
Client
Servlet Architecture – Web Container

• How does the Container handle a request?

request Servlet
Http request Web
Container
response
Thread
Web
Server

response <Html> Service()


Client <Body>
…….
</Body>
</Html>
doGet()
Servlet Architecture – Web Container

The CONTAINER
What is the role of Web Container ?
S2
• Communication Support
S1
• Lifecycle Management

• Multi-threading support JSP1

• Security S3

• JSP Support
S4

The container can contain multiple Servlets & JSPs within it


Servlet Architecture – Deployment Descriptor

• How does the Container know which Servlet the client has
requested for?

A Servlet can have 3 names <web-app>


………
 Client known URL name <servlet>
<servlet-name>LoginServ</servlet-name>
<servlet-class>com.Login</servlet-class>
 Deployer known secret </servlet>
internal name
<servlet-mapping>
<servlet-name>LoginServ</servlet-name>
 Actual file name <url-pattern>/Logon</url-pattern>
</servlet-mapping>
………..
………..
</web-app>
Web.xml
Servlet Lifecycle

• The Servlet lifecycle is simple, there is only one main state –


“Initialized”.

Does not exist

constructor()
destroy()
init()

Initialized

Service()
Servlet Lifecycle - Hierarchy

Interface Servlet

Abstract class GenericServlet If not overridden, implements init()


method from the ‘Servlet’ interface,

Abstract class HttpServlet If not overridden, implements service()


method.

Concrete class Your Servlet We implement the HTTP methods


here.
Servlet Lifecycle – 3 big moments

When is it called What it’s for Do you override


it
init() The container To initialize your
calls the init() servlet before
before the servlet handling any Possibly
can service any client requests.
client requests.
service() When a new To determine
request for that which HTTP No. Very unlikely
servlet comes in. method should be
called.

doGet() or The service() To handle the


doPost() method invokes it business logic.
based on the HTTP Always
method from the
request.
Servlet Lifecycle – Thread handling

• The Container runs multiple threads to process multiple


requests to a single servlet.
Container

Client A Client B

Servlet

Thread Thread
A B

response request request response


Request and Response – GET v/s POST

• The HTTP request method determines whether doGet() or


doPost() runs.
GET (doGet()) POST (doPost())

The request contains only the Along with request line


HTTP Request request line and HTTP header. and header it also contains
HTTP body.
Parameter The form elements are passed The form elements are
passing to the server by appending at passed in the body of the
the end of the URL. HTTP request.
Size The parameter data is limited Can send huge amount of
(the limit depends on the data to the server.
container)
Idempotency GET is Idempotent POST is not idempotent
Usage Generally used to fetch some Generally used to process
information from the host. the sent data.
Request and Response – The response

Request

Can the Servlet No Does the Servlet know


Serve the request? Who can serve?
No

Yes

Yes

Send Redirect
Send resource
Request Dispatcher Error page
Being a Web Container – Servlet Config and Context

Servlet Context

Servlet 1 Servlet 2 Servlet 3 JSP 1

Servlet Config Servlet Config Servlet Config Servlet Config


Being a Web Container – init parameters

• What are init parameters?


• Difference between Servlet Context and Config Init parameters

Context Init Parameters Servlet Init Parameters

Scope Scope is Web Container Specific to Servlet or JSP

Servlet code getServletContext() getServletConfig()

Deployment Within the <web-app> element Within the <servlet> element


Descriptor but not within a specific for each specific servlet
<servlet> element
Being a Web Container - Attributes

• What exactly, is an attribute?


• Difference between Attributes and parameters

Attributes Parameters

Context Context
Types Request Request
Session Servlet Init
We cannot set Init
Method to set setAttribute(String, Object) parameters.

Return type Object String

getInitParameter
Method to get getAttribute(String) (String)
Session Management – Session Tracking

• How sessions work? new


1 2
request, “dark”
ID# 42
“dark”
HttpSession
Client A

response, ID# 42 setAttribute(“dark”)


4 3
Container

ID# 42
“ale” “dark”
#42

Client A 1 HttpSession
request, “ale”, ID# 42
2
Container
Session Tracking – Cookies

HttpSession session = request.getSession(); Here’s your cookie


with session ID
inside…

HTTP/1.1 200 OK
Set-Cookie: JSESSIONID=0ABS
Content-Type: text/html
Client A Server: Apache-Coyote/1.1
<html>

</html>

Container
OK, here’s the HTTP Response
cookie with
my request

POST / login.do HTTP/1.1

Cookie: JSESSIONID=0ABS
Accept: text/html……

Client A
HTTP Request Container
Session Tracking – URL Rewriting

URL ;jsessionid=1234567
Container
HTTP/1.1 200 OK
Content-Type: text/html
Server: Apache-Coyote/1.1
<html>
<body>
< a href =“ http:// www.sharmanj.com/Metavante;jsessionid=0AAB”>
click me </a>
Client A </html>
HTTP Response

GET /Metavante;jsessionid=0AAB

HTTP / 1.1
Host: www.sharmanj.com
Accept: text/html

Client A HTTP Request Container


Servlet Mechanics
• A servlet is a Java class and thus needs to be
executed in a Java Virtual Machine by a
service called a servlet engine. The servlet
engine loads the servlet before it can be used.
The servlet then stays loaded until it is
unloaded or the servlet engine is shut down.
Servlet Engines
• Some web servers, including Sun Java Web
Server, W3C Jigsaw, and Gefion LiteWebServer
are implemented in Java and have a built in
servlet engine.
• High end commercial servers like Websphere
and Web Logic tend to include a servlet engine.
• Other web servers such as Microsoft IIS and
Apache require a servlet add-on module which
must be loaded separately.
Overview of Servlet Technology
• Servlets
– Analog to applets
• Execute on server's machine, supported by most
web servers
– Demonstrate communication via HTTP protocol
• Client sends HTTP request
• Server receives request, servlets process it
• Results returned (HTML document, images, binary
data)
The Servlet API
• Servlet interface
– Implemented by all servlets
– Many methods invoked automatically by server
• Similar to applets (paint, init, start, etc.)
– abstract classes that implement Servlet
• GenericServlet (javax.servlet)
• HTTPServlet (javax.servlet.http)
– Examples in chapter extend HTTPServlet
• Methods
– void init( ServletConfig config )
• Automatically called, argument provided
The Servlet API
• Methods
– ServletConfig getServletConfig()
• Returns reference to object, gives access to config info
– void service ( ServletRequest
request, ServletResponse response )
• Key method in all servlets
• Provide access to input and output streams
– Read from and send to client
– void destroy()
• Cleanup method, called when servlet exiting
HttpServlet Class
• HttpServlet
– Base class for web-based servlets
– Overrides method service
• Request methods:
– GET - retrieve HTML documents or image
– POST - send server data from HTML form
– Methods doGet and doPost respond to GET and
POST
• Called by service
• Receive HttpServletRequest and
HttpServletResponse (return void) objects
HttpServletRequest Interface
• HttpServletRequest interface
– Object passed to doGet and doPost
– Extends ServletRequest
• Methods
– String getParameter( String name )
• Returns value of parameter name (part of GET or POST)
– Enumeration getParameterNames()
• Returns names of parameters (POST)
– String[] getParameterValues( String
name )
• Returns array of strings containing values of a parameter
– Cookie[] getCookies()
• Returns array of Cookie objects, can be used to identify
client
Creating Servlet Example in Eclipse

• Eclipse is an open-source ide for developing JavaSE and JavaEE


(J2EE) applications. You can download the eclipse ide from the
eclipse website http://www.eclipse.org/downloads/.
• You need to download the eclipse ide for JavaEE developers.
• Creating servlet example in eclipse ide, saves a lot of work to be
done. It is easy and simple to create a servlet example. Let's see the
steps, you need to follow to create the first servlet example.

1. Create a Dynamic web project


2. create a servlet
3. add servlet-api.jar file
4. Run the servlet
1.Create the dynamic web project:

For creating a dynamic web project click on File


Menu -> New -> Project..-> Web -> dynamic
web project -> write your project name e.g.
first -> Finish.
2) Create the servlet in eclipse IDE:

For creating a servlet, explore the project by clicking the


+ icon -> explore the Java Resources -> right click on
src -> New -> servlet -> write your servlet name

e.g. Hello -> uncheck all the checkboxes except doGet()


-> next -> Finish.
3) add jar file in eclipse IDE:
For adding a jar file, right click on your project -
> Build Path -> Configure Build Path -> click
on Libraries tab in Java Build Path -> click on
Add External JARs button -> select the
servlet-api.jar file under tomcat/lib -> ok.
4) Start the server and deploy the project:
For starting the server and deploying the project
in one step, Right click on your project -> Run
As -> Run on Server -> choose tomcat server -
> next -> addAll -> finish.
• Now tomcat server has been started and
project is deployed. To access the servlet write
the url pattern name in the URL bar of the
browser. In this case Hello then enter.
• How to configure tomcat server in Eclipse ? (One
time Requirement)
• If you are using Eclipse IDE first time, you need to
configure the tomcat server First.
• For configuring the tomcat server in eclipse
IDE, click on servers tab at the bottom side of
the IDE -> right click on blank area -> New ->
Servers -> choose tomcat then its version -> next
-> click on Browse button -> select the apache
tomcat root folder previous to bin -> next ->
addAll -> Finish.
• Servlet Example by implementing Servlet
interface
• Servlet Interface
• Servlet interface provides common behavior to
all the servlets.Servlet interface defines methods
that all servlets must implement.
• Servlet interface needs to be implemented for
creating any servlet (either directly or indirectly).
It provides 3 life cycle methods that are used to
initialize the servlet, to service the requests, and
to destroy the servlet and 2 non-life cycle
methods.
File: First.java
import java.io.*;
import javax.servlet.*;

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
Life Cycle of Servlet
servlet

GenericServlet HttpServlet

init(ServletConfig);

doGet(HttpServletRequest,
service(ServletRequest,
HttpServletResponse);
ServletResponse);
doPost(HttpServletRequest,
HttpServletResponse);
destroy(); …….
HttpServletResponse Interface
• HttpServletResponse
– Object passed to doGet and doPost
– Extends ServletResponse
• Methods
– void addCookie( Cookie cookie )
• Add Cookie to header of response to client
– ServletOutputStream
getOutputStream()
• Gets byte-based output stream, send binary data to client
– PrintWriter getWriter()
• Gets character-based output stream, send text to client
– void setContentType( String type )
• Specify MIME type of the response (Multipurpose Internet Mail
Extensions)
• MIME type “text/html” indicates that response is HTML document.
• Helps display data
Handling HTTP GET Requests
• HTTP GET requests
– Usually gets content of specified URL
• Usually HTML document (web page)
• Example servlet
– Handles HTTP GET requests
– User clicks Get Page button in HTML document
• GET request sent to servlet HTTPGetServlet
– Servlet dynamically creates HTML document
displaying "Welcome to Servlets!"
Handling HTTP GET Requests
3 import javax.servlet.*;
4 import javax.servlet.http.*;

– Use data types from javax.servlet and


javax.servlet.http
7 public class HTTPGetServlet extends HttpServlet {

– HttpServlet has useful methods, inherit from it


8 public void doGet( HttpServletRequest request,
9 HttpServletResponse response )
10 throws ServletException, IOException

– Method doGet
• Responds to GET requests
• Default action: BAD_REQUEST error (file not found)
• Override for custom GET processing
• Arguments represent client request and server response
Handling HTTP GET Requests
14 response.setContentType( "text/html" ); // content type

– setContentType
• Specify content
12 •PrintWriter
text/html for HTML documents
output;
15 output = response.getWriter(); // get writer

– getWriter
• Returns PrintWriter object, can send text to client
• getOutputStream to send binary data (returns
ServletOutputStream object)
Handling HTTP GET Requests
19 buf.append( "<HTML><HEAD><TITLE>\n" );
20 buf.append( "A Simple Servlet Example\n" );
21 buf.append( "</TITLE></HEAD><BODY>\n" );
22 buf.append( "<H1>Welcome to Servlets!</H1>\n" );
23 buf.append( "</BODY></HTML>" );

24 output.println( buf.toString() );
25 – Lines 19-23 create HTML document
output.close(); // close PrintWriter stream

• println sends response to client


• close terminates output stream
– Flushes buffer, sends info to client
Handling HTTP GET Requests
• Running servlets
– Must be running on a server
• Check documentation for how to install servlets
• Tomcat web server
• Apache Tomcat
Handling HTTP GET Requests
• Port number
– Where server waits for client (handshake point)
– Client must specify proper port number
• Integers 1 - 65535, 1024 and below usually reserved
– Well-known port numbers
• Web servers - port 80 default
• JSDK/Apache Tomcat 4.0 Webserver- port 8080
– Change in default.cfg (server.port=8080)
Handling HTTP GET Requests
• HTML documents
1 <!-- Fig. 19.6: HTTPGetServlet.html -->
2 <HTML>
3 <HEAD>
4 <TITLE>
5 Servlet HTTP GET Example
6 </TITLE>
7 </HEAD>

– Comments: <!-- text -->


– Tags: <TAG> ... </TAG>
• <HTML> ... <HTML> tags enclose document
• <HEAD> ... </HEAD> - enclose header
– Includes <TITLE> Title </TITLE> tags
– Sets title of document
9
Handling HTTP GET Requests
<FORM
10 ACTION="http://lab.cs.siu.edu:8080/rahimi/HTTPGetServlet"
11 METHOD="GET">
12 <P>Click the button to have the servlet send
13 an HTML document</P>
14 <INPUT TYPE="submit" VALUE="Get HTML Document">
15 </FORM>
16 </BODY>

– Document body (<BODY> tags)


• Has literal text and tags for formatting
– Form (<FORM> tags )
• ACTION - server-side form handler
• METHOD - request type
Handling HTTP GET Requests
10 ACTION="http://localhost:8080/servlet/HTTPGetServlet"

– ACTION
• localhost - your computer
• :8080 - port
14
• /servlet - directory
<INPUT TYPE="submit" VALUE="Get HTML Document">

– GUI component
• INPUT element
• TYPE - "submit" (button)
• VALUE - label
• When pressed, performs ACTION
• If parameters passed, separated by ? in URL
1 // Fig. 19.5: HTTPGetServlet.java
2 // Creating and sending a page to the client
3 import javax.servlet.*;
4 import javax.servlet.http.*; Import necessary classes and inherit
5 import java.io.*;
methods from HttpServlet.
6
7 public class HTTPGetServlet extends HttpServlet {
8 public void doGet( HttpServletRequest request,
9 HttpServletResponse response )
10 throws ServletException, IOException
11 {
12 PrintWriter output;
13
14 response.setContentType( "text/html" ); // content type
15 output = response.getWriter(); // get writer
16
1. import
17 // create and send HTML page to client
1.1 extends HttpServlet
Create PrintWriter object.
18 StringBuffer buf = new StringBuffer();
19 buf.append( "<HTML><HEAD><TITLE>\n"2. doGet
);
Create HTML file and send to
20 2.1 setContentType
buf.append( "A Simple Servlet Example\n" ); client.
21 2.2 getWriter
buf.append( "</TITLE></HEAD><BODY>\n" );
22 buf.append( "<H1>Welcome to Servlets!</H1>\n"
2.3 println );
23 buf.append( "</BODY></HTML>" );
24 output.println( buf.toString() );
25 output.close(); // close PrintWriter stream
26 }
27 }
1 <!-- Fig. 19.6: HTTPGetServlet.html -->
2 <HTML>
3 <HEAD>
4 <TITLE>
5 Servlet HTTP GET Example ACTION specifies form
6 </TITLE>
handler, METHOD specifies
7 </HEAD>
8 <BODY>
request type.
9 <FORM
10 ACTION="http://lab.cs.siu.edu:8080/rahimi/HTTPGetServlet"
11 METHOD="GET">
12 <P>Click the button to have the servlet send
13 an HTML document</P>
14 <INPUT TYPE="submit" VALUE="Get HTML Document">
15 </FORM>
16 </BODY> HTML document

17 </HTML> Creates submit button,


1. <TITLE>

performs ACTION
2. <FORM> when

clicked. 2.1 ACTION

2.2 METHOD

3. INPUT TYPE
Program Output
Handling HTTP POST Requests
• HTTP POST
– Used to post data to server-side form handler (i.e.
surveys)
– Both GET and POST can supply parameters
• Example servlet
– Survey
• Store results in file on server
– User selects radio button, presses Submit
• Browser sends POST request to servlet
– Servlet updates responses
• Displays cumulative results
Handling HTTP POST Requests
9 public class HTTPPostServlet extends HttpServlet {

– Extend HttpServlet
• Handle GET and POST
10 private String animalNames[] =
11 { "dog", "cat", "bird", "snake", "none" };

– Array for animal names


13 public void doPost( HttpServletRequest request,
14 HttpServletResponse response )
15 throws ServletException, IOException

– doPost
• Responds to POST requests (default BAD_REQUEST)
• Same arguments as doGet (client request, server response)
18
Handling HTTP POST Requests
File f = new File( "survey.txt" );
23 ObjectInputStream input = new ObjectInputStream(
24 new FileInputStream( f ) );
26 animals = (int []) input.readObject();

40 – Open survey.txt,
String value = load animals array
41 request.getParameter( "animal" );

– Method getParameter( name )


• Returns value of parameter as a string
64 response.setContentType( "text/html" ); // content type

– Content type
67
Handling HTTP POST Requests
StringBuffer buf = new StringBuffer();
68 buf.append( "<html>\n" );
69 buf.append( "<title>Thank you!</title>\n" );
70 buf.append( "Thank you for participating.\n" );
71 buf.append( "<BR>Results:\n<PRE>" );
73 DecimalFormat twoDigits = new DecimalFormat( "#0.00" );
74 for ( int i = 0; i < percentages.length; ++i ) {
75 buf.append( "<BR>" );
76 buf.append( animalNames[ i ] );
88 responseOutput.println( buf.toString() );

– Return HTML document as before


– <PRE> tag
• Preformatted text, fixed-width
– <BR> tag - line break
8
Handling HTTP POST Requests
<FORM METHOD="POST" ACTION=
9 "http://lab.cs.siu.edu:8080/rahimi/HTTPPostServlet">
10 What is your favorite pet?<BR><BR>
11 <INPUT TYPE=radio NAME=animal VALUE=dog>Dog<BR>
12 <INPUT TYPE=radio NAME=animal VALUE=cat>Cat<BR>
13 <INPUT TYPE=radio NAME=animal VALUE=bird>Bird<BR>
14 <INPUT TYPE=radio NAME=animal VALUE=snake>Snake<BR>
15 <INPUT TYPE=radio NAME=animal VALUE=none CHECKED>None
16 <BR><BR><INPUT TYPE=submit VALUE="Submit">
17 <INPUT TYPE=reset>
18 </FORM>

– METHOD="POST"
– Radio buttons (only one may be selected)
• TYPE - radio
• NAME - parameter name
• VALUE - parameter value
• CHECKED - initially selected
8
Handling HTTP POST Requests
<FORM METHOD="POST" ACTION=
9 "http://lab.cs.siu.edu:8080/rahimi/HTTPPostServlet">
10 What is your favorite pet?<BR><BR>
11 <INPUT TYPE=radio NAME=animal VALUE=dog>Dog<BR>
12 <INPUT TYPE=radio NAME=animal VALUE=cat>Cat<BR>
13 <INPUT TYPE=radio NAME=animal VALUE=bird>Bird<BR>
14 <INPUT TYPE=radio NAME=animal VALUE=snake>Snake<BR>
15 <INPUT TYPE=radio NAME=animal VALUE=none CHECKED>None
16 <BR><BR><INPUT TYPE=submit VALUE="Submit">
17 <INPUT TYPE=reset>
18 </FORM>

– Submit button (executes ACTION)


– Reset button - browser resets form, with None
selected
1 // Fig. 19.7: HTTPPostServlet.java
2 // A simple survey servlet
3 import javax.servlet.*;
4 import javax.servlet.http.*; Extending HttpServlet allows
5 import java.text.*; processing of GET and POST
6 import java.io.*;
7 import java.util.*;
requests.
8
9 public class HTTPPostServlet extends HttpServlet {
10 private String animalNames[] =
11 { "dog", "cat", "bird", "snake", "none" };
12
13 public void doPost( HttpServletRequest request,
14 HttpServletResponse response )
15 throws ServletException, IOException
16 {
17 int animals[] = null, total = 0;
18 File f = new File( "survey.txt" );
19 1. import
20 if ( f.exists() ) {
21 1.1 extends HttpServlet
// Determine # of survey responses so far
22 try { 1.2 animalNames
23 ObjectInputStream input = new ObjectInputStream(
24 new FileInputStream( f ) 2. );doPost
25 2.1 Open file
26 animals = (int []) input.readObject();
27 input.close(); // close stream
28
29 for ( int i = 0; i < animals.length; ++i )
30 total += animals[ i ];
31 }
32 catch( ClassNotFoundException cnfe ) {
33 cnfe.printStackTrace();
34 }
35 } Use request (HttpServletRequest)
36 else method getParameter to get value of
37 animals = new int[ 5 ]; animal.
38
39 // read current survey response
40 String value =
41 request.getParameter( "animal" );
42 ++total; // update total of all responses
43
44 // determine which was selected and update its total
45 for ( int i = 0; i < animalNames.length; ++i )
46 if ( value.equals( animalNames[ i ] ) )
47 ++animals[ i ];
48
49 // write updated totals out to disk
50 ObjectOutputStream output = new ObjectOutputStream(
51 new FileOutputStream( f ) );
52
53
2.2 getParameter
output.writeObject( animals );
54 output.flush();
55 output.close();
56
57 // Calculate percentages
2.3 Write to file
58 double percentages[] = new double[ animals.length ];
59
60 for ( int i = 0; i < percentages.length; ++i )
61 percentages[ i ] = 100.0 * animals[ i ] / total;
62
63 // send a thank you message to client
64 response.setContentType( "text/html" ); // content type
65
66 PrintWriter responseOutput = response.getWriter();
67 StringBuffer buf = new StringBuffer();
68 buf.append( "<html>\n" );
69 buf.append( "<title>Thank you!</title>\n" );
70 buf.append( "Thank you for participating.\n" );
71 buf.append( "<BR>Results:\n<PRE>" );
72
73 DecimalFormat twoDigits = new DecimalFormat( "#0.00" );
74 for ( int i = 0; i < percentages.length; ++i ) {
75 buf.append( "<BR>" );
76 buf.append( animalNames[ i ] );
77 buf.append( ": " );
78 buf.append( twoDigits.format( percentages[ i ] ) );
79 buf.append( "% responses: " );
80 buf.append( animals[ i ] );
81 buf.append( "\n" ); 2.4 getWriter
82 }
83
2.5 Create HTML code
84 buf.append( "\n<BR><BR>Total responses: " );
85 buf.append( total );
86 ); println
buf.append( "</PRE>\n</html>" 2.6
87
88 responseOutput.println( buf.toString() );
89 responseOutput.close();
90 }
91 }
1 <!-- Fig. 19.8: HTTPPostServlet.html -->
2 <HTML>
3 <HEAD>
4 <TITLE>Servlet HTTP Post Example</TITLE>
5 </HEAD>
Use a POST request
6
7 <BODY>
type.
8 <FORM METHOD="POST" ACTION=
9 "http://lab.cs.siu.edu:8080/rahimi/HTTPPostServlet">
10 What is your favorite pet?<BR><BR>
11 <INPUT TYPE=radio NAME=animal VALUE=dog>Dog<BR>
12 <INPUT TYPE=radio NAME=animal VALUE=cat>Cat<BR>
13 <INPUT TYPE=radio NAME=animal VALUE=bird>Bird<BR>
14 <INPUT TYPE=radio NAME=animal VALUE=snake>Snake<BR>
15 <INPUT TYPE=radio NAME=animal VALUE=none CHECKED>None
16 <BR><BR><INPUT TYPE=submit VALUE="Submit">
17 <INPUT TYPE=reset>
HTML file
18 </FORM>
19 </BODY> 1. <FORM>
Create radio buttons. Specify parameter
20 </HTML>
name and value. None is initially
1.1 METHOD="POST"
selected (CHECKED).
Returns form to original state 2. <INPUT>
(None selected).
Program Output
Program Output
Session Tracking
• Web sites
– Many have custom web pages/functionality
• Custom home pages - http://my.yahoo.com/
• Shopping carts
• Marketing
– HTTP protocol does not support persistent
information
• Cannot distinguish clients
• Distinguishing clients
– Cookies
– Session Tracking
Cookies
• Cookies
– Small files that store information on client's computer
– Servlet can check previous cookies for information
• Header
– In every HTTP client-server interaction
– Contains information about request (GET or POST)
and cookies stored on client machine
– Response header includes cookies servers wants to
store
• Age
– Cookies have a lifespan
– Can set maximum age
• Cookies can expire and are deleted
Cookies
• Example
– Demonstrate cookies
– Servlet handles both POST and GET requests
– User selects programming language (radio buttons)
• POST - Add cookie containing language, return HTML page
• GET - Browser sends cookies to servlet
– Servlet returns HTML document with recommended books
– Two separate HTML files
• One invokes POST, the other GET
• Same ACTION - invoke same servlet
Cookies
14 public void doPost( HttpServletRequest request,
15 HttpServletResponse response )

19 String language = request.getParameter( "lang" );

– Method doPost
21
• Cookie
Get language selection
c = new Cookie( language, getISBN( language ) );
22 c.setMaxAge( 120 ); // seconds until cookie removed

– Cookie constructor
• Cookie ( name, value )
• getISBN is utility method
• setMaxAge( seconds ) - deleted when expire
Cookies
23 response.addCookie( c ); // must precede getWriter

– Add cookie to client response


• Part of HTTP header, must come first
41 •public
Thenvoid
HTML document
doGet( sent to client
HttpServletRequest request,
42 HttpServletResponse response )

46 Cookie cookies[];
48 cookies = request.getCookies(); // get client's cookies

– Method doGet
– getCookies
• Returns array of Cookies
57
Cookies
if ( cookies != null ) {
62 output.println(
63 cookies[ i ].getName() + " How to Program. " +
64 "ISBN#: " + cookies[ i ].getValue() + "<BR>" );

– Cookie methods
• getName, getValue
• Used to determine recommended book
• If cookie has expired, does not execute
1 // Fig. 19.9: CookieExample.java
2 // Using cookies. Allows class to handle
3 import javax.servlet.*;
GET and POST.
4 import javax.servlet.http.*;
5 import java.io.*;
6
7 public class CookieExample extends HttpServlet {
8 private String names[] = { "C", "C++", "Java",
9 "Visual Basic 6" };
10 private String isbn[] = {
11 "0-13-226119-7", "0-13-528910-6",
12 "0-13-012507-5", "0-13-528910-6" };
13
14 public void doPost( HttpServletRequest request,
15 Create a new Cookie,
HttpServletResponse response )
16 throws ServletException, IOException
initialized with language
1. import
17 {
18 PrintWriter output;
parameter.1.1 extends HttpServlet

2. doPost
19 String language = request.getParameter( "lang" );
2.1 getParameter
20
21 2.2 Cookie
Cookie c = new Cookie( language, getISBN( language ) );
22 c.setMaxAge( 120 ); // seconds until cookie removed
2.3 setMaxAge

23 response.addCookie( c ); // must 2.4precede


addCookie getWriter

24
25 response.setContentType( "text/html" ); Set maximum age of
26 output = response.getWriter(); cookie, add to header.
27
28 // send HTML page to client
29 output.println( "<HTML><HEAD><TITLE>" );
30 output.println( "Cookies" );
31 output.println( "</TITLE></HEAD><BODY>" );
32 output.println( "<P>Welcome to Cookies!<BR>" );
33 output.println( "<P>" );
34 output.println( language );
35 output.println( " is a great language." );
36 output.println( "</BODY></HTML>" );
37
38 output.close(); // close stream
39 }
40
41 public void doGet( HttpServletRequest request,
42 HttpServletResponse response )
43 throws ServletException, IOException
44 {
45 PrintWriter output; Returns array of
46 Cookie cookies[]; Cookies.
47
48
3. doGet
cookies = request.getCookies(); // get client's cookies
49
50 response.setContentType( "text/html" );
51
52
3.1 getCookies
output = response.getWriter();

53 output.println( "<HTML><HEAD><TITLE>" );
54 output.println( "Cookies II" );
55 output.println( "</TITLE></HEAD><BODY>" );
56
57 if ( cookies != null ) {
58 output.println( "<H1>Recommendations</H1>" );
59
60 // get the name of each cookie
61 for ( int i = 0; i < cookies.length; i++ )
62 output.println(
63 cookies[ i ].getName() + " How to Program. " +
64 "ISBN#: " + cookies[ i ].getValue() + "<BR>" );
65 }
66 else {
67 output.println( "<H1>No Recommendations</H1>" Use
); cookies to determine
68 output.println( "You did not select a languagerecommended
or" ); book and
69 output.println( "the cookies have expired." );ISBN.
70 }
71
72 output.println( "</BODY></HTML>" ); If cookies have expired,
73 output.close(); // close stream no recommendations.
74 }
75
76
3.2 getName, getValue
private String getISBN( String lang )
77 {
78 for ( int i = 0; i < names.length; ++i )
79 4. Method getISBN
if ( lang.equals( names[ i ] ) )
80 return isbn[ i ];
81
82 return ""; // no matching string found
83 }
84 }
1 <!-- Fig. 19.10: SelectLanguage.html -->
2 <HTML>
3 <HEAD>
4 <TITLE>Cookies</TITLE>
5 </HEAD>
6 <BODY>
7 <FORM ACTION="http://lab.cs.siu.edu:8080/rahimi/CookieExample"
8 METHOD="POST">
9 <STRONG>Select a programming language:<br>
10 </STRONG><BR>
11 <PRE>
12 <INPUT TYPE="radio" NAME="lang" VALUE="C">C<BR>
13 <INPUT TYPE="radio" NAME="lang" VALUE="C++">C++<BR>
14 <INPUT TYPE="radio" NAME="lang" VALUE="Java"
15 CHECKED>Java<BR> HTML file
16 <INPUT TYPE="radio" NAME="lang"
17 1. POST
VALUE="Visual Basic 6">Visual Basic 6
18 </PRE>
19 <INPUT TYPE="submit" VALUE="Submit">
2. Radio buttons
20 <INPUT TYPE="reset"> </P>
21 </FORM>
22 </BODY>
23 </HTML>
1 <!-- Fig. 19.11: BookRecommendation.html -->
2 <HTML>
3 <HEAD>
4 <TITLE>Cookies</TITLE>
5 </HEAD>
6 <BODY>
7 <FORM ACTION="http://lab.cs.siu.edu:8080/rahimi/CookieExample"
8 METHOD="GET">
9 Press "Recommend books" for a list of books.
10 <INPUT TYPE=submit VALUE="Recommend books">
11 </FORM>
12 </BODY>
13 </HTML>

HTML file

1. GET

2. Submit
Program Output
Session Tracking with HttpSession
• HttpSession (javax.servlet.http)
– Alternative to cookies
– Data available until browsing ends
• Methods
–23Creation
HttpSession session = request.getSession( true );

– getSession( createNew )
• Class HttpServletRequest
• Returns client's previous HttpSession object
• createNew - if true, creates new HttpSession object
if does not exist
Session Tracking with HttpSession
26 session.putValue( language, getISBN( language ) );

– putvalue( name, value )


• Adds a name/value pair to object
58 valueNames = session.getValueNames();
73 for ( int i = 0; i < valueNames.length; i++ ) {
74 String value =
75 (String) session.getValue( valueNames[ i ] );

– getValueNames()
• Returns array of Strings with names
– getValue( name )
• Returns value of name as an Object
• Cast to proper type
Session Tracking with HttpSession
• Redo previous example
– Use HttpSession instead of cookies
– Use same HTML files as before
• Change ACTION URL to new servlet
1 // Fig. 19.13: SessionExample.java
2 // Using sessions.
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import java.io.*;
6
7 public class SessionExample extends HttpServlet {
8 private final static String names[] =
9 { "C", "C++", "Java", "Visual Basic 6" };
10 private final static String isbn[] = {
11 "0-13-226119-7", "0-13-528910-6",
12 "0-13-012507-5", "0-13-528910-6" };
13
14 public void doPost( HttpServletRequest request,
15 HttpServletResponse response )
16 throws ServletException, IOException
17 { 1. import
18 PrintWriter output;
19 2. doPost
String language = request.getParameter( "lang" ); Load HttpSession
20 if exists, create if does
2.1 getSession
21 // Get the user's session object. not.
22 // Create a session (true) if one
2.2 does not exist.
putValue
23 HttpSession session = request.getSession( true );
24 Set name/value
25 // add a value for user's choice to session pair.
26 session.putValue( language, getISBN( language ) );
27
28 response.setContentType( "text/html" );
29 output = response.getWriter();
30
31 // send HTML page to client
32 output.println( "<HTML><HEAD><TITLE>" );
33 output.println( "Sessions" );
34 output.println( "</TITLE></HEAD><BODY>" );
35 output.println( "<P>Welcome to Sessions!<BR>" );
36 output.println( "<P>" );
37 output.println( language );
38 output.println( " is a great language." );
39 output.println( "</BODY></HTML>" );
40
41 output.close(); // close stream
42 }
43
44 public void doGet( HttpServletRequest request,
45 HttpServletResponse response )
46 throws ServletException, IOException
Do not create object if does
47
48
{
PrintWriter output;
3. doGet not exist. session set to
49 null.
50 // Get the user's session object.
51
52
3.1 getSession
// Don't create a session (false) if one does not exist.
HttpSession session = request.getSession( false );
53

54 // get names of session object's values


55 String valueNames[];
56
57 if ( session != null )
58 valueNames = session.getValueNames();
59 else
60 valueNames = null;
61
Put names into
62 response.setContentType( "text/html" ); array.
63 output = response.getWriter();
64
65 output.println( "<HTML><HEAD><TITLE>" );
66 output.println( "Sessions II" );
67 output.println( "</TITLE></HEAD><BODY>" );
68
69 if ( valueNames != null && valueNames.length != 0 ) {
70 output.println( "<H1>Recommendations</H1>" );
71
72 // get value for each name in valueNames
73 for ( int i = 0; i < valueNames.length; i++ ) {
74 String value =
75 (String) session.getValue( valueNames[ i ] );
76
77
3.2 getValueNames
output.println(
78 valueNames[ i ] + " How to Program. " + Get value associated with
79 "ISBN#: " + value + "<BR>" );
name.
80
81 }
}
3.3 getValue
82 else {
83 output.println( "<H1>No Recommendations</H1>" );
84 output.println( "You did not select a language or" );
85 output.println( "the session has expired." );
86 }
87
88 output.println( "</BODY></HTML>" );
89 output.close(); // close stream
90 }
91
92 private String getISBN( String lang )
93 {
94 for ( int i = 0; i < names.length; ++i )
95 if ( lang.equals( names[ i ] ) )
96 return isbn[ i ];
97
98 return ""; // no matching string found
99 }
100 }
Program Output
Program Output
Program Output
Multitier Applications: Using JDBC
from a Servlet
• Servlets and databases
– Communicate via JDBC
• Connect to databases in general manner
• Use SQL-based queries
• Three tier distributed applications
– User interface
• Often in HTML, sometimes applets
• HTML preferred, more portable
– Business logic (middle tier)
• Accesses database
– Database access
– Three tiers may be on separate computers
• Web servers for middle tier
Multitier Applications: Using JDBC
from a Servlet
• Servlets
– Method init
• Called exactly once, before client requests
• Initialization parameters
– Method destroy
• Called automatically, cleanup method
• Close files, connections to databases, etc.
Multitier Applications: Using JDBC
from a Servlet
• HTML files
– <INPUT TYPE=CHECKBOX NAME=name VALUE=value>
• Creates checkbox, any number can be selected

– <INPUT TYPE=TEXT NAME=name>


• Creates text field, user can input data
Multitier Applications: Using JDBC
from a Servlet
• Example servlet
– Guest book to register for mailing lists
– HTML document first tier
• Get data from user
– Use servlet as middle tier
• Provides access to database
• Set up connection in init
– Microsoft Access database (third tier)
1 // Fig. 19.16: GuestBookServlet.java
2 // Three-Tier Example
3 import java.io.*;
4 import javax.servlet.*;
5 import javax.servlet.http.*;
6 import java.util.*;
7 import java.sql.*;
8
9 public class GuestBookServlet extends HttpServlet {
10 private Statement statement = null;
11 private Connection connection = null;
12 private String URL = "jdbc:odbc:GuestBook";
13
14 public void init( ServletConfig config )
15 throws ServletException
16 { init called exactly once, before
17 super.init( config );
client requests are processed.
18
1. import Note the first line format.
19 try {
20 Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver"
1.1 URL );
21 connection =
22 init"", "" );
DriverManager.getConnection(2.URL,
23 }
24 catch ( Exception e ) { 2.1 Connect to database
25 e.printStackTrace();
26 connection = null; Get connection to database (no
27 } name/password).
28 }
29
30 public void doPost( HttpServletRequest req,
31 HttpServletResponse res )
32 throws ServletException, IOException
33 {
34 String email, firstName, lastName, company,
35 snailmailList, cppList, javaList, vbList,
36 iwwwList;
37
38 email = req.getParameter( "Email" );
39 firstName = req.getParameter( "FirstName" );
40 lastName = req.getParameter( "LastName" );
41 company = req.getParameter( "Company" );
42 snailmailList = req.getParameter( "mail" );
43 cppList = req.getParameter( "c_cpp" );
44 javaList = req.getParameter( "java" );
45 vbList = req.getParameter( "vb" );
46 iwwwList = req.getParameter( "iwww" );
47
48 3. doPost
PrintWriter output = res.getWriter();
49 res.setContentType( "text/html" );
50 3.1 getParameter
51 if ( email.equals( "" ) ||
52 firstName.equals( "" ) || 3.2 getWriter
53 lastName.equals( "" ) ) {
3.3 println
54 output.println( "<H3> Please click the back " +
55 "button and fill in all " +
56 "fields.</H3>" );
57 output.close();
58 return;
59 }
60
61 /* Note: The GuestBook database actually contains fields
62 * Address1, Address2, City, State and Zip that are not
63 * used in this example. However, the insert into the
64 * database must still account for these fields. */
65 boolean success = insertIntoDB(
66 "'" + email + "','" + firstName + "','" + lastName +
67 "','" + company + "',' ',' ',' ',' ',' ','" +
68 ( snailmailList != null ? "yes" : "no" ) + "','" +
69 ( cppList != null ? "yes" : "no" ) + "','" +
70 ( javaList != null ? "yes" : "no" ) + "','" +
71 ( vbList != null ? "yes" : "no" ) + "','" +
72 ( iwwwList != null ? "yes" : "no" ) + "'" );
73
74 if ( success )
75 output.print( "<H2>Thank you " + firstName +
76 " for registering.</H2>" );
77 else
78
79
4. insertIntoDB
output.print( "<H2>An error occurred. " +
"Please try again later.</H2>" );
80
81 output.close();
82 } 4.1 createStatement
83
84 private boolean insertIntoDB( String stringtoinsert )
85 {
86 try {
87 statement = connection.createStatement();
88 statement.execute(
89 "INSERT INTO GuestBook values (" +
90 stringtoinsert + ");" );
91 statement.close(); Insert data into
92 } database.
93 catch ( Exception e ) {
94 System.err.println(
95 "ERROR: Problems with adding new entry" );
96 e.printStackTrace();
97 return false;
98 }
99
100 return true;
101 }
102 destroy called
103 public void destroy() automatically, closes
104 {
105 try {
connection to database.
106 connection.close();
107 }
4.2 INSERT INTO
108 catch( Exception e ) {
109 destroy
System.err.println( "Problem5.closing the database" );
110 }
111 }
112 } 5.1 close
1 <!-- Fig. 19.17: GuestBookForm.html -->
2 <HTML>
3 <HEAD>
4 <TITLE>Deitel Guest Book Form</TITLE>
5 </HEAD>
6
7 <BODY>
8 <H1>Guest Book</H1>
9 <FORM
10 ACTION=http://lab.cs.siu.edu:8080/rahimi/GuestBookServlet
11 METHOD=POST><PRE>
12 * Email address: <INPUT TYPE=text NAME=Email>
13 * First Name: <INPUT TYPE=text NAME=FirstName>
14 * Last name: <INPUT TYPE=text NAME=LastName>
15 Company: <INPUT TYPE=text NAME=Company>
16
17 * fields are required
18 </PRE>
HTML file
19 Create text fields
20 <P>Select mailing lists from which you want
1. <FORM> and checkboxes for
21 to receive information<BR>
user input.
22 <INPUT TYPE=CHECKBOX NAME=mail 1.1 TYPE=text
VALUE=mail>
23 Snail Mail<BR>
24 2. TYPE=CHECKBOX
<INPUT TYPE=CHECKBOX NAME=c_cpp VALUE=c_cpp>
25 <I>C++ How to Program & C How to Program</I><BR>
26 <INPUT TYPE=CHECKBOX NAME=java VALUE=java>
27 <I>Java How to Program</I><BR>
28 <INPUT TYPE=CHECKBOX NAME=vb VALUE=vb>
29 <I>Visual Basic How to Program</I><BR>
30
31 <INPUT TYPE=CHECKBOX NAME=iwww VALUE=iwww>
32 <I>Internet and World Wide Web How to Program</I><BR>
33 </P>
34 <INPUT TYPE=SUBMIT Value="Submit">
35 </FORM>
36 </BODY>
37 </HTML>
Program Output
Program Output
Electronic Commerce
• Revolution in electronic commerce
– 2/3 of stock transactions by 2007
– amazon.com, ebay.com, huge volumes of
sales
– Business to business transactions
– Servlet technology
• Help companies get into e-commerce
– Client-server systems
• Many developers use all Java
• Applets for client, servlets for server
Java Server Pages (JSP)

110
Servlets & JSPs
Java Server Pages (JSP)

Agenda

• Introduction
• JSP Elements
• Implicit Objects
• Tag Libraries
• JSP Actions
• Error Handling
• Demo

111
Introduction – What is JSP

• JSP Stands for Java Server Pages


• Presents dynamic content to users
• Handles the presentation logic in an MVC architecture

(business logic)

request servlet

Business Tier
Container

Helper
Objects

JSP
(presentation logic)
response

112
Introduction – JSP v/s Servlet

How is JSP different / similar to Servlet?

Servlets JSP

Handles dynamic data

Handles business logic Handles presentation logic


Lifecylce methods
Lifecylce methods
jspInit() : can be overridden
init() : can be overridden
_jspService() : cannot be overridden
service() : can be overridden
jspDestroy() : can be overridden
destroy() : can be overridden

Html within java Java within html


out.println(“<htrml><body>”); <html><body>
out.println(“Time is” + new Date()); Time is <%=new Date()%>
out.println(“</body></html>”); </body></html>

Runs within a Web Container


113
Introduction – JSP is a Servlet

• In the end, a JSP is just a Servlet

Is translated to Compiles to Is loaded and


Initialized as
writes Import javax. 0010 0001
JSP
servlet. 1100 1001 Servlet
HttpServlet.* 0001 0011

MyJsp.jsp MyJsp_jsp.java MyJsp_jsp.class MyJsp_jsp


Servlet

114
Introduction – Comments

• JSP Comments
 <%-- {CODE HERE} --%>
 Does not show the comments on the page
 Does not show the comments in page source
 Can only be used outside JSP Elements

• HTML Comments
 <!– {CODE HERE} -->
 Does not show the comments on the page
 Shows the comments in page source
 Can only be used outside JSP Elements

• Single line Comments


 // {CODE HERE}
 When put outside JSP Elements, shows comments on the page & source
 When put inside Scriptlets/Declarations, does not show on page &
source
 Can be used inside scriptlets/declarations and outside JSP Elements
115
JSP Elements – Intro

• Need to write some Java in your HTML?

• Want to make your HTML more dynamic?

 JSP Declarations :: Code that goes outside the service method

 JSP Scriptlets :: Code that goes within the service method

 JSP Expressions :: Code inside expressions is evaluated

 JSP Directives :: Commands given to the JSP engine

116
JSP Elements - Declarations

• What are declarations?


– Whatever goes inside the “<%!{JAVA_HERE}%>” tags is called a declaration
– Everything you write in a declarations goes outside the service method
– Treat them as instance methods and instance variables

• What do you declare in declarations?


– You can declare methods and variables in declarations

• Why do you need declarations?


– You have any variable that needs to be shared across different requests.
– You have repeated common code in you jsp, declare it in a method.

• Example
<%! int instanceVar = 10; %>

117
JSP Elements - Declarations

Request 1

Service1 Service2 Service3

Request 2

Declarations

Request 3

118
JSP Elements - Scriptlets

• What are declarations?


– Whatever goes inside the “<%{JAVA_HERE}%>” tags is called a scriptlet
– Everything you write in a scriptlets goes in the service method
– Treat variables in scriptlets as method/local variables

• What do you put in scriptlets?


– Business logic in JSPs are put in scriptlets. Set of java statements

• Why do you need scriptlets?


– Need to perform some small business logic (if logic is complex, do in java)
– Need to perform some basic validations

• Example
<% int localVar = 10; %>

119
JSP Elements - Expressions

• What are expressions?


– Whatever goes inside the “<%={JAVA_HERE}%>” tags is called an expression
– Code inside expressions is evaluated, and output is displayed
– Whatever is put inside expressions should evaluate to a value

• What do you put in scriptlets?


– Variables or methods that return some values

• Why do you need scriptlets?


– Need to print some text onto the page

• Example
<%= localVar %>

120
JSP Elements - Example

<html><head><title>JSP Elements Example</title>


</head>
<body> Declarations
<%! int userCnt = 0; %>

<% Scriptlets
String name = "Sharad";
userCnt++;
%> Expressions
<table>
<tr><td>
Welcome <%=name%>. You are user number <%=userCnt%>
</td></tr>
</table>
</body>
</html>

121
JSP Elements - Directives

• What are directives?


– Whatever goes inside the “<%@{DIRECTIVES}%>” tags is called a directive
– Directives gives pre-processing commands to the JSP Engine.
– Everything in directives are processed before JSP is translated to Servlet

• What do you put in directives?


– Processing commands to the JSP Engine.

• Why do you need directives?


– To incorporate certain additional features into the JSP
– Modifying the Servlet behaviour generated from the JSP
– Include other html/jsp files in the JSP.
– Provide tag libraries

Example
<%@ page import=“java.util.ArrayList” %>
122
Directives – page directive

• Any number of the pre-defined attributes can be added to the page directive

<%@ page import = “{IMPORTED_CLASSES}”


contentType = “{CONTENT_TYPE}”
isThreadSafe = “{true/false}
session = “{true/false}”
buffer = “{BUFFER_SIZE}”
autoflush = “{true/false}”
extends = “{EXTENDS_FROM_PAGE}”
info = “{PAGE_INFO”}
errorPage = “{ERROR_PAGE_NAME}”
isErrorPage = “{true/false}”
language = “{LANGUAGE}”

123
Directives – include directive

• Including other page content into your JSP


<%@ include file = {PAGE_URL_TO_INCLUDE} %>
• Includes files at translation time
• If included file is modified, the main jsp needs to be recompiled

<%@ include file =“header.jsp"/>


Hello <%=userName%>

header.jsp
Main page
<%@ include file =“footer.jsp"/>
<table><tr>
<td>Contact Details</td>
<tr></table>

main.jsp footer.jsp
124
Directives – taglib directive

• Providing output based on common custom logic

<%@ taglib uri=“{TLD_FILE}" prefix=“{PREFIX}" %>

• Components involved in tag libraries

 Tag handler class


 Common custom logic and HTML generation

 Descriptor configuration file


 Directive’s properties mapping information

 taglib directive
 Used in JSPs to use the tag handler functionality
125
taglib directive – high-level overview

<tag>
<name>txtBox</name>
<%@ taglib uri=“sharmanjTags” prefix=“sharmanj” %> <tagclass>TxtBoxTag</tagclass>
….. <bodycontent>EMPTY</bodycontent>
< sharmanj:txtBox length=“10“ name=“userName”/> <attribute>
….. <name>name</name>
<required>true</required>
test.jsp ….
</attribute>

</tag>

sharmanj-taglib.tld

<web-app>
<taglib>
<taglib-uri>sharmanjTags</taglib-uri> public class TxtBoxTag extends TagSupport {
<taglib-location> public int doStartTag() {
sharmanj-taglib.tld ….
</taglib-location> }
</taglib> }
</web-app>
TxtBoxTag.java
web.xml

126
Implicit Objects - Introduction

• Set of predefined objects readily available for use.

– out: JspWriter
– request: HttpRequest
– response: HttpResponse
– session: HttpSession
– config: ServletConfig
– application: ServletContex
– page: JSP page
– pageContext: Special object

127
Implicit Objects - Example

<html>
<head>
<title>JSP Implicit objects Example</title>
</head>
<body>
<%
if (“YES”.equals(request.getAttribute(“SCOPE”))) {
out.println(“REQUEST”);
} else {
if (“YES”.equals(session.getAttribute(“SCOPE”))) {
out.println(“SESSION”);
} else {
out.println(“NONE”);
}
}
%>
</body>
</html>

128
Implicit Objects – out

• An instance of JspWriter

• Writes statements to the page

• The java way to display text on the webpage

• Displaying dynamic data

129
Implicit Objects – request

• Instance of HttpServletRequest
• Use the attributes stored in request object for display /basic
validations in JSP

Forwards request to JSP


Servlet JSP
request.setAttribute(“a”, “10”)

a = 10

Helper
Uses helper Object
object
(a = 10)

130
Implicit Objects – response

• Instance of HttpServletResponse
• Send the response back to the client (HTML in most of the
cases)

Send response to client

JSP1

response.sendRedirect(“url”);

Redirect to JSP2 Send response to client


JSP1 JSP2

131
Implicit Objects – session

• Instance of HttpSession
• Retrieve and set the session attributes in JSP
• Remember the client across multiple requests

Request 1

Response1

Web App CLIENT


Request 1

Response2

SESSION
132
Implicit Objects – config and application

• config - Instance of ServletConfig


• Application – instance of ServletContext
Servlet Context

JSP 1 JSP 1 JSP 1 JSP 1

133
Servlet Config Servlet Config Servlet Config Servlet Config
Implicit Objects – page

Hello <%=userName%>
<jsp:include page=“/header.jsp"/>

header.jsp

Main page
<table><tr>
<td>Contact Details</td>
<tr></table>
<jsp:include page=“/footer.jsp"/>

footer.jsp
main.jsp
134
Implicit Objects – pageContext

Least visible to most visible

application

session

pageContext

request

page

135
JSP Actions

• Special tags which provides special features

• The container handles these tags in a special way

• Addresses certain common functionalities

• Achieve functionality with less code, and more standard way

<jsp:include>
<jsp:forward>
<jsp:param>
<jsp:useBean>
<jsp:getProperty>
<jsp:setProperty>
136
JSP Actions - <jsp:include>

Definition:
Includes a page at the given location in the main page

Syntax:

<jsp:include page="{PAGE_TO_INCLUDE}" flush="true" />

137
JSP Actions – Include Action v/s Include Directive

Include Directive Include Action

Translation time Run time

Copies the included file References to the included file

For static content For dynamic content

Cannot pass parameters Can pass parameters

138
JSP Actions - <jsp:forward>

Definition:
Forwards the request to the given page

Syntax:

<jsp:forward page=“{PAGE_TO_FORWARD}" />

139
JSP Actions - <jsp:param>

Definition:
Pass parameters to the included/forwarded page

Syntax:

<jsp:include page="{PAGE_TO_INCLUDE}" flush="true" >


<jsp:param name=“{parameterName}” value="{paramValue}" />
</jsp:include>

<jsp:forward page="{PAGE_TO_FORWARD}" flush="true" >


<jsp:param name=“{parameterName}” value="{paramValue}" />
</jsp:forward>

140
JSP Actions - <jsp:useBean>

getId();
setId(..)
getName()
How can I use
setName(…)
that bean?

bean

Servlet JSP

request.setAttribute(“userBean”, userBean”) <jsp:useBean …./>

141
JSP Actions - <jsp:useBean>

Definition:
Instantiate a bean class, use bean properties, and set property values

Syntax:

<jsp:useBean id=“{beanInstanceName}"
scope="page|request|session|application"
class=“{package.class}"
type=“{package.class}"
beanName=" {package.beanName}”>
</ jsp:useBean>

UserBean ub = new UserBean();


142
JSP Actions - <jsp:getProperty>

Definition:
Gets property values of a Bean

Syntax:

<jsp:getProperty name=“{beanInstanceName}"
property= “{propertyName}">

143
JSP Actions - <jsp:setProperty>

Definition:
Sets property values in a Bean

Syntax:

<jsp:setProperty name=“{beanInstanceName}"
property= "*" | property="propertyName"
param=“{parameterName}"
value="{paramValue}" } />

144
JSP Actions – useBean

<jsp:useBean id=“userBean"
scope="session“
class=“com.sharmanj.UserBean" >
<jsp:setProperty name=“userBean”
property=“userName”
value=“Sharad”/>
</ jsp:useBean>

<jsp:getProperty name=“userBean" property=“userName" />

145
Error Handling – Types of errors

• Errors in java code in scriptlets


 handle errors in try/catch block
 may occur at runtime

• Errors in HTML

 adhere to the HTML rules

 can be caught during testing


146
Error Handling

Why is error handling important in JSPs?

147
Error Handling – Error page

• Error pages come to the rescue

<%@page isErrorPage="true" %>


<html>
<head>
<title>My Error Page</title>
</head>
<body>
We are sorry, the page you are
trying to access is currently not
available. Please try after some time
</body>
</html>

148
Error Handling

• Specify error page in your main page • Specify error page in web.xml
<%@page errorPage=“errPage.jsp" %> <web-app>
<html> …………….
<head> ……………
<title>This is the main page</title>
</head> <error-page>
<body> <exception-type>com.a.myExp</exception-type>
………………….. <location>/error.jsp</location>
………………….. </error-page>

…………………… <error-page>
…………………… <error-code>404</error-code>
<location>/errorServlet</location>
// ERROR CODE GOES HERE </error-page>

………………….
…………………. ………………..
</body> ……………….
</html> </web-app>
149
JSP Overview - Servlets v/s JSPs

JSPs : Java within HTML


Servlets : HTML within Java
Presentation logic
business logic

public void doGet(request, response) <html>


{ <body>
PrintWriter out = response.getWriter(); <% String name =
String name = request.getParameter(name); %>
request.getParameter(name);
out.println(“<html><body>”); Hello <%= name %>
out.println("Hello” + name);
out.println(“</body></html>”); </body>
} </html>
JSP Elements – JSP to Servlet

• Where does the JSP code land in the Servlet?

import javax.servlet.HttpServlet.*
<%@ page import=“foo.*” %>
import foo.*;
public class MyJsp_jsp extends
<html>
HttpServlet
<body>
{
int count = 0;
<% int i = 10; %>
public void display()
<%! int count = 0; %>
{
out.println(“Hello”);
Hello! Welcome
}
public void _jspService(req, res)
<%! Public void display()
{
{
int i = 0;
out.println(“Hello”);
out.println(“<html>\r<body>”);
} %>
out.println(“Hello! Welcome”);
}
</body>
}
</html>
JSP Overview - What is a JSP

• In the end, a JSP is just a Servlet.

Is translated to Compiles to Is loaded and


Initialized as
writes Import javax. 0010 0001
JSP
servlet. 1100 1001 Servlet
HttpServlet.* 0001 0011

MyJsp.jsp MyJsp_jsp.java MyJsp_jsp.class MyJsp_jsp


Servlet
Thanks

153