Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo

1

www.sunilos.com
www.raystec.com
JSP/Servlet

2

Web Application
www.SunilOS.com 2
Web Server
JVM
JSP/Servlet Container
Jsp/Servlet
User
Browser
Request
Response
HTTP

3

Web Servers
Tomcat
JBoss
Jonas
Jetty
Weblogic
Web Sphere
Glass Fish
JDevelper
www.SunilOS.com 3

4

www.SunilOS.com 4
JSP/Servlet Architecture

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.

7

www.SunilOS.com 7
HTTP

8

www.SunilOS.com 8
Servlet
Specification Version 2.5
Specification Version 3.0 and above support
annotation.

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();
}
}

11

www.SunilOS.com 11
Deployment Descriptor (web.xml)
<web-app>
<servlet>
<servlet-name>HW</servlet-name>
<servlet-class>
in.co.sunrays.HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HW</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
<web-app>
URL to run servlet
http://localhost:8080/<context path>/servlet/HelloWorld

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);
}
}

21

www.SunilOS.com 21
Header Info - Output

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.

23

Initialization Parameters
 <servlet>
 <servlet-name>HelloWorld</servlet-name>
 <servlet-class>in.co.sunrays.servlet.HelloWorld</servlet-class>
 <init-param>
 <param-name>dburl</param-name>
 <param-value>jdbc:mysql://localhost:3306/test</param-value>
 </init-param>
 <init-param>
 <param-name>dbdriver</param-name>
 <param-value>com.mysql.jdbc.Driver</param-value>
 </init-param>
 <load-on-startup>0</load-on-startup>
 </servlet>
 <session-config>
 <session-timeout>30</session-timeout>
 </session-config>
www.SunilOS.com 23

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”)

25

www.SunilOS.com 25
JSP
Version 2.0

26

www.SunilOS.com 26
HelloJava.html
<HTML>
<HEAD></HEAD>
<BODY>
<center>
<b><u>Hello Java</u></b>
</center>
</BODY>
</HTML>

27

www.SunilOS.com 27
Hello.jsp - Scriptlet
 Print ‘Hello Java’ 5 times
<HTML>
<BODY>
<%
for (int i=0; i< 5; i++ ){
%>
<H1>Hello Java</H1>
<%
}
%>
</BODY>
</HTML>
Scriptlet –
<% code fragment %>
Contains :
1. Statements
2. Variables declarations
3. Expressions

28

www.SunilOS.com 28
Hello.jsp - Expression
Print ‘Hello Java’ 5 times with sequence numbers
<HTML>
<BODY>
<%
for (int i=0; i< 5; i++ ){
%>
<H1><%=i+1%> Hello Java</H1>
<%
}
%>
</BODY>
</HTML>
Expression –
<%= expression %>
Contains :
1. Expressions or RHS values

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

32

FORM Fields
 <FORM METHOD=GET ACTION=“HelloName.jsp">
 Text Field<INPUT TYPE="text" NAME="userId">
 Password Field<INPUT TYPE="password" NAME ="pwd">
 Checkbox <INPUT TYPE="checkbox" NAME=“kid" VALUE="1">
 Radio Button
 <INPUT TYPE="radio" NAME="degree" VALUE="MCA">
 <INPUT TYPE="radio" NAME="degree" VALUE="BE">
 Button <INPUT TYPE="button" NAME="action" VALUE="Go">
 Submit Button<INPUT TYPE="Submit" VALUE="Submit">
www.SunilOS.com 32

33

FORM Fields (Cont.)
 Reset Button<INPUT TYPE="reset" VALUE="Clear"><BR>
 TextArea<TEXTAREA NAME="tArea" ROWS="2"
COLS="20"></TEXTAREA><BR>
 List <SELECT NAME="list">
o <OPTION VALUE="1">ONE</OPTION>
o <OPTION VALUE="2">TWO</OPTION>
 </SELECT><BR>
 Hidden Value <INPUT TYPE="hidden" NAME="id" VALUE="123">
 </FORM>
