SlideShare a Scribd company logo
Servlets & JSPs
- Shubhani Jain
Agenda
Introduction
Servlet Architecture
Servlet lifecycle
Request and Response
Being a Web Container
Session management
Overview of JSP
JSP Elements
Q & A
Servlets & JSPs
 Request-response model.
request
response
HTTP
HTML
HTTP
Request
<html>
<head>
<body>
…
<html>
<head>
<body>
…
Client
Server
Introduction – request-response model
 Client : someone who request for some resource.
 Server : servers the request requested by client
 WebServer / HTTPServer : machine that takes HTTP
request from client over a web and sends the
response back in HTML page back to client over
a web through HTTP.
request-response model
HTTP Request HTTP
Response
Key elements of a “request”
stream:
 HTTP method (action to be
performed) like GET,POST, PUT.
 The page to access (a URL).
 Form parameters.
Key elements of a “response”
stream:
 A status code (for whether
the request was successful).
 Content-type (text, picture,
html, etc…).
 The content ( the actual
content).
Introduction – what is a request and response
Where does Servlet come into the picture?
Web Server
Application
Helper
Application
Web Server
machine
I can serve only
static HTML pages
Not a problem. I
can handle
dynamic
requests.
“The Helper Application is nothing but a SERVLET”
Introduction – What is a Servlet
 What is a Web Container?
GET.
…..
Web
Server
ServletWeb
Container
GET.
…..
GET.
…..
request
Client
Servlet Architecture -Web Container
 How does the Container handle a request?
Web
Container
Servlet
Thread
Service()
doGet()
<Html>
<Body>
…….
</Body>
</Html>
request
response
response
Web
Server
Http request
Client
Servlet Architecture – Web Container
 Helps web server to communicate to servlet
 Servlet does not have any main method, it is only
having call back method. So when request
comes to HTTP Server, it will first go to web
container. Web container know which call back
method can server HTTP request.
 Servlet and JSP resides inside a we container.
 Servlet is just a java program which is present on
server side.
What is the role of Web Container ?
 Communication Support- between servlet & web
server
 Lifecycle Management- servlet is just having
callback method so container is only
responsible for creation and destroy threads
 Multi-threading support- for each request it
creates new request.
 Security- as client cannot directly communicate
with servlet.
 JSP Support
The CONTAINER
S1
S3
S4
S2
JSP1
The container can contain multiple Servlets & JSPs within it
Servlet Architecture – Web Container
 How does the Container know which Servlet the client has
requested for?
A Servlet can have 3 names
 Client known URL name
- <url-pattern>
 Deployer known secret
internal name –
<servlet-name>
 Actual file name-
<servlet-class>
<web-app>
………
<servlet>
2) <servlet-name>LoginServ</servlet-name>
3) <servlet-class>com.Login</servlet-class>
</servlet>
<servlet-mapping>
2) <servlet-name>LoginServ</servlet-name>
<url-pattern>/Logon</url-pattern> 1)
</servlet-mapping>
………..
………..
</web-app>
Web.xml
Servlet Architecture – Deployment Descriptor
 The Servlet lifecycle is simple, there is only one main state –
“Initialized”.
Initialized
Does not exist
constructor()
init()
call only once in lifetime
destroy()
Service()
Servlet Lifecycle
GenericServlet
HttpServlet
Your Servlet
ServletInterface
Abstract class
Abstract class
Concrete class
If not overridden, implements init()
method from the ‘Servlet’ interface,
If not overridden, implements service()
method.
We implement the HTTP methods
here.
Servlet Lifecycle - Hierarchy
When is it called What it’s for Do you override
it
init() The container
calls the init()
before the servlet
can service any
client requests.
To initialize your
servlet before
handling any
client requests.
Possibly
service() When a new
request for that
servlet comes in.
To determine
which HTTP
method should be
called.
No. Very unlikely
doGet() or
doPost()
The service()
method invokes it
based on the HTTP
method from the
request.
To handle the
business logic.
Always
Servlet Lifecycle – 3 big moments
 The Container runs multiple threads to process multiple
