2. Document Version: 1.00
2
Contents to be covered………
Presentation Component
Introduction to HTTP
Developing JEE Web Module
Servlet
Request Forwarding
Cookies
Session Handling
3. Document Version: 1.00
3
Presentation component
For web based enterprise application , UI is displayed
through browser .
UI is rendered through web page.
Web pages are required to be generated dynamically
by executing algorithm.
This algorithm is known as presentation logic and
written as presentation component.
Presentation component is written as servlet and
JSP.
Communication protocol -- HTTP
5. Document Version: 1.00
5
HTTP Model
Request for web page/image
Response from server
Web Server
Request is always made as a form of URL
6. Document Version: 1.00
6
Hypertext Transport Protocol
When A URL is entered in the address bar of a browser , client(browser),
sends a request for a resource to a server and server sends back response
correspoding to resource
A resource can be HTML file, image or a program that generates the
response dynamically
9. Document Version: 1.00
9
HTTP Request Message
Request Message is understandable format for
HTTP.
Request message contains name and path of the
resource.
Type of the request .
name/IP of the computer where above mentioned
resource can be located.
Some other information for the request .
Data to be used by server side program.(POST)
12. Document Version: 1.00
12
Web Server Comp
httpd
From
browser
shopping/index.html C:fileshtmlwebsiteindex.html
URI Web Resource
13. Document Version: 1.00
13
Web Server Comp
httpd
Browser
Response message
(contains HTML to
be displayed by
browser)
Response
14. Document Version: 1.00
14
Response Message
HTTP/1.1 200 OK
Date: Tue, 21 May 2002 12:34:56 GMT
Server: Apache/1.3.22 (Unix) (Red-Hat/Linux) mod_python/2.7.8 Python/1.5.2 mod_ssl/2.8.5
OpenSSL/0.9.6b DAV/1.0.2 PHP/4.0.6 mod_perl/1.26 mod_throttle/3.1.2
Last-Modified: Thu, 01 Nov 2001 20:51:45 GMT
Accept-Ranges: bytes
Content-Length: 2890
Connection: close
Content-Type: text/html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html>
<head>
<title>Test Page for the Apache Web Server on Red Hat Linux</title> </head>
<body bgcolor="#ffffff">
………
……….
</body>
</html>
15. Document Version: 1.00
15
HTTP request types
HTTP request made from the browser are of 8 types.
HEAD , GET , POST , PUT , DELETE , TRACE , TRACE ,
OPTIONS , CONNECT
They are also known as request methods.
From browser , GET and POST type of request can be made.
Entering an URL in the address bar to see a web page generates a GET
request
Clicking an hyperlink generates a GET request
When a Form has “method=post” , a POST request is generated by
browser.
16. Document Version: 1.00
16
URI
The URI does not necessarily correspond to a static file in the
server . It can identify an executable program ,a record in
database or pretty much any thing web server knows about.
In fact there is no way to tell if ‘/shopping/index.html’ URI
corresponds to file or something else ; it is just a name that
means something to server . The web server is configured to
map these unique names to the real resources
17. Document Version: 1.00
17
Static HTML
We know web pages can be created by coding in HTML and then saving
those HTML in a file having extension html/xhtml/htm.
Static html
All requester are going to see exactly same web page.
Home pages of a web site can be developed using static html
18. Document Version: 1.00
18
Dynamic HTML
Some time we need to create HTML programmatically , by processing
some data.
For example , inbox web page of every user is different .
To cater this type of requirement , we need to write a program , which
will do the following :
Receive username and password entered by the user through browser.
Search the database for all mail for that user.
Creates a web page , which will contain all the data it retrieved from
the database.
Send that page back to browser to display inbox web page.
This program is running inside the web server.
This program will have a URI (remember URI is part of URL)
19. Document Version: 1.00
19
Dynamic HTML
So , programs that generate HTML runs within the web server.
They are known as server side program
But , then , how to execute them …. ?
They are executed by using there URL from the browser.
Server side programs are executed from the browser by using there URL
.
How to send data to the server side program…?
Using request parameters.
20. Document Version: 1.00
20
Request Parameters
Suppose a user wants to see result of sum of two numbers as
a web page displayed in his/her browser. User will supply
numbers through browser.
A program must be executed on the web server , which will
receive two numbers , process them , generate a HTML page,
send that page as response back to browser.
User request execution of this program , by writing URL of
this program.
How user sends two numbers i.e. data to be processed by this
program.
In HTTP terminology data , that are passed from browser for
processing by server side program , is known as “Request
Parameter”
21. Document Version: 1.00
21
Request Parameters
Request parameters are name , value pair
i.e. every data , that is passed to the server side program for processing
, must have a name part.
Ex : first=12 , second=25
If more than one request parameter are there ,i.e. server side program
needs more than one data as input , then all the request parameters are
concatenated using “&” symbol
first=12&passwd=25
This string is passed from the browser to the web server
As query string , in case of “GET” request
As payload , in case of “POST” request
22. Document Version: 1.00
22
Request Parameters for GET request
Consider the URL bellow.
http://www.abc.com/calc/addnumbers?first=1&second=2
“first=1” is a request parameter
Name=value
Query String == “first=1&second=2”
For GET request , concatenated request parameters are passed as query
string along with the URL
23. Document Version: 1.00
23
Request Parameters for POST request
POST /calc/addnumbers HTTP/1.1
Host: www.abc.com
User-Agent : Mozilla/5.0
Accept: image/gif, image/jpeg
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
first=1&second=2
For the POST request data goes as payload of request message
25. Document Version: 1.00
25
Module and Component
In JEE , we code algorithms as component.
These components resides into module
For different types of component different modules are created. i.e. for
web component web module is created etc.
Modules are OS file and they are of Java archive format
Created using ‘jar’ utility .
In JEE , module are equivalent to application.
26. Document Version: 1.00
26
Types of Modules
Web Module
Contains web components
EJB Module
Contains EJB components
Resource Adapter Module
For connecting to external system
Application Client Module
Utility Module
Enterprise application module
27. Document Version: 1.00
27
JEE Application Architecture
JEE application is packaged into Enterprise Appilcation module having
extension “ear”.
This is also known as EAR file
This EAR file contains Web Modules , EJB Modules
All web components are packaged into Web Module
Extension of Web Module is “war”
All EJB components are packaged into EJB module -Extension of
EJB module is “jar”
28. Document Version: 1.00
28
JEE Application
Components Java EE Modules
DD
DD
JEE Application
Web Module
EJB Module
DD
Web Module
DD
EJB Module
DD
DD = Deployment Descriptor
Ent App Module
29. Document Version: 1.00
29
Deployment Descriptor
Every JEE module has one and only one Deployment Descriptor(DD)
DD contains information about all components in that module
DD is XML file
Name of this XML file is different for different module
For web module name is web.xml
For EJB module name is ejb-jar.xml
For Ent App module name is application.xml
31. Document Version: 1.00
31
Different Phases of Developing Web Module
Coding/developing web components using servlet / JSP technology
Packaging components into module
Modules are OS file in Java Archive Format(JAR)
Web modules are OS file having extension “war”
All web modules are added to enterprise application module (OS file
,extension “ear”)
Deploying into App Server
Enterprise App Modules gets deployed into App Server
32. Document Version: 1.00
32
Web Module (WAR)
folder
WEB-INF
classes lib
(Html,jsp,gif files)
( web.xml )
( .class files ) ( Library files(.jar,.zip) )
Compressed
into a file
having
extension
war
33. Document Version: 1.00
33
Deployment Descriptor
A xml file, containing configuration information of a particular module
For web module this is named as web.xml
Every J2EE web module must have one (and only one) web.xml
All servlets, listeners,filters are registered in web.xml
35. Document Version: 1.00
35
Servlet
J2EE web component to generate HTML dynamically
A java class which implements an interface – “Servlet” of package
javax.servlet and defines all methods declared
Method “service(ServletRequest , ServletResponse)” contains algorithm
to generate html programmatically .
37. Document Version: 1.00
37
Steps to develop simple servlet
Write a java class by implementing Servlet interface
interface Servlet belongs to the package : javax.servlet
Write algorithm to generate web page dynamically in “service” method.
Compile and copy “.class” file to the “classes” folder
This step will be done by eclipse
Register servlet in web.xml file
Here URI for the servlet is provided
38. Document Version: 1.00
38
Servlet Code
package org.servlet;
import java.io.*;
import javax.servlet.*;
public class FirstServlet implements Servlet {
public void destroy() {}
public ServletConfig getServletConfig() {
return null;
}
public String getServletInfo() {
return null;
}
public void init(ServletConfig arg0) throws ServletException { }
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// Here we write page generation code
}
}
41. Document Version: 1.00
41
HTTPD
Web Container EJB Container
•J2EE Application server contains HTTPD
•So J2EE app server can listen to incoming
web request.
•OR , we can say J2EE app server contains ,
one web server built into it .
Handling a Request
46. Document Version: 1.00
46
ServletRequest
When a client sends a request to application server , it sends few
information along with the request.
An object of type ServletRequest is used to access those information.
This object provides informations like
IP address of the client which sends the request .
Protocol used by the client (HTTP , HTTPS , …).
Request parameters sent by the client are retrieved through this object.
This object is created by web container and passed as a parameter to
“service” method.
47. Document Version: 1.00
47
ServletResponse
Servlet generates HTML and this HTML must be displayed in client browser
An object of type ServletResponse is used to send generated HTML to client
browser.
In servlet code ,ServletResponse object is used to gather generated contents
into it.
This is done by retrieving an object of PrintWriter from ServletRequest
PrintWriter out=res.getWriter();
This object is also created by web container and passed as second parameter to
“service” method
Servlet can send data other than HTML too …like images
Type of data that is being send must be specified at the beginning and this
is done using this object.
Method that is required to be called
• setContentType(String mimetype)
• Above method must be called before getWriter is called.
48. Document Version: 1.00
48
Context Root
To create web portal for an enterprise , we need to develop more than one
web module .
Lets consider an example :
Suppose a bank’s website has three sections , for accounts , loan and
cards. Each section has many web pages to offer and these pages must
be generated dynamically.
For each section one web module is developed
49. Document Version: 1.00
49
Context Root
……. Continuing from the previous example
• From the browser user must enter appropriate URL to go to a particular section
– For example : http://www.smartbank.com/accounts/login.html -- for login
in accounts section
– http://www.smartbank.com/loan/apply -- applying for a loan
– http://www.smartbank.com/cards/listallcards.jsp -- to see list of all cards
offered by the bank
50. Document Version: 1.00
50
Context Root
When request reaches to web container how web container find which
URL is for what web module ?
By inspecting context root
In the URL , http://www.bank.com/loan/apply -- context root is “loan”
Context root identifies web module uniquely
……. Continuing from the previous example
52. Document Version: 1.00
52
Context Root
Context root of a web module is specified in application.xml –
Deployment Descriptor of Enterprise Application Module
53. Document Version: 1.00
53
Activity- Developing A Web App
<form action="AdderServlet" method="get">
First No <input type="text" name="first"/>
Second No <input type="text" name="second"/>
<input type="submit"/>
</form>
54. Document Version: 1.00
54
<form action="AdderServlet" method="get">
First No <input type="text" name="first"/>
Second No <input type="text" name="second"/>
<input type="submit"/>
</form>
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String strfirst=req.getParameter(“first”);
int first=Integer.parseInt(strfirst);
Name of
input type
field must be
passd as
parameter
Activity- Developing A Web App
55. Document Version: 1.00
55
Servlet to which a form is submitted , follows a particular pattern :-
All values that are submitted through the form are retrieved.
• By calling “getParameter” many times
• All these form values are of String type.
They must be converted into appropriate type before processing them.
Activity- Developing A Web App
56. Document Version: 1.00
56
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
----------------------------
----------------------------
String strfirst=req.getParameter(“first”);
String strsecond=req.getParameter(“second”);
int first=Integer.parseInt(strfirst);
int second=Integer.parseInt(strsecond);
-------------------------------------
------------------------------------
}
retrieval
conversion
Activity- Developing A Web App
57. Document Version: 1.00
57
Points to remember
Values entered in different fields of <form> are retrieved as String (and
only as String).
If the value that are passed as a parameter to “getParameter” does not
match with name of the any input field of <form> then :
It returns “null”
It does not throw any exception
59. Document Version: 1.00
59
Servlet Object Creation Steps
An object of servlet class is created by calling default
constructor.
Servlet object is created by web container
Servlet class must have a default constructor.
“init(ServletConfig cfg)” is called on the newly created servlet
object.
‘init()’ plays the role of constructor in servet.
Servlet object is created only for the first request. From the
next request onwards same servlet object will be reused . No
new servlet object will be created .
60. Document Version: 1.00
60
Interface ServletConfig
Configuration information about a servlet is written in Deployment
Descriptor(web.xml)
Servlet class name , servlet name , uri
Web container retrieves those information and stores them into an object
of type ServletConfig
ServletConfig object is created by web container and it is passed as a
parameter to init.
61. Document Version: 1.00
61
Interface ServletConfig
ServletConfig has appropriate methods , those can be called to get
configuration information about a servlet.
Important methods :
public String getInitParameter(String name)
public ServletContext getServletContext()
62. Document Version: 1.00
62
Tricks of using ServletConfig
Parameter variables of a method is local (auto) variable.
Whenever control goes out of block local variable gets destroyed.
So, ServletConfig reference that was passed to “init(ServletConfig)”
method gets lost , when control comes out of the block , as
ServletConfig variable is used as parameter .
Then , how can we get ServletConfig reference, if it is required later in
service method ?
63. Document Version: 1.00
63
Tricks of using ServletConfig
Declare a reference variable of type ServletConfig in your servlet class
private ServletConfig config;
In your “init” method store the passed reference in variable “config”
public void init(ServletConfig cfg){
config=cfg;
}
As ServletConfig reference is stored in an instance variable , it is available
till servlet object is not destroyed .
64. Document Version: 1.00
64
public void service(ServletRequest
req,ServletResponse res){
}
Web Container
Servlet object
Thread
created by
web cont
66. Document Version: 1.00
66
Servlet execution
After servlet object is created and init() completed , web
container creates a thread and this thread calls “service”
method.
For every web request for a servlet , a thread will created
by web container.
Remember , servlet object is created for the first request
From second request onwards , same object is used , but
different thread is created .
All these thread calls the service method of the same
servlet object.
67. Document Version: 1.00
67
Destroying servlet
When a web application is stopped or undeployed, all servlet
object is removed from web container.
Before removing servlet object from the container
,”destroy()” is called on the servlet object by Web Container.
69. Document Version: 1.00
69
Initializing a Servlet
How to initialize data members of a servlet class ?.
Parametarized constructor is of no use for a servlet
zero parameter constructor is used to create servlet object
by web container.
Initial values are specified through deployment descriptor.
71. Document Version: 1.00
71
Accesing initial values
Use “getInitParameter(String p)” of ‘ServletConfig’ .
String v=config.getInitParameter(“var1”);
Above call returns value “value1” in v .
72. Document Version: 1.00
72
GenericServlet
Coding a servlet by implementing Servlet interface is
complex.
Five methods are to be defined.
abstract class GenericServlet implements interface
Servlet partially.
It does not defines “service(…)”. Thus abstract.
Code a java class by extending GenericServlet and
overriding service(..) method.
Another way to develop servlet
74. Document Version: 1.00
74
Background tricks of GenericServlet
GenericServlet employs some useful tricks to make life of developer easy
.
Apart from having init(ServletConfig), available from Servlet interface ,
it declares another init method that does not accept any parameter i.e. init
method is overloaded.
void init(ServletConfig cfg)
void init()
it declares a variable of type ServletConfig as field.
75. Document Version: 1.00
75
Background tricks of GenericServlet
public class GenericServlet implements Servlet,ServletConfig{
private ServletConfig config;
public void init(ServletConfig cfg){
config=cfg;
init();
}
public void init(){}
public ServletConfig getServletConfig(){
return config;
}
-----------------
-----------------
}
76. Document Version: 1.00
76
How does it helps
Tricks employed in GenericServlet , helps us writing “init” method
There is no need to override init(ServletConfig) in our servlet class that
extends GenericServlet
Overriding “init()” is sufficient
No need to worry about ServletConfig object that was passed to
init(ServletConfig) , because that object will be available through
instance variable.
77. Document Version: 1.00
77
public class AddServlet extends GenericServlet{
public void init(){
// your servlet initialization logic
// ServletConfig object is already saved in instance
// variable
}
public void service(ServletRequest req,ServletResponse res){
// your HTML page generation logic
}
-----------------
-----------------
}
78. Document Version: 1.00
78
Using Methods of GenericServlet
public class AddServlet extends GenericServlet{
public void init(){
// Call methods inherited from base class
String var1 = getInitParameter(“var1”);
}
public void service(ServletRequest req,ServletResponse res){
//Call methods inherited from base class
String var1 = getInitParameter(“var1”);
}
-----------------
-----------------
}
79. Document Version: 1.00
79
Explanation
So , whenever a new request for AddServlet comes , web container creates
an object of AddServlet , by calling the default constructor.
Web container calls , init(ServletConfig) , which is available to
AddServlet from GenericServlet .
From init(ServletConfig) control goes to init() .Initially init() was also
available from GenericServlet.
As AddServlet has overridden init() in its class, so instead of calling init()
of GenericServlet , it call init() of AddServlet.(Due to dyn polymorphism)
80. Document Version: 1.00
80
Background Tricks of GenericServlet
Abstract class GenericServlet has implemented Servlet as well as
ServletConfig interface
So , all methods that are declared in ServletConfig , available in
GenericServlet.
81. Document Version: 1.00
81
Background tricks of GenericServlet
public class GenericServlet implements Servlet,ServletConfig{
private ServletConfig config;
public String getInitParameter(String nm){
String value=config.getInitParameter(nm);
return value;
}
public String getServletName(){
String name=config.getServletName();
return name;
}
-----------------
-----------------
}
83. Document Version: 1.00
83
Servlet and HTTP
Many protocols are in use for WWW.
Ex . ftp, smtp, news , telnet etc
HTTP is most pervasive
Dynamic content generation is required not only for
HTTP but other protocols of WWW too.
interface Servlet and abstract class GenericServlet
are not specific to any protocol.
It is not possible to use any HTTP protocol specific
properties .
GenericServlet class is root of all servlet class
regardless of any protocol.
84. Document Version: 1.00
84
HttpServlet
Use of servlet in HTTP protocol is very frequent.
Servlets are used to generate HTML on request basis.
JEE provides an abstract class HttpServlet ,
which can be used as a base class to code a HTTP
bases servlet.
class HttpServlet is inherited from GenericServlet and
available in package javax.servlet.http .
This class lets us HTTP protocol specific
properties.
Simplifies writing HTTP based servlet class.
87. Document Version: 1.00
87
Using HttpServlet
Our servlet class extends HttpServlet
Depending on the requirement , we need to override either “doGet” or
“doPost” method .
Both of them can be overridden in a single servlet class
When it is necessary to treat GET request and POST request separately.
There is usefull coding style – that will be revealed later.
88. Document Version: 1.00
88
Coding using HttpServlet
We need to import following package (atleast) :
package org.servlet; // package name can be anything
import java.io.*; // service() throws IOException
import javax.servlet.*; // service() throws ServletException
import javax.servlet.http.*; // as HttpServlet is being extended
Our servlet class must be part of a package . Not for
syntactical reason but for security
89. Document Version: 1.00
89
Coding using HttpServlet
public class AnyServlet extends HttpServlet{
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException
{
}
//either doGet or doPost or both
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException
{
}
}
90. Document Version: 1.00
90
HttpServlet
public void service(ServletRequest req,ServletResponse res)
public void service(HttpServletRequest req,HttpServletResponse res)
delegates
GET or POST?
public void doGet(….) public void doPost(….)
GET POST
91. Document Version: 1.00
91
Coding Style
Provide a user defined method (name can be anything) and write HTML
generation logic there , instead of writing them in doGet or doPost
Call this method from doGet or doPost
92. Document Version: 1.00
92
Coding style
public class AnyServlet extends HttpServlet{
public void process(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException
{
// this is user defined method , containing HTML gen
//logic , it can be named anything
}
}
93. Document Version: 1.00
93
Coding style
public class AnyServlet extends HttpServlet{
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException
{
process(req,res);
}
//either doGet or doPost or both
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException
{
process(req,res);
}
}
94. Document Version: 1.00
94
<form action="initservlet" method="post">
FIRST <input type=text name="first"/><br>
SECOND <input type="text" name="second"/><br>
<input type="submit"/>
</form>
95. Document Version: 1.00
95
POST Request Message
POST /servletweb/initservlet HTTP/1.1
Accept: image/gif, image/x-xbitmap,.....
Referer: http://localhost:8080/servletweb/posttest.html
Accept-Language: en-us
Content-Type: application/x-www-form-urlencoded
UA-CPU: x86
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; FDM)
Host: 127.0.0.1:8081
Content-Length: 24
Connection: Keep-Alive
Cache-Control: no-cache
first=12&second=45
96. Document Version: 1.00
96
GET Request Message
GET /servletweb/initservlet?first=12&second=45 HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg,...
Referer: http://localhost:8081/servletweb/posttest.html
Accept-Language: en-us
UA-CPU: x86
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; FDM)
Host: 127.0.0.1:8081
Connection: Keep-Alive
97. Document Version: 1.00
97
Connecting to Database
To connect to database driver class is required, which is available in driver
jar file.
This driver jar file must be available in classpath.
This driver jar file must be copied in the “lib” folder
Any jar file copied to “lib” folder , taken into classpath.
98. Document Version: 1.00
98
Connecting to Database
Lets take an example :- Suppose we are entering student record
into a student table. Data for a student is taken from a web page.
Student table is created in MySQL.
99. Document Version: 1.00
99
Connecting to Database
<form action="CreateServlet" method="post">
Roll <input type="text" name="roll" /><br/>
Name <input type="text" name="name" /><br/>
Marks <input type="text" name="marks" /><br/>
<input type="submit" /><br/>
</form>
100. Document Version: 1.00
100
Connecting to Database
Codes can be written either in doPost or in doGet method
For this problem doPost must be used .
Servlet to which form is submitted must perform 2 steps discussed earlier.
Retrieval
Conversion
101. Document Version: 1.00
101
Connecting to Database
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
………………………
// retrieving form data
String strroll=request.getParameter("roll");
String strname=request.getParameter("name");
String strmarks=request.getParameter("marks");
// converting them to appropriate data type
int roll=Integer.parseInt(strroll);
int marks=Integer.parseInt(strmarks);
………………………………………….
}
102. Document Version: 1.00
102
Connecting to Database
Variables required to establish connection are declared here.
To connect using JDBC following informations are required
• Driver class name
• Jdbc url
• User name
• Password
Variables declared to hold above information .
103. Document Version: 1.00
103
Connecting to Database
// following variables are required for JDBC connection
String driver="com.mysql.jdbc.Driver";
String jdbcurl="jdbc:mysql://localhost:3306/gps";
String user=“your username";
String password=“your password";
Here we are considering MySQL
104. Document Version: 1.00
104
Connecting to Database
Variables for JDBC operation related data
A string variable to hold SQL statement (insert statement for this case )
Connection variable
PreparedStatement variable
105. Document Version: 1.00
105
Connecting to Database
// variable required for JDBC operation
String sql="insert into student(roll,name,marks) values (?,?,?)";
Connection conn=null;
PreparedStatement pstmt=null;
106. Document Version: 1.00
106
Connecting to Database
Now the code which will do the task of inserting
Class.forName(driver);
conn=DriverManager.getConnection(jdbcurl,user,password);
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, roll);
pstmt.setString(2, strname);
pstmt.setInt(3, marks);
pstmt.executeUpdate();
forName() throws checked exception ClassNotFoundException
prepareStatement () , setters , executeUpdate throws SQLException.
These checked exceptions are required to be handled
107. Document Version: 1.00
107
Connecting to Database
try {
// codes from previous slide comes here
} catch (ClassNotFoundException e) {
e.printStackTrace();
out.println("<h3>error occured while loading driver....</h3>");
} catch (SQLException e) {
e.printStackTrace();
out.println("<h3>error occured in sql operation :
"+e.getMessage()+"</h3>");
}
108. Document Version: 1.00
108
Connecting to Database
•But , connection must be closed . Best place for closing
connection is “finally” block.
•Before closing connection , we should check connection was
opened or not
finally{
if (conn !=null){
try {
conn.close();
} catch (SQLException e) {}
}
}
109. Document Version: 1.00
109
A small problem….
The servlet that we have created in last exercise can handle post request
only.
It has code written in doPost() only.
What will happen , if any user accesses this servlet by GET request ?
Writes complete URL of the servlet in the address bar of a browser ,
this generates the GET request
User will see unexpected output in the browser.
110. Document Version: 1.00
110
Solution…
For the example we are discussing , whenever user makes a GET request
to this servlet (say CreateServlet) , servlet must send back the HTML page
, which accepts data to insert in the database.
This is done by request redirecting.
111. Document Version: 1.00
111
Request Redirection
Request redirection is related to Response Status Code
response message contains response status code.
Response status code indicates how servlet /web container handled the
request.
Depending on response status code browser takes action.
112. Document Version: 1.00
112
Response Status Code
200
Request is successful . A web page is returned successfully.
404
No resource found with matching request uri.
Every browser has its own way to display error message.
302
This message indicates browser should request another URL .
This URL is supplied by servlet.
This is status code for Request Redirection.
500
Internal server error . Servlet encountered an exception.
113. Document Version: 1.00
113
Servlet and Request Redirection
HttpServletResponse interface has a method
public void sendRedirect(String location) throws IOException .
A complete URL must be passed as a parameter to it.
When called , this method generates a response status code , 302 and
sends the passed URL to browser and browser uses passed URL .
114. Document Version: 1.00
114
Example
So , in doGet() of CreateServlet , sendRedirect method must be called.
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
res.sendRedirect("http://localhost:8080/StudentWeb/createstudent.html");
}
116. Document Version: 1.00
116
Request Forwarding
A servlet/JSP can forward a request to another servlet/JSP and that can
continue…
So, more than one servlet/JSP can participate to process a single request.
Last servlet/JSP in the chain generates the response.
This is useful in Model-View-Controller situation.
117. Document Version: 1.00
117
RequestDispatcher
In order to forward request to another servlet or JSP , an object of
type RequestDispatcher must be obtained.
A RequestDispatcher object works as wrapper around a web
resource accessible by a URL.
A RequestDispatcher can be obtained by calling
“getRequestDispatcher(String uri)” of ServletRequest object
Then invoke “forward” method of the RequestDispatcher object
119. Document Version: 1.00
119
Example …
RequestDispatcher rd=request.getRequestDispatcher(“/displayservlet”);
rd.forward(req,res);
Where ‘req’and ‘res’are request and response object respectively ,
received through “service” method
120. Document Version: 1.00
120
“service” method of targeted servlet will be called as a result of invoking
“forward” method .
request and response object that were created by the web container to
handle the request will be used through out at the time of request
forwarding.
122. Document Version: 1.00
122
Example
Lets say we are developing a web application to search a student
details and student roll no is accepted through a web page
<form action="SearchServlet" method="get">
Roll No to search <input type="text" name="roll" /><br/>
<input type="submit" /><br/>
</form>
123. Document Version: 1.00
123
Example
Here the servlet , where form is submitted , will retrieve the roll no to be
searched.
Performs the JDBC operations somewhat similar way we have learned
before.
Here a select statement is executed .
124. Document Version: 1.00
124
Example
// variables required for JDBC operation
String sql="select name,marks from student where roll=?";
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null ;
// ResultSet variable is required , because we are using select stmt
125. Document Version: 1.00
125
Example
// declaring variables to store information searched from database
String name=null;
int marks=0;
//Declaring variable to generate output
response.setContentType("text/html");
PrintWriter out=response.getWriter();
127. Document Version: 1.00
127
Analysis
now think for a while ... we are searching by rollno , which is
primary key(supposed to be) .So there will be exactly one
student matching with the roll no or no student (i.e. no student
exists with matching rollno) . So maximum number of records
returned will be 1.
If no records returned, that will signify that student with
matching rollno does not exists . So , now we have to check
whether any record has returned or not.
128. Document Version: 1.00
128
Example
if (rs.next()){
/*we are not using any loop , because we know resultset can have
max one record
if next() returned true , it means rollno matched...so student exists
*/
name=rs.getString(1);
marks=rs.getInt(2);
out.println("<h3> name : "+name+"</h3>");
out.println("<h3> marks : "+marks+"</h3>");
}else{
out.println("<h3>No record found.....</h3>");
}
129. Document Version: 1.00
129
Explanation
SearchServlet is doing two task
Task1 : searching the database using JDBC
Task2 : generating response page
• If student found , then display details
• If not found , then generate error page
These two tasks are intermixed
If single servlet performs many task and if these tasks are intermixed ,
then it is difficult to maintain, upgrade.
So we have separate tasks into many servlets
130. Document Version: 1.00
130
Solution
All page generation logic are taken out from “SearchServlet” and
delegated to another servlet named say “DisplayServlet”
“DisplayServlet” will generate the response page .
“SearchServlet” will do the task of JDBC logic execution.
So different tasks which were handled previously by single servlet , are
distributed to many servlet.
132. Document Version: 1.00
132
Sending to data to next servlet
“SearchServlet ” forwards request to “DisplayServlet” using an object of
RequestDispatcher.
We have seen that no new request and response object will be created ,
same objects will be shared by all servlet in the chain.
“SearchServlet” will use request object as a medium to send data to
“DisplayServlet”.
“DisplayServlet” receives those data via request object.
133. Document Version: 1.00
133
Sending and Receiving
ServletRequest has following methods :
void setAttribute(String name, Object o)
Object getAttribute(String name)
Method “setAttribute” is used to send data from one servlet to next.
Data can not passed alone , a name must be associated with it . Name
must be of String type.
Primitive data must be converted to wrapper type.
134. Document Version: 1.00
134
Sending data ..example
Suppose following variable to be sent via request object
int marks = 250;
Integer objm=new Integer(marks);
request.setAttribute(“MARKS”,objm);
String name=“John” ;
// already reference , no need to convert to wrapper type
request.setAttribute(“NAME”,name);
It is a convention use name in capital
135. Document Version: 1.00
135
Receiving
Method “getAttribute” is used to receive data sent through “setAttribute”.
Pass the same name , that was used in “setAttribute” , as a parameter to
“getAttribute”.
Otherwise it will return null.
“getAttribute” returns “Object” type . Which must be type casted to
appropriate type.
136. Document Version: 1.00
136
Receiving data …example
Object v=request.getAttribute(“MARKS”);
// now typecast
Integer iobj=(Integer)v;
int i=iobj.intValue();
String name=(String)request.getAttribute(“NAME”);
137. Document Version: 1.00
137
Rewriting SearchServlet
As “SearchServlet” is not generating any HTML, it is not required to have
the following :
response.setContentType("text/html");
PrintWriter out=response.getWriter();
At the same time it won’t have any “out.println()” statement
138. Document Version: 1.00
138
Rewriting SearchServlet
// variables required for JDBC operation
String sql="select name,marks from student where roll=?";
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null ;
// ResultSet variable is required , because we are using select stmt
RequestDispatcher dispatcher=null;
dispatcher = request.getRequestDispatcher(“/DisplayServlet”);
A RequestDispatcher variable is required , because a
RequestDispatcher object for DisplayServlet is needed
139. Document Version: 1.00
139
Rewriting SearchServlet
// declaring variables to store information searched from database
String name=null;
int marks=0;
/* along with these two variables , another variable is required to
hold error message */
String errmsg=null;
140. Document Version: 1.00
140
Rewriting SearchServlet
if (rs.next()){
name=rs.getString(1);
marks=rs.getInt(2);
//out.println("<h3> name : "+name+"</h3>");
//out.println("<h3> marks : "+marks+"</h3>");
Integer marksobj=new Integer(marks);
request.setAttribute("NAME", name);
request.setAttribute("MARKS",marksobj);
// forwarding the request
dispatcher.forward(request, response);
}else{
see next slide
}
All out.println() are commented out. Data are stored in request object
141. Document Version: 1.00
141
Rewriting SearchServlet
else{
//out.println("<h3>No record found.....</h3>");
errmsg="<h3>No record found.....</h3>");
request.setAttribute(“ERRMSG”,errmsg);
dispatcher.forward(request,response);
}
142. Document Version: 1.00
142
Dealing exceptions
try {
// codes from previous slide comes here
} catch (ClassNotFoundException e) {
errmsg="<h3>error occured while loading driver....</h3>";
request.setAttribute(“ERRMSG”,errmsg);
dispatcher.forward(request,response);
} catch (SQLException e) {
errmsg="<h3>error occured in sql operation :
"+e.getMessage()+"</h3>");
request.setAttribute(“ERRMSG”,errmsg);
dispatcher.forward(request,response);
}
143. Document Version: 1.00
143
Coding DisplayServlet
Check whether request object contains any error msg
If error msg exists then generate HTML using error msg
Else retrieve name and marks from request object and generate HTML
using them
144. Document Version: 1.00
144
DisplayServlet
// checking whether request object contains any error message
String errmsg=(String)request.getAttribute("ERRMSG");
if (errmsg != null){
//i.e. some error...
// generate HTML containing error message
out.println(errmsg);
}else{
see next slide
}
145. Document Version: 1.00
145
DisplayServlet
else{
// retrieve data (from request) that SearchServlet sent
String name=(String)request.getAttribute("NAME");
Integer iobj=(Integer)request.getAttribute("MARKS");
int marks=iobj.intValue();
out.println("<h3> name : "+name+"</h3>");
out.println("<h3> marks : "+marks+"</h3>");
}
146. Document Version: 1.00
146
Few issues…..
Although in the last problem , we are displaying only two fields (name ,
marks) , but in real life situation , we may need to display many fields like
name , date of birth, address, phy_marks,chem_marks etc..
So in “SearchServlet” , we have to call “setAttribute” many times .
Similary in “DisplayServlet” , we have to call “getServlet” many times .
So we have to find solution where we write a single “setAttribute” method
and still send all necessary data to DisplayServlet .
147. Document Version: 1.00
147
Solution
Write a class named StudentBean , having following private fields
int roll;
String name;
int marks;
Write constructors
Write getter , setter
148. Document Version: 1.00
148
package org.bean;
public class StudentBean {
private int roll;
private String name;
private int marks;
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
getter setter
Write getter and setter for all private fields
149. Document Version: 1.00
149
package org.bean;
public class StudentBean {
private int roll;
private String name;
private int marks;
----------------------
----------------------
public StudentBean() {}
public StudentBean(int roll, String name, int marks) {
this.roll = roll;
this.name = name;
this.marks = marks;
}
}
150. Document Version: 1.00
150
SearchServlet with StudentBean
if (rs.next()){
name=rs.getString(1);
marks=rs.getInt(2);
Integer marksobj=new Integer(marks);
//request.setAttribute("NAME", name);
//request.setAttribute("MARKS",marksobj);
// create an object of StudentBean
StudentBean sb=new StudentBean(roll,name,marks);
// store StudentBean object in request
// package “org.bean.*” must be imported
request.setAttribute(“STUDENT", sb);
dispatcher.forward(request, response);
}else{
just like before
}
151. Document Version: 1.00
151
How DisplayServlet will look like
else{
//String name=(String)request.getAttribute("NAME");
//Integer iobj=(Integer)request.getAttribute("MARKS").
StudentBean s=null;
// retrieving student object passed through request
s=(StudentBean)request.getAttribute(“STUDENT");
// calling getters
String name=s.getName();
int marks=s.getMarks();
out.println("<h3> name : "+name+"</h3>");
out.println("<h3> marks : "+marks+"</h3>");
}
153. Document Version: 1.00
153
Cookie
Cookie is a name=value pair which is stored in a small text file in browser
computer.
Cookie is dispatched by a webserver to a browser and it is saved by
browser.
When a browser request back to a webserver , it sends all the cookies it
received from that webserver , along with the request.
154. Document Version: 1.00
154
Request for page
Web page + cookie (c1=“jhn234”)
Browser saves the
cookie
(c1=“jhn234”)
Request + cookie (c1=“jhn234”)
Request + cookie (c1=“jhn234”)
Web Serverbrowser
155. Document Version: 1.00
155
Types of Cookie
There are two types of cookies:
Session Cookies (aka Transient Cookies)
Persistent Cookies
Browser stores session cookies in memory
Once browser is closed , all the session cookies gets deleted.
Browser stores persistence cookies in browser computers hard drive.
156. Document Version: 1.00
156
Sending cookie to client
Create a Cookie object
Call the Cookie constructor with a cookie name and value ,
both of them are String
• Cookie c=new Cookie(“userID”,”a0234”)
set the maximum age
To tell browser to store cookie on disk instead of just in memory
• c.setMaxAge(7*24*60*60) (value in second)
Place the cookie into the HTTP response
response.addCookie(c)
157. Document Version: 1.00
157
Reading Cookies from the client
Call request.getCookies()
Cookies c[]=request.getCookies()
Navigate through returned array
158. Document Version: 1.00
158
Reading Cookies from the client
Call request.getCookies()
Cookies c[]=request.getCookies()
Navigate through returned array
159. Document Version: 1.00
159
Reading Cookies from the client
String cookieName = "userID";
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
doSomethingWith(cookie.getValue());
}
}
}
161. Document Version: 1.00
161
Session Handling
HTTP is stateless protocol
Does not understand conversesion .
Request/response protocol
Client request a page , server sends back requested page ,
then server fogets every thing about the user who requested
that page. Next request from the same client will be
completely new for the server.
HTTP does not associate a state with communications
Example of stateful protocols : telnet ,ftp
162. Document Version: 1.00
162
Session Handling
J2EE framework provides session handling
capabilities.
For each conversession , an object of type HttpSession is
created by container.
This object can be used to hold conversession specific data
or state.
Container generates unique identifier for each client.
This UID is associated with session object and this UID is
also handed over to the client(browser)
Browser is required to bring this UID , whenever it
communicates with the server(container).
This UID is known as Session ID.
163. Document Version: 1.00
163
Session Handling in J2EE
Session ID is dispatched to browser in one of the three ways
Cookies (default)
Hidden Form fields
URL rewriting
Sometimes browsers are configured not to accept any cookies , then
framework switches back to URL rewriting
164. Document Version: 1.00
164
HttpSession Interface
To get HttpSession object:
HttpSession session=request.getSession(true);
To store data into session object :
session.setAttribute(“name”,value)
void setAttribute(String name,Object val)
To retrieve data from session object:
Object obj=session.getAttribute(“name”);
To destroy a session :
session.invalidate()
166. Document Version: 1.00
166
Compare Servlet & JSP
Servlet is java program . HTML tags are embedded within it.
JSP contains HTML tags and java code is embedded within it.
HTML tags are embedded using special types of tags.
167. Document Version: 1.00
167
JSP
JavaServer Pages (JSP) technology enables you to mix
regular, static HTML with dynamically generated content
from servlets.
Aside from the regular HTML, there are three main types of
JSP constructs that you embed in a page: scripting elements,
directives, and actions.
168. Document Version: 1.00
168
A Simple JavaServer Page example
<HTML>
<BODY>
<P>Hello! <BR>
Today is: <%= new java.util.Date() %>
</BODY>
</HTML>
JavaServer Pages
currentdate.jsp – extension of a jsp file is ‘jsp’
169. Document Version: 1.00
170
How is a JSP Served?
http://localhost:8080/myapp/Hello.jsp
Java
Compiler
Servlet
Runner
JSP
Translator
JSP
Source
Hello.jsp
Generated
file
Hello.java
Servlet class
Hello
Output
of Hello
HTML
/XML
170. Document Version: 1.00
171
Scripting Elements
Expressions of the form <%= expression %>,
which are evaluated and inserted into the
servlet’s output
Scriptlets of the form <% code %>, which are
inserted into the servlet’s _jspService
method (called by service)
Declarations of the form <%! code %>, which
are inserted into the body of the servlet class,
outside of any existing methods
171. Document Version: 1.00
174
Example -- Scriptlet & Expression
<html>
<!--- JSP name: area problem --
<head>
</head>
<body>
<% int height = 4, width = 7 ; %>
The area of the rectangle is <%= height * width %>
</body>
</html>
The browser displays: 'The area of the rectangle is 28'.
Note: Java and JSP are very case sensitive
172. Document Version: 1.00
175
<html>
<!--- JSP name: Random Numbers --
<body><H1>Your Personal Random Numbers</h2>
<P>Here are your personal random numbers:
<OL>
<%
java.util.Random r = new java.util.Random( );
for (int i=0; i<5; i++) {
out.print("<LI>");
out.println(r.nextInt( ));
out.println("</LI>");
}
%>
</OL>
</body></html>
Example -- Scriptlet
173. Document Version: 1.00
176
<html>
<!--- JSP name: Random Numbers --
<body><H1>Your Personal Random Numbers</h2>
<P>Here are your personal random numbers:
<OL>
<%
java.util.Random r = new java.util.Random( );
for (int i=0; i<5; i++) {
%>
<LI><%= r.nextInt( )%></LI>
%>
}
%>
</OL>
</body></html>
Example -- Scriptlet
174. Document Version: 1.00
177
Output
The browser displays:
Your Personal Random Numbers
Here are your personal random numbers:
1.524033632
2.-1510545386
3.1167840837
4.-850658191
5.-1203635778
175. Document Version: 1.00
178
Scriptlets
Scriptlets are enclosed in <% ... %> tags
Scriptlets do not produce a value that is inserted directly into the
HTML (as is done with <%= ... %> )
Scriptlets are Java code that may write into the HTML
Example:
<% String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData); %>
Scriptlets are inserted into the servlet exactly as written, and are not
compiled until the entire servlet is compiled
Example:
<% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!
<% } else { %>
Have a <B>lousy</B> day!
<% } %>
176. Document Version: 1.00
179
Declarations
Use <%! ... %> for declarations to be added to your servlet
class, not to any particular method
Caution: Servlets are multithreaded, so nonlocal variables
must be handled with extreme care
If declared with <% ... %>, variables are local and OK
You can use <%! ... %> to declare methods as easily as to
declare variables
177. Document Version: 1.00
180
Directives
Directives affect the servlet class itself
Three main directives are
The page directive
The include directive
The taglib directive
A directive has the form:
<%@ directive attribute="value" %>
or
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
178. Document Version: 1.00
181
The page directive
The most useful directive is page, which lets you import packages
Example:
<%@ page import="java.util.*" %>
180. Document Version: 1.00
183
The page directive
Attributes of page directive
errorPage
<%@ page errorPage=“MyError.jsp" %>
isErrorPage
<%@ page isErrorPage="false" %> <%!-- Default
--%>
language
<%@ page language=“java" %> <%!– Only Supported
Language --%>
181. Document Version: 1.00
184
The include directive
The include directive inserts another file into the file
being parsed
The included file is treated as just more JSP, hence it can
include static HTML, scripting elements, actions, and
directives
Syntax: <%@ include file="URL" %>
The URL is treated as relative to the JSP page
If the URL begins with a slash, it is treated as relative to the
home directory of the Web server
If you change an included JSP file, you must update
the modification dates of all JSP files that use it.
182. Document Version: 1.00
185
Actions
Actions are XML-syntax tags used to control the servlet
engine
The jsp:include Element
<jsp:include page="URL" flush="true" />
Inserts the indicated relative URL at execution time (not at
compile time, like the include directive does)
This is great for rapidly changing data
Use the include directive if included files will use JSP
constructs. Otherwise, use jsp:include.
183. Document Version: 1.00
186
Actions
The jsp:forward Element
<jsp:forward page="URL" />
<jsp:forward page="<%= JavaExpression %>" />
Jump to the (static) URL or the (dynamically computed)
JavaExpression resulting in a URL
184. Document Version: 1.00
187
Variables
You can declare your own variables, as usual
JSP provides several predefined variables
request : The HttpServletRequest parameter
response : The HttpServletResponse parameter
session : The HttpSession associated with the request, or
null if there is none
out : A JspWriter (like a PrintWriter) used to send
output to the client
Example:
Your hostname: <%= request.getRemoteHost() %>
186. Document Version: 1.00
189
Model-view-controller (MVC)
MVC helps resolve some of the issues with the single module
approach by dividing the problem into three categories:
Model.
• The model contains the core of the application's functionality. The model
encapsulates the state of the application. Sometimes the only functionality it
contains is state. It knows nothing about the view or controller.
View.
• The view provides the presentation of the model. It is the look of the
application. The view can access the model getters, but it has no knowledge of
the setters. In addition, it knows nothing about the controller. The view should
be notified when changes to the model occur.
Controller.
• The controller reacts to the user input. It creates and sets the model.
187. Document Version: 1.00
190
Two Different Models
MVC or JSP Model 1 and Model 2 differ essentially in
the location at which the bulk of the request
processing is performed.
Model 1 Model 2
188. Document Version: 1.00
191
Model 1
In the Model 1 architecture the JSP page alone is
responsible for processing the incoming request and
replying back to the client.
189. Document Version: 1.00
192
Model 2
A hybrid approach for serving dynamic content.
It combines the use of both servlets and JSP.
190. Document Version: 1.00
193
JSP and JavaBeans
A JavaBean is a Java Class file that creates an object
Defines how to create an Object, retrieve and set properties of the Object
JSPJavaBeans
Get Bean Value
Set Bean Value
191. Document Version: 1.00
194
JSP and JavaBeans (Cont’d)
JavaBeans can store data
JavaBeans can perform complex calculations
JavaBeans can hold business logic
JavaBeans can handle Database Connectivity and
store data retrieved from them
JavaBeans facilitate
Reuse of code
Debugging process
Separating code from content
Beans are not for user interfaces