www.SunilOS.com 33

34

FORM Fields
www.SunilOS.com 34

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.

37

www.SunilOS.com 37
Forward / Send Redirect
A.jsp
req
B.jsp
req
C.jsp
req
Req
Forward
Forward
Response
Browser
A.jsp
req
Req
sendRedirect (B)
Browser
Ask Browser to resend
request to B.jsp
B.jsp
req
New Req
Response

38

www.SunilOS.com 38
Request Object
Browser
a=One
Request
Response
A.jsp
setAttribute(“a”,”One”)
a=One
b=Two
B.jsp
fwd
setAttribute(“b”,”Two”)
a=One
b=Two
c=Three
C.jsp
fwd
setAttribute(“c”,”Three”)

39

www.SunilOS.com 39
Forward
JSP
 <jsp:forward page=“New.jsp” />
Servlet
 RequestDispatcher rd =request.getRequestDispatcher(“/New.jsp");
 rd.forward(request, response);
 rd.include(request, response);

40

www.SunilOS.com 40
Key Methods
setAttribute(key,value)
getAttribute(key)
getAttributeNames()
removeAttribute(key)
removeAll()
 Key must be a String
 Value can be any object but can not be a primitive data
type.

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”)’

42

Sample Code
public void doGet(HttpServletRequest
request, HttpServletResponse
response) throws ServletException,
IOException
{
response.sendRedirect("B.jsp");
}
www.SunilOS.com 42

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;
 %>

46

www.SunilOS.com 46
Servlet conversion
 String globalVar = null;
 public void temp() {
 String localVar = null;
 };
 public void _jspService(HttpServletRequest request, HttpServletResponse
response) throws java.io.IOException, ServletException {
 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.

51

www.SunilOS.com 51
Can we store a user’s state in an instance variable?

52

www.SunilOS.com 52
Servlet class hierarchy
Servlet
+init()
+service()
+destroy()
+getServletConfig()
GenericServlet
+init()
+service()
+destroy()
+getServletConfig()
HttpServlet
+init()
+service()
+destroy()
+getServletConfig()
+doGet()
+doPost()
+doPut()..

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

61

www.SunilOS.com 61
Session - HTTP is a stateless protocol

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

71

www.SunilOS.com 71
Key Methods
setAttribute(key,value)
getAttribute(key)
getAttributeNames()
removeAttribute(key)
removeAll()
 Key must be a String
 Value can be any object but can not be a primitive data
type.

72

www.SunilOS.com 72
Student Management
 <HTML><BODY>
 <H2>Student Management</H2>
 <FORM METHOD=“GET” ACTION=“StudentMgtCtl.jsp">
 Roll No : <INPUT TYPE="text" NAME="rollNo"><BR>
 First Name : <INPUT TYPE="text" NAME="firstName"><BR>
 Last Name: <INPUT TYPE="text" NAME="lastName"><BR>
 Session: <INPUT TYPE="text" NAME="session"><BR>
 <INPUT TYPE="submit" Value="Add" name="operation" >
 <INPUT TYPE="submit" Value="Delete" name="operation" >
 <INPUT TYPE="submit" Value="Modify" name="operation" >
 </FORM>
 </BODY></HTML>
 http://localhost:8080/demoappt/StudentMgtCtl?
rollNo=123&firstName=Sunrays&lastName=Tech&sesion=2007&o
peration=Add

73

www.SunilOS.com 73
Student Management Ctl ( StudentMgtCtl.jsp )
 <%@page import="com.dto.Student"%>
 <%
 Student std = new Student();
 std.setRollNo(request.getParameter("rollNo"));
 std.setFirstName(request.getParameter("firstName"));
 std.setLastName(request.getParameter("lastName"));
 std.setSession(request.getParameter("session"));
 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);
 }
 %>
 <jsp:forward ….>
