SlideShare a Scribd company logo
The Servlet Technology
Inside Servlets
Writing Servlet Applications
What Is a Servlet?
“A servlet is a server-side Java replacement for CGI
scripts and programs. Servlets are much faster and
more efficient than CGI and they let you unleash
the full power of Java on your web server, including
back-end connections to databases and object
repositories through JDBC, RMI, and CORBA”
– Atlanta Java Users Group (http://www.ajug.org/meetings/jun98.html)

2
Ways to use Servlet
A simple way:
Servlet can process data which was POSTed
over HTTPS using an HTML FORM, say, an
order-entry, and applying the business logic used
to update a company's order database.
A simple servlet
Some other uses:
Since servlets handle multiple requests concurrently, the
requests can be synchronized with each other to support
collaborative applications such as on-line conferencing.
One could define a community of active agents, which
share work among each other. The code for each agent
would be loaded as a servlet, and the agents would pass
data to each other.
One servlet could forward requests other servers. This
technique can balance load among several servers which
mirror the same content.
Server-side Java for the web
a servlet is a Java program which outputs an html page; it is a
server-side technology
HTTP Request
HTTP Response
browser

Server-side Request
Response Header +
Html file
web server

Java Servlet
Java Server Page

servlet container
(engine) - Tomcat
Servlet Structure
Java Servlet Objects on Server Side
Managed by Servlet Container
Loads/unloads servlets
Directs requests to servlets
Request → doGet()

Each request is run as its own thread
A servlet Is a Server-side Java Class
Which Responds to Requests

doGet()

doPost()
service()
doPut()

doDelete()

8
Servlet Basics
Packages:
javax.servlet, javax.servlet.http
Runs in servlet container such as Tomcat
Tomcat 4.x for Servlet 2.3 API
Tomcat 5.x for Servlet 2.4 API

Servlet lifecycle
Persistent (remains in memory between requests)
Startup overhead occurrs only once
init() method runs at first request
service() method for each request
destroy() method when server shuts down
Web App with Servlets

GET …

Servlet

HEADERS
BODY

doGet()
…
…

Servlet Container
Life-cycle of a servlet
init()
service()
destroy()
It can sit there simply servicing requests with no
start up overhead, no code compilation. It is
FAST
It may be stateless – minimal memory

11
Client - Server - DB
5 Simple Steps for Java Servlets
1. Subclass off HttpServlet
2. Override doGet(....) method
3. HttpServletRequest
getParameter("paramName")

4. HttpServletResponse
set Content Type
get PrintWriter
send text to client via PrintWriter

5. Don't use instance variables
HTTP: Request &
Response
Client sends HTTP request (method) telling
server the type of action it wants performed
GET method
POST method

Server sends response

14
Http: Get & Post

GET method
For getting information from server
Can include query string, sequence with additional
information for GET, appended to URL
e.g. Http://www.whoami.Com/Servlet/search?Name=Inigo&ID=1223344

15
Http: Get & Post

POST method
designed to give information to server
all information (unlimited length) passed as part of
request body
• invisible to user
• cannot be reloaded (by design)

16
Interaction with Client
HttpServletRequest
String getParameter(String)
Enumeration getParameters(String[])

HttpServletResponse
Writer getWriter()
ServletOutputStream getOutputStream()

Handling GET and POST Requests
HttpServlet
Implements Servlet
Receives requests and sends responses to a web
browser
Methods to handle different types of HTTP requests:
handles GET requests
doPost() handles POST requests
doPut() handles PUT requests
doDelete() handles DELETE requests
doGet()

10/12/11

G53ELC: Servlets

18
HttpServlet Request Handling

19
Handling HttpServlet
Requests
service() method not usually overridden
doXXX() methods handle the different request types
Needs to be thread-safe or must run on a STM
(SingleThreadModel) Servlet Engine
multiple requests can be handled at the same time

20
Simple Counter Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet
{
int count = 0;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType(“text/plain”);
PrintWriter out = res.getWriter();
count++;
out.println(“This servlet has been accessed “ + count +
“ times since loading”);
}
}

21
Multithreading solutions
Synchronize the doGet() method
public synchronized void doGet(HttpServletRequest req,
HttpServletResponse res)

servlet can’t handle more than one GET request at a
time

Synchronize the critical section
PrintWriter out = res.getWriter();
synchronized(this)
{
count++;
out.println(“This servlet has been accessed “ + count + “ times
since loading”);
}

22
Forms and Interaction
<form method=get action=“/servlet/MyServlet”>
GET method appends parameters to action URL:
/servlet/MyServlet?userid=Jeff&pass=1234
This is called a query string (starting with ?)