requests to a single servlet.
Servlet
Thread
A
Thread
B
Container
Client A Client B
response
responserequest request
Servlet Lifecycle – Thread handling
 The HTTP request method determines whether doGet() or
doPost() runs.
GET (doGet()) POST (doPost())
HTTP Request
The request contains only the
request line and HTTP header.
Along with request line
and header it also contains
HTTP body.
Parameter
passing
The form elements are passed
to the server by appending at
the end of the URL.
The form elements are
passed in the body of the
HTTP request.
Size The parameter data is limited
(the limit depends on the
container)
Can send huge amount of
data to the server.
Idempotency GET is Idempotent- browsing
something on chrome
POST is not idempotent-
filling app form, secured
data, login
Usage Generally used to fetch some
information from the host.
Generally used to process
the sent data.
Request and Response – GET v/s POST
Request
Can the Servlet
Serve the request?
Send resource
Yes
Does the Servlet know
Who can serve?
Error page
Send Redirect
Request Dispatcher
No
Yes
No
Request and Response – The response
Key Notes
 Constructor is not having access to servlet
context and servlet config obj. That’s why in
Servlet init() method is there which is having
access to servlet context and config.
 Send Redirect- Servlet sends response back to
browser that some other servlet can serve this
request. So browser sends again the request that
servlet. Client will know about this. This is 2 step
process.
 Request Dispatcher- Servlet sends request to
other servlet instead of sending back to web
browser. Client will not know about this. This can
use only when other servlet resides over same
web application.
Servlet 2Servlet 1 Servlet 3 JSP 1
Servlet Context- only one in whole web application
Servlet Config Servlet ConfigServlet Config Servlet Config
Being a Web Container – Servlet Config and Context
 What are init parameters?
 Difference between Servlet Context and Config Init parameters
Context Init Parameters Config Init Parameters
Scope Scope is Web Container Specific to Servlet or JSP
Servlet code getServletContext() getServletConfig()
Deployment
Descriptor
Within the <web-app> element
but not within a specific
<servlet> element- for
initializing datasource by
providing datasource name &
uri
Within the <servlet> element
for each specific servlet
Being a Web Container – init parameters
 What exactly, is an attribute? – both attribute and parameter are used
to store and retrieve data
 Difference between Attributes and parameters
Attributes Parameters
Types
Context
Request
Session
Context
Request
Servlet Init
Method to set
setAttribute(String, Object)
so if object value changes we should
use attibutes
We cannot set Init
parameters. Initialize
Only once in web.xml
Return type Object String
Method to get getAttribute(String)
getInitParameter
(String)
Being a Web Container - Attributes
 How sessions work?
ID# 42
“dark”
1
4 3
2
ID# 42
“dark”“ale”
#42
1
2
request, “dark”
new
setAttribute(“dark”)response, ID# 42
request, “ale”, ID# 42
HttpSession
HttpSession
Container
Client A
Client A
Container
Session Management – Session Tracking
 Http is a stateless protocol so it does not have the
capability to store the state of the request. When request
comes it cannot understand that this request is coming
from different user
 Cookies- It is created by server which is sent back to client
and store at client machine.It contains info about client
and whenever client request to server cookie will go with
the request to server.
 URL Rewriting- Client can disable cookie. Even if server
sends a cookie it will not store inside client machine. So
appending jsessionId to url
URL+ jsessionId=12355
 Which is best cookie or url rewriting ?
 For the first time server employees both method.If client