Student
-rollNo : String
-firstName : String
-lastName String
-session : String
+setters
+getters
StudentModel
+add(Student)
+update(Student)
+delete(Student)
+get(rollNo) :Student
+search(Student):List

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

78

Error Handler (संकटमोचन) Pages
www.SunilOS.com 78

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>

82

www.SunilOS.com 82
Implicit Objects
request: ServletRequest
response: ServletResponse
out: response.getWriter()
session: HttpSession
application: ServletContext
config: ServletConfig
exception: Throwable
pageContext: PageContext

83

www.SunilOS.com 83
Filters
Browser JSP/Servlet
Filters

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.

85

www.SunilOS.com 85
Usage of Filter
 Authentication Filters
 Authorization Filters
 Logging and Auditing Filters
 Image conversion Filters
 Data compression Filters
 Encryption Filters
 Tokenizing Filters
 Filters that trigger resource access events
 XSL/T filters
 Mime-type chain Filter

86

Sample Filter Class
public class MyFilter implements Filter {
FilterConfig conf = null;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
Enumeration e = request.getParameterNames();
String key, value;
while (e.hasMoreElements()) {
key = (String) e.nextElement();
value = request.getParameter(key);
System.out.println(key + " = " + value);
}
//Pre Processing
chain.doFilter(request, response);
//Post processing
}
public void init(FilterConfig conf) throws ServletException {this.conf = conf;}
public void destroy() { conf = null; }
}
www.SunilOS.com 86

87

Apply Filter to a single Servlet
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.servlet.HelloWorld</servlet-class>
</servlet>
<filter>
<filter-name>HelloFilter</filter-name>
<filter-class>com.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HelloFilter</filter-name>
<servlet-name>HelloWorld</servlet-name>
</filter-mapping>
www.SunilOS.com 87

88

www.SunilOS.com 88
Apply Filter to URL pattern
<filter>
<filter-name>Logger</filter-name>
<filter-class>com.filter.Logger</filter-class>
</filter>
<filter-mapping>
<filter-name>Logger</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>

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

90

Marksheet Mgt. Screen Flow
www.SunilOS.com 90
Marksheet
<<jsp>>
MarksheetCtl
<<servlet>>
MarksheetModel
<<javabean>>
Marksheet
<<javabean>>
DB
Error MarksheetListCtl
<<servlet>>
MarksheetList
<<jsp>>
1
2
3.2 Create
3.1
4
5: Use
6
7: FWD 8
9

91

Login Screen Flow
www.SunilOS.com 91
Login
<<jsp>>
LoginCtl
<<Servlet>>
UserModel
<<class>>
Valid ID
RollNo.jsp
<<jsp>>
RollNoCtl.jsp
<<Servlet>>
MarksheetModel
2:Authenticate
6.1 No
6.2.1 Yes
Marksheet.jsp
<<jsp>>
8:Get
9:Fwd
7:Submit
1:Submit
User
<<class>>
Session
3:Create
4:Use
6.2:setAttribute
5:
8.1:return
Markseet

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

93

Thank You!
www.SunilOS.com 93
www.SunilOS.com

More Related Content