Username: <input type=text name=“userid” size=20>
Password: <input type=password name=“pass”
size=20>
<input type=submit value=“Login”>
Assignment 2:
Get Stock Price
Lecture 2
RequestHeaderExample.java
import
import
import
import

java.io.*;
java.util.*;
javax.servlet.*;
javax.servlet.http.*;

public class RequestHeaderExample extends HttpServlet {
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(headerName);
out.println(name + “ = “ + value );
}
}
}
Accessing Request Components
getParameter("param1")
getCookies() => Cookie[]
getContentLength()
getContentType()
getHeaderNames()
getMethod()
Environment Variables
JavaServlets do not require you to use the
clunky environment variables used in CGI
Individual functions:
PATH_INFO
REMOTE_HOST
QUERY_STRING
…

req.getPathInfo()
req.getRemoteHost()
req.getQueryString()
Setting Response Components
Set status first!
setStatus(int)

HttpServletResponse.SC_OK...
sendError(int, String)
sendRedirect(String url)
Setting Response Components
Set headers
setHeader(…)
setContentType(“text/html”)

Output body
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD>...")
 Install Web Server on your machine such as Tomcat, Appache, ..
 Create Home Page as CV which should contains:
 Your Name as title
 You Image in the right hand side
 Your previous courses listed in Table

 Another linked Page for Accepting your friends which should
contains form to accept your friends information:








Name (Text Field)
Birth of Date (Text Field)
Country ( Drop Down List)
E-mail ( Text Field)
Mobile ( Text Field)
Gender (Radio Button with Male or Female)
Save request of friends into file

31
Ad

More Related Content

What's hot (20)

Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
vikram singh
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
Venkateswara Rao N
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
backdoor
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
Java web application development
Java web application developmentJava web application development
Java web application development
RitikRathaur
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Emprovise
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra
 
Dropwizard Internals
Dropwizard InternalsDropwizard Internals
Dropwizard Internals
carlo-rtr
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
David Gómez García
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
PRIYADARSINISK
 
Servlets
ServletsServlets
Servlets
Rajkiran Mummadi
 
Servlet
ServletServlet
Servlet
Priyanka Pradhan
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Masoud Kalali
 
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
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
 
Java Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application SecurityJava Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application Security
IMC Institute
 
01 session tracking
01   session tracking01   session tracking
01 session tracking
dhrubo kayal
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
vikram singh
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
backdoor
 
Java web application development
Java web application developmentJava web application development
Java web application development
RitikRathaur
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Emprovise
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra
 
Dropwizard Internals
Dropwizard InternalsDropwizard Internals
Dropwizard Internals
carlo-rtr
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
PRIYADARSINISK
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Masoud Kalali
 
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
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
 
Java Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application SecurityJava Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application Security
IMC Institute
 
01 session tracking
01   session tracking01   session tracking
01 session tracking
dhrubo kayal
 

Similar to Lecture 2 (20)

SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
Servlets
ServletsServlets
Servlets
Akshay Ballarpure
 
Java servlets
Java servletsJava servlets
Java servlets
yuvarani p
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
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
 
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptxUnitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
VikasTuwar1
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
Jyothishmathi Institute of Technology and Science Karimnagar
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
Lokesh Singrol
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servlets
Aamir Sohail
 
SERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptxSERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
Payal Dungarwal
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
patinijava
 
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
bharathiv53
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
IMC Institute
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
PawanMM
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
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
 
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptxUnitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
VikasTuwar1
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servlets
Aamir Sohail
 
SERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptxSERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
Payal Dungarwal
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
patinijava
 
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
bharathiv53
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
IMC Institute
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
PawanMM
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
Ad

Recently uploaded (20)

UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Ad

