This document provides an overview of JSP/Servlet architecture. It describes how a web request is handled from the browser to the web server and JSP/Servlet container. It then discusses key components like servlets, JSPs, the request and response objects. It provides examples of basic servlet and JSP code to output text and access request parameters. It also covers servlet configuration, mappings, and the use of forwards and redirects.
5. www.SunilOS.com 5
Introduction
When an application is accessed by web browser is
called web application.
Browser is called Web Client that communicates with a
Web Server.
Web pages are accessed by URLs.
A web page is uniquely identified by a name is called URI
(Unified Resource Identifier).
The Web Server hosts components, that understand the
web client’s request, invoke required dynamic or static
web page and then generate the response.
The Web Server provides user sessions to save state
across several contiguous requests from the same user.
The most common communication protocol between web
client and server is HTTP.
6. www.SunilOS.com 6
JSP/Servlet Overview
JSP/Servlet is a class that generates dynamic response
on receiving the Client’s request.
It is more efficient replacement of CGI scripts for web
programming.
It is multi-threaded. It creates multiple threads instead of
multiple processes for concurrent multiple users.
JSP/Servlets are Web Server portable. Same code can be
deployed on any J2EE Web Server without making any
changes.
Sometimes Web Servers are referred as Container.
Web Server can be run in standalone mode or can be
integrated with other servers.
9. www.SunilOS.com 9
How to write a Servlet
Extends from javax.servlet.http.HttpServlet class
o Overrides doGet method to handle GET request.
o Or overrides doPost method to handle POST request.
o Above methods are called by service() lifecycle method. Do NOT
override service() method.
Both methods receive two parameters
o HttpServletRequest is the object that contains parameters sent by
Client.
o HttpServletResponse is the object that contains data sent to the
client from the server.
Servlet will be mapped with a URL in web.xml. This URL
is used by client to access servlet from browser.
10. www.SunilOS.com 10
Hello World
package in.co.sunrays.servlet;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
12. www.SunilOS.com 12
Servlet Mappings
One servlet can be mapped with multiple URLs
<servlet>
<servlet-name>ak</servlet-name>
<servlet-class>
in.co.sunrays.servlet.AkshayKumar
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ak</servlet-name>
<url-pattern>/akki</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ak</servlet-name>
<url-pattern>/sik</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ak</servlet-name>
<url-pattern>*.khiladi</url-pattern>
</servlet-mapping>
13. Servlet Mappings ( Cont.)
Call Servlet by multiple URLs
o http://localhost:8080/demo/akki
o http://localhost:8080/demo/sik
o http://localhost:8080/demo/786.khiladi
o http://localhost:8080/demo/sabsebada.khiladi
o http://localhost:8080/demo/anadi.khiladi
All URLs will call same server
AkshayKumar.
www.SunilOS.com 13
14. www.SunilOS.com 14
Servlet Mappings ( Cont.)
<servlet>
<servlet-name>kk</servlet-name>
<servlet-class>com.servlet.KatrinaKaif</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>kk</servlet-name>
<url-pattern>/kakki</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>kk</servlet-name>
<url-pattern>/sik</url-pattern>
</servlet-mapping>
….
Following URLs will call the same servlet KatrinaKaif.
• http://localhost:8080/demo/kakki
• http://localhost:8080/demo/sik
15. www.SunilOS.com 15
HttpServletRequest object
A request object consists of Header and
Data:
o Header contains metadata and client/server IP
and Port information.
o Data contains the data submitted by user from
input HTML Form.
16. www.SunilOS.com 16
Request Methods
GET ( Default) method sends Header and Data in a single
URL.
o GET is considered to be safe, As usually browsers do not inform
the user about submitting data.
o URL strings of GET requests can be book marked.
POST method sends Header as URL and Data in a
separate socket connection.
PUT
o for saving the data under the request URI.
DELETE
o for deleting the data under the request URI.
17. www.SunilOS.com 17
HttpServletRequest Params
Servlet receives user request as HttpServletRequest object.
Sent parameters are retrieved by getParameter(key) method.
• Query String : ?name=Ram&surname=Sharma
• String name = request.getParameter(“name”);
• String surname= request.getParameter(“surname”);
One parameter may have mutiple values. In this case we will use
method getParameterValues(key). It returns String[] array.
• Query String : ?address=Mumbai&address=Delhi
• String[] add= request.getParameter(“address”);
Method getParameterNames() returns a list of parameter sent by
user.
Request Header information can be retrieved by getHeader(key)
method.
Method getHeaderNames() returns the list of header names.
18. www.SunilOS.com 18
Request Info
public class RequestInfo extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h3>Request Information Example</h3>");
out.println("Method: " + request.getMethod());
out.println("Request URI: " + request.getRequestURI());
out.println("Protocol: " + request.getProtocol());
out.println("Remote Address: " + request.getRemoteAddr());
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
doGet(request, response);
}
}
19. www.SunilOS.com 19
Request Info - Output
Method: GET
Request URI: /servlet/RequestInfo
Protocol: HTTP/1.1
Remote Address: 127.0.0.1
20. www.SunilOS.com 20
Print all header information
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = request.getHeader(name);
out.println(name + " = " + value);
}
}
22. www.SunilOS.com 22
ServleConfig object
ServletConfig object is created for each Servlet.
It is used to pass initialization parameters to the
Servlet by Container from web.xml.
Servlet can access this object using:
o ServletConfig config=getServletConfig();
JSP can access this object using implicit object
config.
24. www.SunilOS.com 24
Read Parameters
Servlet
o ServletConfig config = getServletConfig();
o String value = config.getInitParameter(“dburl”)
JSP
o JSP has config implicit object
o config.getInitParameter(“dburl”)
29. Hello.jsp - Expression
Print ‘Hello Java’ 5 times with sequence numbers
<HTML>
<BODY>
<%
int i=0;
while (i< 5){
%>
<H1><%=i+1%> Hello Java</H1>
<%
i++;
}
%>
</BODY>
</HTML>
www.SunilOS.com 29
Expression –
<%= expression %>
Contains :
1. Expressions or RHS values
30. HelloName.jsp – getParameter
Read parameter from request object and display.
<HTML>
<BODY>
<%
String name = request.getParameter(“name");
String lastName = request.getParameter(“surname");
for (int i=0; i< 5; i++ ){
%>
<H1><%=i+1%> Hello <%=name%></H1>
<%
}
%>
</BODY>
</HTML>
www.SunilOS.com 30
http://localhost:8080/demoapp/HelloName.jsp?name=Ram&surname=Sharma
GET
Method
31. Submit Data From HTML Form
<HTML>
<HEAD></HEAD>
<BODY>
<FORM METHOD=“GET” ACTION="HelloName.jsp">
Enter Name
<INPUT TYPE="text" NAME=“name">
<INPUT VALUE="GO" TYPE="submit">
</FORM>
</BODY>
</HTML>
www.SunilOS.com 31
GET
POST
On Submit - http://localhost:8080/demoiapp/HelloName.jsp?name=Ram
35. Query String
http://localhost:8080/demoapp/HelloName.jsp?name=Ram
URL (Universal resource Locator )
o http://localhost:8080
URI : (Universal resource Identifier)
o demoapp/HelloName.jsp
Query String :
o ?name=Ram
o ?name=Ram&surname=Sharma&address=Mumbai
www.SunilOS.com 35
36. www.SunilOS.com 36
JSP is a Servlet
Hello.JSP Hello.Java Hello.class
JSP Servlet Class
Precompile
r
Compiler
•A JSP is converted into servlet on its first client call.
41. www.SunilOS.com 41
SendRedirect - Usage
Send redirect is used:
o When control goes from one application to another application.
o When call goes from one web server to another web server.
o When call goes to from one web JVM to another web JVM.
o When call goes from one module to another module.
o When you want to change URL in browser’s address bar.
Syntax
o response.sendRedirect(“B.jsp”)’
43. www.SunilOS.com 43
Includes – Jsp Vs Directive tag
Directive:
o <%@ include file="relativeURL" %>
o Includes code at compile time.
JSP Action Tag:
o <jsp:include page="{ relativeURL | <%= expression %> }" />
o Includes output data at runtime.
Servlet
o RequestDispatcher rd = request.getRequestDispatcher(“/New.jsp");
o rd.include(request, response);
44. www.SunilOS.com 44
Includes
int h
Header.jsp
int f
Footer.jsp
PreCom
int m
StudetMgt.jsp
int m
int h
int f
StudetMgt.java
compile
int m
int h
int f
StudetMgt.clas
s
int h
Header.jsp
int f
Footer.jsp
Compile
int m
StudetMgt.jsp
Run
output
output
output
Output
StudetMgt.clas
s
int m
int h Header.clas
s
int f Footer.class
Directive <%@ include file="relativeURL" %>
<jsp:include page="{ relativeURL | <%= expression %> }" flush="true"
/>
45. www.SunilOS.com 45
Declaration Tag
It is used to declare methods and instance variables in a
JSP.
<%! Declaration; %>
<%! String globalVar = null; %>
<%! public void temp() {
String localVar = null;
};%>
<%
String localVar = null;
%>
47. www.SunilOS.com 47
Servlet LifeCycle
Servlet Container
init()
Service()
User1
User2
User3
1:instantiate
3:remove
Service()service()
destroy()
2:run
Instantiated by
Container either
at server startup
or first Client’s
request
Removed by
Container either
at server
shutdown or free
memory is
required
48. www.SunilOS.com 48
Life of a Servlet
Birth: Creates and initializes the servlet. On birth
init() method is called.
Life: Handles 0 or more clients’ requests. During
life time for each request service() method is
called.
Death: Destroys the servlet. At the time destruction
destroy() method is called.
49. www.SunilOS.com 49
Life of a Servlet (Cont.)
When the Servlet instance is created, the container will call init()
method. Now the Servlet is ready for processing users’ requests.
Method service() is called to process a user’s request.
Based on the header information, service() will call doPost() or doGet()
method.
The Servlet remains loaded and ready after a request is processed.
Method destroy() is called before a Servlet is deleted. Time of deletion
of a servlet is not defined.
Only one instance of the servlet is instantiated in
its life.
50. www.SunilOS.com 50
Servlet One Instance
Q-Why container has only single instance of a Servlet for
multiple users.
A- For resources (memory) optimization.
Q- Can you define instance variables in a servlet?
A – Yes
Q- Can we store a user state in an instance variable?
A – Yes, but that is not advisable.
Q- Why not advisable?
A –Since all users have access on the same Servlet
instance so any user can modify instance variable thus, it is
not recommended to store a user state in the instance
variable of a Servlet.
53. www.SunilOS.com 53
Package javax.servlet
Defines the interface between Servlet Engine and Servlet.
Servlet: independent of communication protocol (e.g. HTTP, FTP)
ServletRequest: information about the request.
ServletResponse: generating and sending the response to the
browser.
ServletConfig: provides initialization parameters for a Servlet
(from web.xml).
ServletContext: describes runtime environment of the Servlet.
54. Package javax.servlet.http
HttpServlet: handles the HTTP protocol
o Provides direct access to HTTP header.
o provides named constants for HTTP.
HttpServletRequest provides access to:
o Parameters sent with the HTTP request. Parameters are accessed by
getParameter(name) method.
o Fields of the HTTP headers. Headers are accessed by getHeader() and
getHeaderNames() methods.
o Corresponding Session object . Session object is accessed by getSession()
method.
HttpServletResponse
o Servlet writes its output to response object.
HttpSession
o Represents a Session that provides a memory storage for multiple requests
from the same user.
www.SunilOS.com 54
55. SingleThread Model
A SingleThreadModel servlet handles only one request at a time. In
other words requests are processed sequentially.
It is guaranteed that NO two threads can access this servlet
concurrently.
Servlet has to implement interface SingleThreadModel. This
interface is a marker interface and contains ZERO method.
Some application servers create separate instances for multiple users
to increase the performance of application.
Syntax:
public class SingleThreadServlet
extends HttpServlet
implements SingleThreadModel{ … }
Some application servers create separate instances for multiple users
to increase the performance of application.
www.SunilOS.com 55
56. www.SunilOS.com 56
Service()DONE
Single Thread Servlet
Servlet Container
init()User1
User2
User3
1:instantiate
3:remove
Service()
destroy()
2:run
Some app
server create a
separate
instance for
each user to
boost the
performance
DONEservice()
57. www.SunilOS.com 57
Single Thread JSP
How to make a JSP Single Thread?
o <%@ page isThreadSafe=“false" %>
o Default value of isThreadSafe is true.
How to make a Servlet single threaded?
o By implementing SingleThreadModel interface
o class MyServlet extends HttpServlet
implements SingleThreadModel
Deprecated – Not recommended to use.
58. Cookies
A Cookie is a key and value pair
(key=value), set by server at
browser.
Cookies are stored in a file.
Cookies files are owned and
controlled by browsers.
Cookies are attached with
requested URLs as header.
A Cookie has maximum age and
removed by Browser after
expiration.
Desktop may have multiple
browsers.
Each browser has separate
cookie file in a separate folder.
Cookies can be enabled or
disabled by browser.
www.SunilOS.com 58
Desktop
IE
KeyN=valueN
Web Server
FireFox
KeyN=valueN
59. Set Cookies
public void doGet(..) throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// set a cookie
String name = request.getParameter("cookieName");
String value = request.getParameter("cookieValue");
Cookie c = new Cookie(name, value);
c.setMaxAge(long);
response.addCookie(c);
}
www.SunilOS.com 59
60. Get Cookies
public void doGet(..) throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// print out cookies
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
String name = c.getName();
String value = c.getValue();
out.println(name + " = " + value);
}
}
www.SunilOS.com 60
62. What is Session
HTTP is a stateless protocol.
Session tracking mechanism is used by servlets to maintain
the state of a user(browser).
A state consists of a series of requests from the same user
(browser) for a particular time.
Session will be shared by multiple servlets those are
accessed by the same user.
A good example is online Shopping Cart that contains
multiple items, selected from multiple user’s requests.
www.SunilOS.com 62
63. www.SunilOS.com 63
A Student’s Session
Student
1st
Yr Marks
2nd
Yr Marks
3rd
Yr Marks
EnrollNo = AXZ123
1st
Yr Admission
1st
Yr Marksheet
+ Enrollment #
2nd
Yr + Enrollment #
3rd
yr + Enrollment #
2nd
Yr Marksheet
marks
marks
marks
1st
Year
2nd
Year
Session
3rd
Year
College University
3nd
Yr Marksheet
Degree
Enrollment #
Degree
64. www.SunilOS.com 64
A Web User’s Session
www.yahoo.com
Id=neno
pwd=neno
SessionID = AXZ123
Login Req Req Data+Cookie
Login Res
Res Data+sessionID
Browser Cookies File
Key1=Value1,SessionID=AXZ123
Maillist req Req Data+SessionID
Mail Req
Maillist Res
Mail Res
Req Data+SessionID
Res Data+sessionID
Res Data+sessionID
setAttribute
getAttribute
getAttribute
Login
Mail List
Session
Mail
Client Web Server
session.invalid()
65. www.SunilOS.com 65
Session Example
public void doGet(..) {
...
HttpSession session = request.getSession(true);
//print session info
Date created = new Date(session.getCreationTime());
Date accessed = new Date(session.getLastAccessedTime());
out.println("ID " + session.getId());
out.println("Created: " + created);
out.println("Last Accessed: " + accessed);
66. www.SunilOS.com 66
Session Example
//set attributes in session.
String dataName = request.getParameter("dataName");
String dataValue = request.getParameter("dataValue");
session.setAttribute(dataName, dataValue);
//get attributes from session and print.
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = (String) session.getAttribute(name) ;
out.println(name + " = " + value);
}
}
67. www.SunilOS.com 67
Session Tracking
Session is tracked with help of Session ID.
There are three ways to track a session:
o Cookies: Session ID is stored as Cookie
o URL Rewriting: Session ID is appended with URL as
a parameter. For example:
• http://www.yahoo.com?jsessionid=AZX1234
o Session ID is stored in Hidden form field.
• <INPUT type=“hidden” name=“jsessionid” value=“1234” />
68. www.SunilOS.com 68
Session Tracking
<a href=“MyJsp.jsp">Simple Link</a> -------Cookie
OR
<%
String enUrl = response.encodeURL("MyJsp.jsp"); -------URL Rewriting
%>
<a href="<%=enUrl%>">Encoded Link</a>
<a href=“MyJsp.jsp?jsessionid=<%=session.getId()%>">Simple Link</a>
OR
This is my JSP page. -------Form Hidden Field
<form action="MyJsp.jsp" method="GET">
o <input type="hidden" name="jsessionid" value="<%=session.getId()%>" />
o <input type="text" name="n" />
o <input type="submit" />
</form>
69. www.SunilOS.com 69
Session Tracking
<a href="MyJsp.jsp">Link</a>
<a
href="MyJsp.jsp;jsessionid=24A1B3B97851D1E40AEF3955C33C8F79">En
coded Link</a>
<form action="MyJsp.jsp" method="GET">
<input type="hidden" name="jsessionid"
value="24A1B3B97851D1E40AEF3955C33C8F79" />
In case of URL rewriting/hidden field, all pages must be
JSP or Servlet.
70. www.SunilOS.com 70
Web Server
Bank
Rail
Reservation
Insurance
User1 User2 UserN
JSP/Serv JSP/Serv JSP/Serv
ServletContext
application =
getServletContext()
HttpSession session
=request.getSession()
page :
PageContext
•Database Name
•Admin email id
•Application Cache
•User Login Id
•User Profile
•User Cache
JSP/Serv JSP/Serv JSP/Serv
fwd fwd
request request request responserequest :
HttpServletRequest
•Error Messages
74. Student Management Ctl
<jsp:useBean id=“std" scope="page" class="com.dto.Student" />
<jsp:setProperty name=“std“ property= “*" />
<%
String op = request.getParameter("operation");
if (op.equals("Add")) { StudentModel.add(std);
}else if (op.equals("Modify")){ StudentModel.update(std);
}else if ( op.equals("Delete")) { StudentModel.delete(std);
}
%>
www.SunilOS.com 74
Student
-rollNo : String
-firstName : String
-lastName String
-session : String
+setters
+getters
Parameter
names and
bean attribute
names must be
same
75. www.SunilOS.com 75
UseBean Tag
<% Student std = new
Student();
request.setAttribute(“std”,std);
std.setFirstName(“sunray
s” ) %>
..
Name <%=
std.getFirstName()%>
<% if(std != null ) { ……
%>
<jsp:useBean id=“std"
scope=“request"
class="com.dto.Student" />
<jsp:setProperty name=“std“
property= “firstName"
value="sunrays" />
..
Name <jsp:getProperty name=“std"
property="firstName" />
<% if(std != null ) { …… %>
There can be multiple setProperty
and getProperty tags.
76. www.SunilOS.com 76
Jsp:SetProperty
Set All Attributes- Will set all attributes matching with parameter
names:
o <jsp:setProperty name=“std“ property= “*" />
When parameter and attribute names are different:
o <jsp:setProperty name=“std“ property= “firstName"
param=“name" />
o std.setFirstName(request.getParameter(“name”));
Set a literal value:
o <jsp:setProperty name=“std“ property= “firstName" value="sunrays"
/>
o std.setFirstName(“sunrays”);
Set value from a variable:
o String name = “sunrays”;
o <jsp:setProperty name=“std“ property= “firstName" value=“<
%=name%>" />
77. Error Handling
JSP pages can be categorized into regular and error
pages:
Regular pages raise exceptions. By default each page is a
regular page. False value of attribute isErrorPage says this
is a regular page.
o <%@ page isErrorPage=“false"%>
Error Handler pages handle exceptions. You can make an
error handler page by setting true value to attribute
isErrorPage.
o <%@ page isErrorPage=“true"%>
www.SunilOS.com 77
79. www.SunilOS.com 79
FormHandler.jsp
Attribute errorPage points the error handler page that will
handle the exception occurred on this page.
<%@ page errorPage="ExceptionHandler.jsp"%>
<html> <body>
<%
o int age;
o age = Integer.parseInt(request.getParameter("age"));
%>
<p>
o Your age is: <%=age%> years.
</p>
</body></html>
http://localhost:8080/demoapp/FormHandler.jsp?age=60
http://localhost:8080/demoapp/FormHandler.jsp?age=Sweet60
80. www.SunilOS.com 80
ExceptionHandler.jsp
Raised exception can be referred on this page by implicit object
exception.
<%@ page isErrorPage="true“ import="java.io.* %>
<font color="red"><%=exception.getMessage()%></font>
<%
o StringWriter sw = new StringWriter();
o PrintWriter pw = new PrintWriter(sw);
o exception.printStackTrace(pw);
o //print stack trace as HTML hidden comment
o out.print(“<!--" + sw + ("-->");
o sw.close();
o pw.close();
%>
81. www.SunilOS.com 81
Check Exception Type
<%
String message=null;
if(exception instanceof NumberFormatException){
message = "Value is not a number, Please enter a valid integer value";
} else if (exception instanceof NullPointerException){
message = "Value can not be null";
}
%>
<font color="red"> <%=message%></font>
84. www.SunilOS.com 84
Filter
A filter is an object that performs filtering operations on
either the request to a Servlet or on the response from a
Servlet or on both.
A filter class is created by implementing interface
javax.servlet.Filter.
A Filter has three lifecycle methods, init(), doFilter() and
destroy().
Method doFilter() is called on each user’s request.
A filter can be applied to a single servlet or a URL pattern.
Filters are configured in web.xml.
89. Front Controller
Most common use of Filter is Front Controller. Front controller is a
standard code practice followed by all web applications. Front
controller authorizes a user, if user is logged then only user can access
any page from application otherwise user is redirected to login page
with an error message “OOPS your session is expired”.
<filter id=“frontCtl">
o <filter-name>frontCtl</filter-name>
o <filter-class>com.filter.MainFilter</filter-class>
</filter>
<filter-mapping>
o <filter-name>frontCtl</filter-name>
o <url-pattern>*.*</url-pattern>
</filter-mapping>
www.SunilOS.com 89
92. Disclaimer
This is an educational presentation to enhance the
skill of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are
used in this presentation to simplify technical
examples and correlate examples with the real
world.
We are grateful to owners of these URLs and
pictures.
www.SunilOS.com 92