Jsp/Servlet

  • 2. Web Application www.SunilOS.com 2 Web Server JVM JSP/Servlet Container Jsp/Servlet User Browser Request Response HTTP
  • 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.
  • 8. www.SunilOS.com 8 Servlet Specification Version 2.5 Specification Version 3.0 and above support annotation.
  • 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(); } }
  • 11. www.SunilOS.com 11 Deployment Descriptor (web.xml) <web-app> <servlet> <servlet-name>HW</servlet-name> <servlet-class> in.co.sunrays.HelloWorld </servlet-class> </servlet> <servlet-mapping> <servlet-name>HW</servlet-name> <url-pattern>/servlet/HelloWorld</url-pattern> </servlet-mapping> <web-app> URL to run servlet http://localhost:8080/<context path>/servlet/HelloWorld
  • 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.
  • 23. Initialization Parameters  <servlet>  <servlet-name>HelloWorld</servlet-name>  <servlet-class>in.co.sunrays.servlet.HelloWorld</servlet-class>  <init-param>  <param-name>dburl</param-name>  <param-value>jdbc:mysql://localhost:3306/test</param-value>  </init-param>  <init-param>  <param-name>dbdriver</param-name>  <param-value>com.mysql.jdbc.Driver</param-value>  </init-param>  <load-on-startup>0</load-on-startup>  </servlet>  <session-config>  <session-timeout>30</session-timeout>  </session-config> www.SunilOS.com 23
  • 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”)
  • 27. www.SunilOS.com 27 Hello.jsp - Scriptlet  Print ‘Hello Java’ 5 times <HTML> <BODY> <% for (int i=0; i< 5; i++ ){ %> <H1>Hello Java</H1> <% } %> </BODY> </HTML> Scriptlet – <% code fragment %> Contains : 1. Statements 2. Variables declarations 3. Expressions
  • 28. www.SunilOS.com 28 Hello.jsp - Expression Print ‘Hello Java’ 5 times with sequence numbers <HTML> <BODY> <% for (int i=0; i< 5; i++ ){ %> <H1><%=i+1%> Hello Java</H1> <% } %> </BODY> </HTML> Expression – <%= expression %> Contains : 1. Expressions or RHS values
  • 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
  • 32. FORM Fields  <FORM METHOD=GET ACTION=“HelloName.jsp">  Text Field<INPUT TYPE="text" NAME="userId">  Password Field<INPUT TYPE="password" NAME ="pwd">  Checkbox <INPUT TYPE="checkbox" NAME=“kid" VALUE="1">  Radio Button  <INPUT TYPE="radio" NAME="degree" VALUE="MCA">  <INPUT TYPE="radio" NAME="degree" VALUE="BE">  Button <INPUT TYPE="button" NAME="action" VALUE="Go">  Submit Button<INPUT TYPE="Submit" VALUE="Submit"> www.SunilOS.com 32
  • 33. FORM Fields (Cont.)  Reset Button<INPUT TYPE="reset" VALUE="Clear"><BR>  TextArea<TEXTAREA NAME="tArea" ROWS="2" COLS="20"></TEXTAREA><BR>  List <SELECT NAME="list"> o <OPTION VALUE="1">ONE</OPTION> o <OPTION VALUE="2">TWO</OPTION>  </SELECT><BR>  Hidden Value <INPUT TYPE="hidden" NAME="id" VALUE="123">  </FORM> www.SunilOS.com 33
  • 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.
  • 37. www.SunilOS.com 37 Forward / Send Redirect A.jsp req B.jsp req C.jsp req Req Forward Forward Response Browser A.jsp req Req sendRedirect (B) Browser Ask Browser to resend request to B.jsp B.jsp req New Req Response
  • 39. www.SunilOS.com 39 Forward JSP  <jsp:forward page=“New.jsp” /> Servlet  RequestDispatcher rd =request.getRequestDispatcher(“/New.jsp");  rd.forward(request, response);  rd.include(request, response);
  • 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”)’
  • 42. Sample Code public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("B.jsp"); } www.SunilOS.com 42
  • 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;  %>
  • 46. www.SunilOS.com 46 Servlet conversion  String globalVar = null;  public void temp() {  String localVar = null;  };  public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException {  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.
  • 51. www.SunilOS.com 51 Can we store a user’s state in an instance variable?
  • 52. www.SunilOS.com 52 Servlet class hierarchy Servlet +init() +service() +destroy() +getServletConfig() GenericServlet +init() +service() +destroy() +getServletConfig() HttpServlet +init() +service() +destroy() +getServletConfig() +doGet() +doPost() +doPut()..
  • 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
  • 61. www.SunilOS.com 61 Session - HTTP is a stateless protocol
  • 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
  • 72. www.SunilOS.com 72 Student Management  <HTML><BODY>  <H2>Student Management</H2>  <FORM METHOD=“GET” ACTION=“StudentMgtCtl.jsp">  Roll No : <INPUT TYPE="text" NAME="rollNo"><BR>  First Name : <INPUT TYPE="text" NAME="firstName"><BR>  Last Name: <INPUT TYPE="text" NAME="lastName"><BR>  Session: <INPUT TYPE="text" NAME="session"><BR>  <INPUT TYPE="submit" Value="Add" name="operation" >  <INPUT TYPE="submit" Value="Delete" name="operation" >  <INPUT TYPE="submit" Value="Modify" name="operation" >  </FORM>  </BODY></HTML>  http://localhost:8080/demoappt/StudentMgtCtl? rollNo=123&firstName=Sunrays&lastName=Tech&sesion=2007&o peration=Add
  • 73. www.SunilOS.com 73 Student Management Ctl ( StudentMgtCtl.jsp )  <%@page import="com.dto.Student"%>  <%  Student std = new Student();  std.setRollNo(request.getParameter("rollNo"));  std.setFirstName(request.getParameter("firstName"));  std.setLastName(request.getParameter("lastName"));  std.setSession(request.getParameter("session"));  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);  }  %>  <jsp:forward ….> Student -rollNo : String -firstName : String -lastName String -session : String +setters +getters StudentModel +add(Student) +update(Student) +delete(Student) +get(rollNo) :Student +search(Student):List
  • 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
  • 78. Error Handler (संकटमोचन) Pages www.SunilOS.com 78
  • 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>
  • 82. www.SunilOS.com 82 Implicit Objects request: ServletRequest response: ServletResponse out: response.getWriter() session: HttpSession application: ServletContext config: ServletConfig exception: Throwable pageContext: PageContext
  • 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.
  • 85. www.SunilOS.com 85 Usage of Filter  Authentication Filters  Authorization Filters  Logging and Auditing Filters  Image conversion Filters  Data compression Filters  Encryption Filters  Tokenizing Filters  Filters that trigger resource access events  XSL/T filters  Mime-type chain Filter
  • 86. Sample Filter Class public class MyFilter implements Filter { FilterConfig conf = null; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Enumeration e = request.getParameterNames(); String key, value; while (e.hasMoreElements()) { key = (String) e.nextElement(); value = request.getParameter(key); System.out.println(key + " = " + value); } //Pre Processing chain.doFilter(request, response); //Post processing } public void init(FilterConfig conf) throws ServletException {this.conf = conf;} public void destroy() { conf = null; } } www.SunilOS.com 86
  • 87. Apply Filter to a single Servlet <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>com.servlet.HelloWorld</servlet-class> </servlet> <filter> <filter-name>HelloFilter</filter-name> <filter-class>com.filter.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>HelloFilter</filter-name> <servlet-name>HelloWorld</servlet-name> </filter-mapping> www.SunilOS.com 87
  • 88. www.SunilOS.com 88 Apply Filter to URL pattern <filter> <filter-name>Logger</filter-name> <filter-class>com.filter.Logger</filter-class> </filter> <filter-mapping> <filter-name>Logger</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>
  • 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
  • 90. Marksheet Mgt. Screen Flow www.SunilOS.com 90 Marksheet <<jsp>> MarksheetCtl <<servlet>> MarksheetModel <<javabean>> Marksheet <<javabean>> DB Error MarksheetListCtl <<servlet>> MarksheetList <<jsp>> 1 2 3.2 Create 3.1 4 5: Use 6 7: FWD 8 9
  • 91. Login Screen Flow www.SunilOS.com 91 Login <<jsp>> LoginCtl <<Servlet>> UserModel <<class>> Valid ID RollNo.jsp <<jsp>> RollNoCtl.jsp <<Servlet>> MarksheetModel 2:Authenticate 6.1 No 6.2.1 Yes Marksheet.jsp <<jsp>> 8:Get 9:Fwd 7:Submit 1:Submit User <<class>> Session 3:Create 4:Use 6.2:setAttribute 5: 8.1:return Markseet
  • 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