disable cookie on next request , cookie will be sent to
server else URL rewriting is done if required
HTTP/1.1 200 OK
Set-Cookie: JSESSIONID=0ABS
Content-Type: text/html
Server: Apache-Coyote/1.1
<html>
…
</html>
POST / login.do HTTP/1.1
Cookie: JSESSIONID=0ABS
Accept: text/html……
Here’s your cookie
with session ID
inside…
OK, here’s the
cookie with
my request
HTTP Response
HTTP Request
HttpSession session = request.getSession();
Client A
Client A
Container
Container
Session Tracking – Cookies
URL ;jsessionid=1234567
HTTP/1.1 200 OK
Content-Type: text/html
Server: Apache-Coyote/1.1
<html>
<body>
< a href =“ http:// www.sharmanj.com/Metavante;jsessionid=0AAB”>
click me </a>
</html>
GET /Metavante;jsessionid=0AAB
HTTP / 1.1
Host: www.sharmanj.com
Accept: text/html
Container
Container
Client A
Client A
HTTP Response
HTTP Request
Session Tracking – URL Rewriting
public void doGet(request, response)
{
PrintWriter out = response.getWriter();
String name =
request.getParameter(name);
out.println(“<html><body>”);
out.println("Hello” + name);
out.println(“</body></html>”);
}
<html>
<body>
<% String name =
request.getParameter(name); %>
Hello <%= name %>
</body>
</html>
Servlets : HTML within Java
business logic
JSPs : Java within HTML
Presentation logic
JSP Overview - Servlets v/s JSPs
 In the end, a JSP is just a Servlet.Web container is
reposible for all these conversions
0010 0001
1100 1001
0001 0011
Import javax.
servlet.
HttpServlet.*JSP Servlet
MyJsp.jsp MyJsp_jsp.java MyJsp_jsp.class MyJsp_jsp
Servlet
writes
Is translated to Compiles to Is loaded and
Initialized as
JSP Overview - What is a JSP
 Scriptlets- whatever java code you want to write you can put in <% %>.It will treat that as
java code
 <% int I = 10; %>
 <% Dog d = new Dog(); %>
 Expressions- whatever you wrtite in <%= %>
will go in out.println() statement and prints
on UI
 <%= i %>
 <%= d.getName() %>
 Declarations- whatever you want to initialize only once you can put in <%! %>
 <%! int i=10; %>
 <%! void display() { System.out.println(“Hello”); } %
 Directives- when container converts the jsp to servlet it looks for directives which start
with <%@ %>.Then is will process jsp accordingly.
 Pages - <%@ page import=“foo.*, bar.*” %>
 include - <%@ include file=“/foo/myJsp.jsp” %>
 taglib - <%@ taglib uri=“Tags” prefix=“cool” %>
= out.println(i);
= out.println(d.getName());
JSP Elements
 Where does the JSP code land in the Servlet?
<%@ page import=“foo.*” %>
<html>
<body>
<% int i = 10; %>
<%! int count = 0; %>
Hello! Welcome
<%! Public void display()
{
out.println(“Hello”);
} %>
</body>
</html>
import javax.servlet.HttpServlet.*
import foo.*;
public class MyJsp_jsp extends
HttpServlet
{
int count = 0;
public void display()
{
out.println(“Hello”);
}
public void _jspService(req, res)
{
int i = 0;
out.println(“<html>r<body>”);
out.println(“Hello! Welcome”);
}
}
JSP Elements – JSP to Servlet
Q & A

More Related Content

What's hot

Web api
Web apiWeb api
Web api
udaiappa
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013
Mohan Arumugam
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Transfer to kubernetes data platform from EMR
Transfer to kubernetes data platform from EMRTransfer to kubernetes data platform from EMR
Transfer to kubernetes data platform from EMR
창언 정
 
Oracle OSB Tutorial 3
Oracle OSB Tutorial 3Oracle OSB Tutorial 3
Oracle OSB Tutorial 3
Rakesh Gujjarlapudi
 
One App, Many Clients: Converting an APEX Application to Multi-Tenant
One App, Many Clients: Converting an APEX Application to Multi-TenantOne App, Many Clients: Converting an APEX Application to Multi-Tenant
One App, Many Clients: Converting an APEX Application to Multi-Tenant
Jeffrey Kemp
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
PostgREST Design Philosophy
PostgREST Design PhilosophyPostgREST Design Philosophy
PostgREST Design Philosophy
begriffs
 
The app server, web server and everything in between
The app server, web server and everything in betweenThe app server, web server and everything in between
The app server, web server and everything in between
ColdFusionConference
 
Streamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariStreamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache Ambari
Jayush Luniya
 
Java servlets and CGI
Java servlets and CGIJava servlets and CGI
Java servlets and CGI
lavanya marichamy
 
Developing SOAP Web Services using Java
Developing SOAP Web Services using JavaDeveloping SOAP Web Services using Java
Developing SOAP Web Services using Java
krishnaviswambharan
 
Cold fusion is racecar fast
Cold fusion is racecar fastCold fusion is racecar fast
Cold fusion is racecar fast
ColdFusionConference
 
Web api scalability and performance
Web api scalability and performanceWeb api scalability and performance
Web api scalability and performance
Himanshu Desai
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra
 
Groovy Component With Mule ESB
Groovy Component With Mule ESBGroovy Component With Mule ESB
Groovy Component With Mule ESB
Jitendra Bafna
 
Mule ESB - Consuming RESTful WS with RAML Definition
Mule ESB - Consuming RESTful WS with RAML DefinitionMule ESB - Consuming RESTful WS with RAML Definition
Mule ESB - Consuming RESTful WS with RAML Definition
Giuseppe De Michele
 
Compress and decompress
Compress and decompressCompress and decompress
Compress and decompress
Son Nguyen
 
Microsoft Search Server 2008 - Technical Overview
Microsoft Search Server 2008 - Technical OverviewMicrosoft Search Server 2008 - Technical Overview
Microsoft Search Server 2008 - Technical Overview
ukdpe
 
Mule for each scope header collection
Mule for each scope header collectionMule for each scope header collection
Mule for each scope header collection
Praneethchampion
 

What's hot (20)

Web api
Web apiWeb api
Web api
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Transfer to kubernetes data platform from EMR
Transfer to kubernetes data platform from EMRTransfer to kubernetes data platform from EMR
Transfer to kubernetes data platform from EMR
 
Oracle OSB Tutorial 3
Oracle OSB Tutorial 3Oracle OSB Tutorial 3
Oracle OSB Tutorial 3
 
One App, Many Clients: Converting an APEX Application to Multi-Tenant
One App, Many Clients: Converting an APEX Application to Multi-TenantOne App, Many Clients: Converting an APEX Application to Multi-Tenant
One App, Many Clients: Converting an APEX Application to Multi-Tenant
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
PostgREST Design Philosophy
PostgREST Design PhilosophyPostgREST Design Philosophy
PostgREST Design Philosophy
 
The app server, web server and everything in between
The app server, web server and everything in betweenThe app server, web server and everything in between
The app server, web server and everything in between
 
Streamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariStreamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache Ambari
 
Java servlets and CGI
Java servlets and CGIJava servlets and CGI
Java servlets and CGI
 
Developing SOAP Web Services using Java
Developing SOAP Web Services using JavaDeveloping SOAP Web Services using Java
Developing SOAP Web Services using Java
 
Cold fusion is racecar fast
Cold fusion is racecar fastCold fusion is racecar fast
Cold fusion is racecar fast
 
Web api scalability and performance
Web api scalability and performanceWeb api scalability and performance
Web api scalability and performance
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
Groovy Component With Mule ESB
Groovy Component With Mule ESBGroovy Component With Mule ESB
Groovy Component With Mule ESB
 
Mule ESB - Consuming RESTful WS with RAML Definition
Mule ESB - Consuming RESTful WS with RAML DefinitionMule ESB - Consuming RESTful WS with RAML Definition
Mule ESB - Consuming RESTful WS with RAML Definition
 
Compress and decompress
Compress and decompressCompress and decompress
Compress and decompress
 
Microsoft Search Server 2008 - Technical Overview
Microsoft Search Server 2008 - Technical OverviewMicrosoft Search Server 2008 - Technical Overview
Microsoft Search Server 2008 - Technical Overview
 
Mule for each scope header collection
Mule for each scope header collectionMule for each scope header collection
Mule for each scope header collection
 

Similar to Basics Of Servlet

Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
megrhi haikel
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
SCWCD 2. servlet req - resp (cap3 - cap4)
SCWCD 2. servlet   req - resp (cap3 - cap4)SCWCD 2. servlet   req - resp (cap3 - cap4)
SCWCD 2. servlet req - resp (cap3 - cap4)
Francesco Ierna
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
WebStackAcademy
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
 
Servlet by Rj
Servlet by RjServlet by Rj
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
PawanMM
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
Ahmed Madkor
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
MouDhara1
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
kstalin2
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
KhushalChoudhary14
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
Arumugam90
 
Sun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguideSun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguide
Alberto Romero Jiménez
 

Similar to Basics Of Servlet (20)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servlet
Servlet Servlet
Servlet
 
SCWCD 2. servlet req - resp (cap3 - cap4)
SCWCD 2. servlet   req - resp (cap3 - cap4)SCWCD 2. servlet   req - resp (cap3 - cap4)
SCWCD 2. servlet req - resp (cap3 - cap4)
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Sun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguideSun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguide
 

Recently uploaded

Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
maazsz111
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 

Recently uploaded (20)

Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 

Basics Of Servlet

  • 1. Servlets & JSPs - Shubhani Jain
  • 2. Agenda Introduction Servlet Architecture Servlet lifecycle Request and Response Being a Web Container Session management Overview of JSP JSP Elements Q & A Servlets & JSPs
  • 4.  Client : someone who request for some resource.  Server : servers the request requested by client  WebServer / HTTPServer : machine that takes HTTP request from client over a web and sends the response back in HTML page back to client over a web through HTTP. request-response model
  • 5. HTTP Request HTTP Response Key elements of a “request” stream:  HTTP method (action to be performed) like GET,POST, PUT.  The page to access (a URL).  Form parameters. Key elements of a “response” stream:  A status code (for whether the request was successful).  Content-type (text, picture, html, etc…).  The content ( the actual content). Introduction – what is a request and response
  • 6. Where does Servlet come into the picture? Web Server Application Helper Application Web Server machine I can serve only static HTML pages Not a problem. I can handle dynamic requests. “The Helper Application is nothing but a SERVLET” Introduction – What is a Servlet
  • 7.  What is a Web Container? GET. ….. Web Server ServletWeb Container GET. ….. GET. ….. request Client Servlet Architecture -Web Container
  • 8.  How does the Container handle a request? Web Container Servlet Thread Service() doGet() <Html> <Body> ……. </Body> </Html> request response response Web Server Http request Client Servlet Architecture – Web Container
  • 9.  Helps web server to communicate to servlet  Servlet does not have any main method, it is only having call back method. So when request comes to HTTP Server, it will first go to web container. Web container know which call back method can server HTTP request.  Servlet and JSP resides inside a we container.  Servlet is just a java program which is present on server side.
  • 10. What is the role of Web Container ?  Communication Support- between servlet & web server  Lifecycle Management- servlet is just having callback method so container is only responsible for creation and destroy threads  Multi-threading support- for each request it creates new request.  Security- as client cannot directly communicate with servlet.  JSP Support The CONTAINER S1 S3 S4 S2 JSP1 The container can contain multiple Servlets & JSPs within it Servlet Architecture – Web Container
  • 11.  How does the Container know which Servlet the client has requested for? A Servlet can have 3 names  Client known URL name - <url-pattern>  Deployer known secret internal name – <servlet-name>  Actual file name- <servlet-class> <web-app> ……… <servlet> 2) <servlet-name>LoginServ</servlet-name> 3) <servlet-class>com.Login</servlet-class> </servlet> <servlet-mapping> 2) <servlet-name>LoginServ</servlet-name> <url-pattern>/Logon</url-pattern> 1) </servlet-mapping> ……….. ……….. </web-app> Web.xml Servlet Architecture – Deployment Descriptor
  • 12.  The Servlet lifecycle is simple, there is only one main state – “Initialized”. Initialized Does not exist constructor() init() call only once in lifetime destroy() Service() Servlet Lifecycle
  • 13. GenericServlet HttpServlet Your Servlet ServletInterface Abstract class Abstract class Concrete class If not overridden, implements init() method from the ‘Servlet’ interface, If not overridden, implements service() method. We implement the HTTP methods here. Servlet Lifecycle - Hierarchy
  • 14. When is it called What it’s for Do you override it init() The container calls the init() before the servlet can service any client requests. To initialize your servlet before handling any client requests. Possibly service() When a new request for that servlet comes in. To determine which HTTP method should be called. No. Very unlikely doGet() or doPost() The service() method invokes it based on the HTTP method from the request. To handle the business logic. Always Servlet Lifecycle – 3 big moments
  • 15.  The Container runs multiple threads to process multiple requests to a single servlet. Servlet Thread A Thread B Container Client A Client B response responserequest request Servlet Lifecycle – Thread handling
  • 16.  The HTTP request method determines whether doGet() or doPost() runs. GET (doGet()) POST (doPost()) HTTP Request The request contains only the request line and HTTP header. Along with request line and header it also contains HTTP body. Parameter passing The form elements are passed to the server by appending at the end of the URL. The form elements are passed in the body of the HTTP request. Size The parameter data is limited (the limit depends on the container) Can send huge amount of data to the server. Idempotency GET is Idempotent- browsing something on chrome POST is not idempotent- filling app form, secured data, login Usage Generally used to fetch some information from the host. Generally used to process the sent data. Request and Response – GET v/s POST
  • 17. Request Can the Servlet Serve the request? Send resource Yes Does the Servlet know Who can serve? Error page Send Redirect Request Dispatcher No Yes No Request and Response – The response
  • 18. Key Notes  Constructor is not having access to servlet context and servlet config obj. That’s why in Servlet init() method is there which is having access to servlet context and config.  Send Redirect- Servlet sends response back to browser that some other servlet can serve this request. So browser sends again the request that servlet. Client will know about this. This is 2 step process.  Request Dispatcher- Servlet sends request to other servlet instead of sending back to web browser. Client will not know about this. This can use only when other servlet resides over same web application.
  • 19. Servlet 2Servlet 1 Servlet 3 JSP 1 Servlet Context- only one in whole web application Servlet Config Servlet ConfigServlet Config Servlet Config Being a Web Container – Servlet Config and Context
  • 20.  What are init parameters?  Difference between Servlet Context and Config Init parameters Context Init Parameters Config Init Parameters Scope Scope is Web Container Specific to Servlet or JSP Servlet code getServletContext() getServletConfig() Deployment Descriptor Within the <web-app> element but not within a specific <servlet> element- for initializing datasource by providing datasource name & uri Within the <servlet> element for each specific servlet Being a Web Container – init parameters
  • 21.  What exactly, is an attribute? – both attribute and parameter are used to store and retrieve data  Difference between Attributes and parameters Attributes Parameters Types Context Request Session Context Request Servlet Init Method to set setAttribute(String, Object) so if object value changes we should use attibutes We cannot set Init parameters. Initialize Only once in web.xml Return type Object String Method to get getAttribute(String) getInitParameter (String) Being a Web Container - Attributes
  • 22.  How sessions work? ID# 42 “dark” 1 4 3 2 ID# 42 “dark”“ale” #42 1 2 request, “dark” new setAttribute(“dark”)response, ID# 42 request, “ale”, ID# 42 HttpSession HttpSession Container Client A Client A Container Session Management – Session Tracking
  • 23.  Http is a stateless protocol so it does not have the capability to store the state of the request. When request comes it cannot understand that this request is coming from different user  Cookies- It is created by server which is sent back to client and store at client machine.It contains info about client and whenever client request to server cookie will go with the request to server.  URL Rewriting- Client can disable cookie. Even if server sends a cookie it will not store inside client machine. So appending jsessionId to url URL+ jsessionId=12355  Which is best cookie or url rewriting ?  For the first time server employees both method.If client disable cookie on next request , cookie will be sent to server else URL rewriting is done if required
  • 24. HTTP/1.1 200 OK Set-Cookie: JSESSIONID=0ABS Content-Type: text/html Server: Apache-Coyote/1.1 <html> … </html> POST / login.do HTTP/1.1 Cookie: JSESSIONID=0ABS Accept: text/html…… Here’s your cookie with session ID inside… OK, here’s the cookie with my request HTTP Response HTTP Request HttpSession session = request.getSession(); Client A Client A Container Container Session Tracking – Cookies
  • 25. URL ;jsessionid=1234567 HTTP/1.1 200 OK Content-Type: text/html Server: Apache-Coyote/1.1 <html> <body> < a href =“ http:// www.sharmanj.com/Metavante;jsessionid=0AAB”> click me </a> </html> GET /Metavante;jsessionid=0AAB HTTP / 1.1 Host: www.sharmanj.com Accept: text/html Container Container Client A Client A HTTP Response HTTP Request Session Tracking – URL Rewriting
  • 26. public void doGet(request, response) { PrintWriter out = response.getWriter(); String name = request.getParameter(name); out.println(“<html><body>”); out.println("Hello” + name); out.println(“</body></html>”); } <html> <body> <% String name = request.getParameter(name); %> Hello <%= name %> </body> </html> Servlets : HTML within Java business logic JSPs : Java within HTML Presentation logic JSP Overview - Servlets v/s JSPs
  • 27.  In the end, a JSP is just a Servlet.Web container is reposible for all these conversions 0010 0001 1100 1001 0001 0011 Import javax. servlet. HttpServlet.*JSP Servlet MyJsp.jsp MyJsp_jsp.java MyJsp_jsp.class MyJsp_jsp Servlet writes Is translated to Compiles to Is loaded and Initialized as JSP Overview - What is a JSP
  • 28.  Scriptlets- whatever java code you want to write you can put in <% %>.It will treat that as java code  <% int I = 10; %>  <% Dog d = new Dog(); %>  Expressions- whatever you wrtite in <%= %> will go in out.println() statement and prints on UI  <%= i %>  <%= d.getName() %>  Declarations- whatever you want to initialize only once you can put in <%! %>  <%! int i=10; %>  <%! void display() { System.out.println(“Hello”); } %  Directives- when container converts the jsp to servlet it looks for directives which start with <%@ %>.Then is will process jsp accordingly.  Pages - <%@ page import=“foo.*, bar.*” %>  include - <%@ include file=“/foo/myJsp.jsp” %>  taglib - <%@ taglib uri=“Tags” prefix=“cool” %> = out.println(i); = out.println(d.getName()); JSP Elements
  • 29.  Where does the JSP code land in the Servlet? <%@ page import=“foo.*” %> <html> <body> <% int i = 10; %> <%! int count = 0; %> Hello! Welcome <%! Public void display() { out.println(“Hello”); } %> </body> </html> import javax.servlet.HttpServlet.* import foo.*; public class MyJsp_jsp extends HttpServlet { int count = 0; public void display() { out.println(“Hello”); } public void _jspService(req, res) { int i = 0; out.println(“<html>r<body>”); out.println(“Hello! Welcome”); } } JSP Elements – JSP to Servlet
  • 30. Q & A