Lecture 2

  • 1. The Servlet Technology Inside Servlets Writing Servlet Applications
  • 2. What Is a Servlet? “A servlet is a server-side Java replacement for CGI scripts and programs. Servlets are much faster and more efficient than CGI and they let you unleash the full power of Java on your web server, including back-end connections to databases and object repositories through JDBC, RMI, and CORBA” – Atlanta Java Users Group (http://www.ajug.org/meetings/jun98.html) 2
  • 3. Ways to use Servlet A simple way: Servlet can process data which was POSTed over HTTPS using an HTML FORM, say, an order-entry, and applying the business logic used to update a company's order database.
  • 5. Some other uses: Since servlets handle multiple requests concurrently, the requests can be synchronized with each other to support collaborative applications such as on-line conferencing. One could define a community of active agents, which share work among each other. The code for each agent would be loaded as a servlet, and the agents would pass data to each other. One servlet could forward requests other servers. This technique can balance load among several servers which mirror the same content.
  • 6. Server-side Java for the web a servlet is a Java program which outputs an html page; it is a server-side technology HTTP Request HTTP Response browser Server-side Request Response Header + Html file web server Java Servlet Java Server Page servlet container (engine) - Tomcat
  • 7. Servlet Structure Java Servlet Objects on Server Side Managed by Servlet Container Loads/unloads servlets Directs requests to servlets Request → doGet() Each request is run as its own thread
  • 8. A servlet Is a Server-side Java Class Which Responds to Requests doGet() doPost() service() doPut() doDelete() 8
  • 9. Servlet Basics Packages: javax.servlet, javax.servlet.http Runs in servlet container such as Tomcat Tomcat 4.x for Servlet 2.3 API Tomcat 5.x for Servlet 2.4 API Servlet lifecycle Persistent (remains in memory between requests) Startup overhead occurrs only once init() method runs at first request service() method for each request destroy() method when server shuts down
  • 10. Web App with Servlets GET … Servlet HEADERS BODY doGet() … … Servlet Container
  • 11. Life-cycle of a servlet init() service() destroy() It can sit there simply servicing requests with no start up overhead, no code compilation. It is FAST It may be stateless – minimal memory 11
  • 13. 5 Simple Steps for Java Servlets 1. Subclass off HttpServlet 2. Override doGet(....) method 3. HttpServletRequest getParameter("paramName") 4. HttpServletResponse set Content Type get PrintWriter send text to client via PrintWriter 5. Don't use instance variables
  • 14. HTTP: Request & Response Client sends HTTP request (method) telling server the type of action it wants performed GET method POST method Server sends response 14
  • 15. Http: Get & Post GET method For getting information from server Can include query string, sequence with additional information for GET, appended to URL e.g. Http://www.whoami.Com/Servlet/search?Name=Inigo&ID=1223344 15
  • 16. Http: Get & Post POST method designed to give information to server all information (unlimited length) passed as part of request body • invisible to user • cannot be reloaded (by design) 16
  • 17. Interaction with Client HttpServletRequest String getParameter(String) Enumeration getParameters(String[]) HttpServletResponse Writer getWriter() ServletOutputStream getOutputStream() Handling GET and POST Requests
  • 18. HttpServlet Implements Servlet Receives requests and sends responses to a web browser Methods to handle different types of HTTP requests: handles GET requests doPost() handles POST requests doPut() handles PUT requests doDelete() handles DELETE requests doGet() 10/12/11 G53ELC: Servlets 18
  • 20. Handling HttpServlet Requests service() method not usually overridden doXXX() methods handle the different request types Needs to be thread-safe or must run on a STM (SingleThreadModel) Servlet Engine multiple requests can be handled at the same time 20
  • 21. Simple Counter Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(“text/plain”); PrintWriter out = res.getWriter(); count++; out.println(“This servlet has been accessed “ + count + “ times since loading”); } } 21
  • 22. Multithreading solutions Synchronize the doGet() method public synchronized void doGet(HttpServletRequest req, HttpServletResponse res) servlet can’t handle more than one GET request at a time Synchronize the critical section PrintWriter out = res.getWriter(); synchronized(this) { count++; out.println(“This servlet has been accessed “ + count + “ times since loading”); } 22
  • 23. Forms and Interaction <form method=get action=“/servlet/MyServlet”> GET method appends parameters to action URL: /servlet/MyServlet?userid=Jeff&pass=1234 This is called a query string (starting with ?) Username: <input type=text name=“userid” size=20> Password: <input type=password name=“pass” size=20> <input type=submit value=“Login”>
  • 26. RequestHeaderExample.java import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*; public class RequestHeaderExample extends HttpServlet { 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(headerName); out.println(name + “ = “ + value ); } } }
  • 27. Accessing Request Components getParameter("param1") getCookies() => Cookie[] getContentLength() getContentType() getHeaderNames() getMethod()
  • 28. Environment Variables JavaServlets do not require you to use the clunky environment variables used in CGI Individual functions: PATH_INFO REMOTE_HOST QUERY_STRING … req.getPathInfo() req.getRemoteHost() req.getQueryString()
  • 29. Setting Response Components Set status first! setStatus(int) HttpServletResponse.SC_OK... sendError(int, String) sendRedirect(String url)
  • 30. Setting Response Components Set headers setHeader(…) setContentType(“text/html”) Output body PrintWriter out = response.getWriter(); out.println("<HTML><HEAD>...")
  • 31.  Install Web Server on your machine such as Tomcat, Appache, ..  Create Home Page as CV which should contains:  Your Name as title  You Image in the right hand side  Your previous courses listed in Table  Another linked Page for Accepting your friends which should contains form to accept your friends information:        Name (Text Field) Birth of Date (Text Field) Country ( Drop Down List) E-mail ( Text Field) Mobile ( Text Field) Gender (Radio Button with Male or Female) Save request of friends into file 31