SlideShare uma empresa Scribd logo
1 de 30
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

Mais conteúdo relacionado

Mais procurados

Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Mohan Arumugam
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.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창언 정
 
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-TenantJeffrey Kemp
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
PostgREST Design Philosophy
PostgREST Design PhilosophyPostgREST Design Philosophy
PostgREST Design Philosophybegriffs
 
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 betweenColdFusionConference
 
Streamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariStreamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariJayush Luniya
 
Developing SOAP Web Services using Java
Developing SOAP Web Services using JavaDeveloping SOAP Web Services using Java
Developing SOAP Web Services using Javakrishnaviswambharan
 
Web api scalability and performance
Web api scalability and performanceWeb api scalability and performance
Web api scalability and performanceHimanshu 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-RSFahad Golra
 
Groovy Component With Mule ESB
Groovy Component With Mule ESBGroovy Component With Mule ESB
Groovy Component With Mule ESBJitendra 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 DefinitionGiuseppe De Michele
 
Compress and decompress
Compress and decompressCompress and decompress
Compress and decompressSon Nguyen
 
Microsoft Search Server 2008 - Technical Overview
Microsoft Search Server 2008 - Technical OverviewMicrosoft Search Server 2008 - Technical Overview
Microsoft Search Server 2008 - Technical Overviewukdpe
 
Mule for each scope header collection
Mule for each scope header collectionMule for each scope header collection
Mule for each scope header collectionPraneethchampion
 

Mais procurados (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
 

Semelhante a Basics Of Servlet

servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0megrhi haikel
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
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 jagtapVikas 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 KuteTushar 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 Technologyvikram singh
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2PawanMM
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
Sun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguideSun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguideAlberto Romero Jiménez
 

Semelhante a 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
 

Último

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

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