SlideShare a Scribd company logo
Jan 12, 2016
Servlets
2
Servers
 A server is a computer that responds to requests from a client
 Typical requests: provide a web page, upload or download a file, send
email
 A server is also the software that responds to these requests; a
client could be the browser or other software making these
requests
 Typically, your little computer is the client, and someone else’s
big computer is the server
 However, any computer can be a server
 It is not unusual to have server software and client software running on the
same computer
3
Apache
 Apache is a very popular server
 66% of the web sites on the Internet use Apache
 Apache is:
 Full-featured and extensible
 Efficient
 Robust
 Secure (at least, more secure than other servers)
 Up to date with current standards
 Open source
 Free
 Why use anything else?
4
Ports
 A port is a connection between a server and a client
 Ports are identified by positive integers
 A port is a software notion, not a hardware notion, so there may be very
many of them
 A service is associated with a specific port
 Typical port numbers:

21—FTP, File Transfer Protocol

22—SSH, Secure Shell

25—SMTP, Simple Mail Transfer Protocol

53—DNS, Domain Name Service

80—HTTP, Hypertext Transfer Protocol

8080—HTTP (used for testing HTTP)

7648, 7649—CU-SeeMe

27960—Quake III
These are the ports
of most interest to us
5
Ports II
 My UPenn Web page is:
http://www.cis.upenn.edu/~matuszek
 But it is also:
http://www.cis.upenn.edu:80/~matuszek
 The http: at the beginning signifies a particular protocol
(communication language), the Hypertext Transfer Protocol
 The :80 specifies a port
 By default, the Web server listens to port 80
 The Web server could listen to any port it chose
 This could lead to problems if the port was in use by some other server
 For testing servlets, we typically have the server listen to port 8080
 In the second URL above, I explicitly sent my request to port 80
 If I had sent it to some other port, say, 99, my request would either go
unheard, or would (probably) not be understood
6
CGI Scripts
 CGI stands for “Common Gateway Interface”
Client sends a request to server
Server starts a CGI script
Script computes a result for server
and quits
Another client sends a request
client server
client
script
Server starts the CGI script again
Etc.
script
Server returns response to client
7
Servlets
 A servlet is like an applet, but on the server side
Client sends a request to server
Server starts a servlet
Servlet computes a result for
server and does not quit
Another client sends a request
client server
client
servlet
Server calls the servlet again
Etc.
Server returns response to client
8
Servlets vs. CGI scripts
 Advantages:
 Running a servlet doesn’t require creating a separate process
each time
 A servlet stays in memory, so it doesn’t have to be reloaded
each time
 There is only one instance handling multiple requests, not a
separate instance for every request
 Untrusted servlets can be run in a “sandbox”
 Disadvantage:
 Less choice of languages (CGI scripts can be in any language)
9
Tomcat
 Tomcat is the Servlet Engine than handles servlet requests
for Apache
 Tomcat is a “helper application” for Apache
 It’s best to think of Tomcat as a “servlet container”
 Apache can handle many types of web services
 Apache can be installed without Tomcat
 Tomcat can be installed without Apache
 It’s easier to install Tomcat standalone than as part of
Apache
 By itself, Tomcat can handle web pages, servlets, and JSP
 Apache and Tomcat are open source (and therefore free)
10
Servlets
 A servlet is any class that implements the
javax.servlet.Servlet interface
 In practice, most servlets extend the
javax.servlet.http.HttpServlet class
 Some servlets extend javax.servlet.GenericServlet instead
 Servlets, like applets, usually lack a main method, but
must implement or override certain other methods
11
Important servlet methods, I
 When a servlet is first started up, its init(ServletConfig config)
method is called
 init should perform any necessary initializations
 init is called only once, and does not need to be thread-safe
 Every servlet request results in a call to
service(ServletRequest request, ServletResponse response)
 service calls another method depending on the type of service requested
 Usually you would override the called methods of interest, not service
itself
 service handles multiple simultaneous requests, so it and the methods it
calls must be thread safe
 When the servlet is shut down, destroy() is called
 destroy is called only once, but must be thread safe (because other threads
may still be running)
12
HTTP requests
 When a request is submitted from a Web page, it is almost always
a GET or a POST request
 The HTTP <form> tag has an attribute action, whose value can
be "get" or "post"
 The "get" action results in the form information being put after
a ? in the URL
 Example:
http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-
8&q=servlets
 The & separates the various parameters
 Only a limited amount of information can be sent this way
 "put" can send large amounts of information
13
Important servlet methods, II
 The service method dispatches the following kinds of requests:
DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE
 A GET request is dispatched to the doGet(HttpServletRequest request,
HttpServletResponse response) method
 A POST request is dispatched to the doPost(HttpServletRequest
request, HttpServletResponse response) method
 These are the two methods you will usually override
 doGet and doPost typically do the same thing, so usually you do the real
work in one, and have the other just call it
 public void doGet(HttpServletRequest request,
HttpServletResponse response) {
doPost(request, response);
}
14
A “Hello World” servlet
(from the Tomcat installation documentation)
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " +
"Transitional//EN">n";
out.println(docType +
"<HTML>n" +
"<HEAD><TITLE>Hello</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<H1>Hello World</H1>n" +
"</BODY></HTML>");
}
} Don’t worry, we’ll take this a little at a time!
15
The superclass
 public class HelloServlet extends HttpServlet {
 Every class must extend GenericServlet or a
subclass of GenericServlet
 GenericServlet is “protocol independent,” so you could
write a servlet to process any protocol
 In practice, you almost always want to respond to an
HTTP request, so you extend HttpServlet
 A subclass of HttpServlet must override at least one
method, usually one doGet, doPost, doPut,
doDelete, init and destroy, or getServletInfo
16
The doGet method
 public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
 This method services a GET request
 The method uses request to get the information that was sent to
it
 The method does not return a value; instead, it uses response to
get an I/O stream, and outputs its response
 Since the method does I/O, it can throw an IOException
 Any other type of exception should be encapsulated as a
ServletException
 The doPost method works exactly the same way
17
Parameters to doGet
 Input is from the HttpServletRequest parameter
 Our first example doesn’t get any input, so we’ll discuss this a
bit later
 Output is via the HttpServletResponse object, which we
have named response
 I/O in Java is very flexible but also quite complex, so this
object acts as an “assistant”
18
Using the HttpServletResponse
 The second parameter to doGet (or doPost) is
HttpServletResponse response
 Everything sent via the Web has a “MIME type”
 The first thing we must do with response is set the MIME type
of our reply: response.setContentType("text/html");
 This tells the client to interpret the page as HTML
 Because we will be outputting character data, we need a
PrintWriter, handily provided for us by the getWriter method
of response:
PrintWriter out = response.getWriter();
 Now we’re ready to create the actual page to be returned
19
Using the PrintWriter
 From here on, it’s just a matter of using our PrintWriter,
named out, to produce the Web page
 First we create a header string:
String docType =
"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " +
"Transitional//EN">n";
 This line is technically required by the HTML spec
 Browsers mostly don’t care, but HTML validators do care
 Then use the println method of out one or more times
out.println(docType +
"<HTML>n" +
"<HEAD> ... </BODY></HTML>");
 And we’re done!
20
Input to a servlet
 A GET request supplies parameters in the form
URL ? name=value & name=value & name=value
 (Illegal spaces added to make it more legible)
 Actual spaces in the parameter values are encoded by + signs
 Other special characters are encoded in hex; for example, an
ampersand is represented by %26
 Parameter names can occur more than once, with
different values
 A POST request supplies parameters in the same syntax,
only it is in the “body” section of the request and is
therefore harder for the user to see
21
Getting the parameters
 Input parameters are retrieved via messages to the
HttpServletRequest object request
 Most of the interesting methods are inherited from the superinterface
ServletRequest
 public Enumeration getParameterNames()
 Returns an Enumeration of the parameter names
 If no parameters, returns an empty Enumeration
 public String getParameter(String name)
 Returns the value of the parameter name as a String
 If the parameter doesn’t exist, returns null
 If name has multiple values, only the first is returned
 public String[] getParameterValues(name)
 Returns an array of values of the parameter name
 If the parameter doesn’t exist, returns null
22
Enumeration review
 An Enumeration is almost the same as Iterator
 It’s an older class, and the names are longer
 Example use:
 Enumeration e = myVector.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
23
Example of input parameters
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
... stuff omitted ...
out.println("<H1>Hello");
String names[] =
request.getParameterValues("name");
if (names != null)
for (int i = 0; i < names.length; i++)
out.println(" " + names[i]);
out.println("!");
}
24
Java review: Data from Strings
 All parameter values are retrieved as Strings
 Frequently these Strings represent numbers, and
you want the numeric value
 int n = new Integer(param).intValue();
 double d = new Double(param).doubleValue();
 byte b = new Byte(param).byteValue();

Similarly for short, float, and long

These can all throw a NumberFormatException, which is a
subclass of RuntimeException
 boolean p = new Boolean(param).booleanValue();
 But:
 char c = param.charAt(0);
25
What’s left?
 We’ve covered enough so far to write simple servlets,
but not enough to write useful servlets
 We still need to be able to:

Use configuration information

Authenticate users

Keep track of users during a session

Retain information across different sessions

Make sure our servlets are thread safe

Communicate between servlets
 But remember: The most difficult program in any language is
Hello World!
26
The End

More Related Content

What's hot

SERVIET
SERVIETSERVIET
SERVIET
sathish sak
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
Dhruvin Nakrani
 
Servlets
ServletsServlets
Servlets
Ravi Kant Sahu
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
Jim Yeh
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
Servlets
ServletsServlets
Servlets
ZainabNoorGul
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
it-people
 
Servlets
ServletsServlets
Servlets
Geethu Mohan
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
Rajiv Gupta
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
Jeetendra singh
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
Manjunatha RK
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
kamal kotecha
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 
Servlets
ServletsServlets

What's hot (20)

SERVIET
SERVIETSERVIET
SERVIET
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servlet
Servlet Servlet
Servlet
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Servlets
ServletsServlets
Servlets
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
Servlets
ServletsServlets
Servlets
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Servlets
ServletsServlets
Servlets
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Servlets
ServletsServlets
Servlets
 

Similar to Servlets

Lecture 2
Lecture 2Lecture 2
Lecture 2
Ahmed Madkor
 
Servlet basics
Servlet basicsServlet basics
Servlet basics
Santosh Dhoundiyal
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servlets
Aamir Sohail
 
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010 Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
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
 
Servlet by Rj
Servlet by RjServlet by Rj
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
King Foo
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
MouDhara1
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
kstalin2
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
KhushalChoudhary14
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
Lecture5
Lecture5Lecture5
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
backdoor
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
Shubhani Jain
 
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
 
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
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
PawanMM
 

Similar to Servlets (20)

Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Servlet basics
Servlet basicsServlet basics
Servlet basics
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servlets
 
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010 Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
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...
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Lecture5
Lecture5Lecture5
Lecture5
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
 
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
 
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
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
 

More from Manav Prasad

Experience with mulesoft
Experience with mulesoftExperience with mulesoft
Experience with mulesoft
Manav Prasad
 
Mulesoftconnectors
MulesoftconnectorsMulesoftconnectors
Mulesoftconnectors
Manav Prasad
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
Manav Prasad
 
Mulesoft cloudhub
Mulesoft cloudhubMulesoft cloudhub
Mulesoft cloudhub
Manav Prasad
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
Manav Prasad
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
Manav Prasad
 
Jpa
JpaJpa
Spring introduction
Spring introductionSpring introduction
Spring introduction
Manav Prasad
 
Json
Json Json
The spring framework
The spring frameworkThe spring framework
The spring framework
Manav Prasad
 
Rest introduction
Rest introductionRest introduction
Rest introduction
Manav Prasad
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
Manav Prasad
 
Junit
JunitJunit
Xml parsers
Xml parsersXml parsers
Xml parsers
Manav Prasad
 
Xpath
XpathXpath
Xslt
XsltXslt
Xhtml
XhtmlXhtml
Css
CssCss
Introduction to html5
Introduction to html5Introduction to html5
Introduction to html5
Manav Prasad
 
Ajax
AjaxAjax

More from Manav Prasad (20)

Experience with mulesoft
Experience with mulesoftExperience with mulesoft
Experience with mulesoft
 
Mulesoftconnectors
MulesoftconnectorsMulesoftconnectors
Mulesoftconnectors
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
 
Mulesoft cloudhub
Mulesoft cloudhubMulesoft cloudhub
Mulesoft cloudhub
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Jpa
JpaJpa
Jpa
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Json
Json Json
Json
 
The spring framework
The spring frameworkThe spring framework
The spring framework
 
Rest introduction
Rest introductionRest introduction
Rest introduction
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Junit
JunitJunit
Junit
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Xpath
XpathXpath
Xpath
 
Xslt
XsltXslt
Xslt
 
Xhtml
XhtmlXhtml
Xhtml
 
Css
CssCss
Css
 
Introduction to html5
Introduction to html5Introduction to html5
Introduction to html5
 
Ajax
AjaxAjax
Ajax
 

Recently uploaded

Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Mydbops
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
Bert Blevins
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 
Best Programming Language for Civil Engineers
Best Programming Language for Civil EngineersBest Programming Language for Civil Engineers
Best Programming Language for Civil Engineers
Awais Yaseen
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
jackson110191
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
KAMAL CHOUDHARY
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Chris Swan
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Bert Blevins
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
Mark Billinghurst
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Erasmo Purificato
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
BookNet Canada
 

Recently uploaded (20)

Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 
Best Programming Language for Civil Engineers
Best Programming Language for Civil EngineersBest Programming Language for Civil Engineers
Best Programming Language for Civil Engineers
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
 

Servlets

  • 2. 2 Servers  A server is a computer that responds to requests from a client  Typical requests: provide a web page, upload or download a file, send email  A server is also the software that responds to these requests; a client could be the browser or other software making these requests  Typically, your little computer is the client, and someone else’s big computer is the server  However, any computer can be a server  It is not unusual to have server software and client software running on the same computer
  • 3. 3 Apache  Apache is a very popular server  66% of the web sites on the Internet use Apache  Apache is:  Full-featured and extensible  Efficient  Robust  Secure (at least, more secure than other servers)  Up to date with current standards  Open source  Free  Why use anything else?
  • 4. 4 Ports  A port is a connection between a server and a client  Ports are identified by positive integers  A port is a software notion, not a hardware notion, so there may be very many of them  A service is associated with a specific port  Typical port numbers:  21—FTP, File Transfer Protocol  22—SSH, Secure Shell  25—SMTP, Simple Mail Transfer Protocol  53—DNS, Domain Name Service  80—HTTP, Hypertext Transfer Protocol  8080—HTTP (used for testing HTTP)  7648, 7649—CU-SeeMe  27960—Quake III These are the ports of most interest to us
  • 5. 5 Ports II  My UPenn Web page is: http://www.cis.upenn.edu/~matuszek  But it is also: http://www.cis.upenn.edu:80/~matuszek  The http: at the beginning signifies a particular protocol (communication language), the Hypertext Transfer Protocol  The :80 specifies a port  By default, the Web server listens to port 80  The Web server could listen to any port it chose  This could lead to problems if the port was in use by some other server  For testing servlets, we typically have the server listen to port 8080  In the second URL above, I explicitly sent my request to port 80  If I had sent it to some other port, say, 99, my request would either go unheard, or would (probably) not be understood
  • 6. 6 CGI Scripts  CGI stands for “Common Gateway Interface” Client sends a request to server Server starts a CGI script Script computes a result for server and quits Another client sends a request client server client script Server starts the CGI script again Etc. script Server returns response to client
  • 7. 7 Servlets  A servlet is like an applet, but on the server side Client sends a request to server Server starts a servlet Servlet computes a result for server and does not quit Another client sends a request client server client servlet Server calls the servlet again Etc. Server returns response to client
  • 8. 8 Servlets vs. CGI scripts  Advantages:  Running a servlet doesn’t require creating a separate process each time  A servlet stays in memory, so it doesn’t have to be reloaded each time  There is only one instance handling multiple requests, not a separate instance for every request  Untrusted servlets can be run in a “sandbox”  Disadvantage:  Less choice of languages (CGI scripts can be in any language)
  • 9. 9 Tomcat  Tomcat is the Servlet Engine than handles servlet requests for Apache  Tomcat is a “helper application” for Apache  It’s best to think of Tomcat as a “servlet container”  Apache can handle many types of web services  Apache can be installed without Tomcat  Tomcat can be installed without Apache  It’s easier to install Tomcat standalone than as part of Apache  By itself, Tomcat can handle web pages, servlets, and JSP  Apache and Tomcat are open source (and therefore free)
  • 10. 10 Servlets  A servlet is any class that implements the javax.servlet.Servlet interface  In practice, most servlets extend the javax.servlet.http.HttpServlet class  Some servlets extend javax.servlet.GenericServlet instead  Servlets, like applets, usually lack a main method, but must implement or override certain other methods
  • 11. 11 Important servlet methods, I  When a servlet is first started up, its init(ServletConfig config) method is called  init should perform any necessary initializations  init is called only once, and does not need to be thread-safe  Every servlet request results in a call to service(ServletRequest request, ServletResponse response)  service calls another method depending on the type of service requested  Usually you would override the called methods of interest, not service itself  service handles multiple simultaneous requests, so it and the methods it calls must be thread safe  When the servlet is shut down, destroy() is called  destroy is called only once, but must be thread safe (because other threads may still be running)
  • 12. 12 HTTP requests  When a request is submitted from a Web page, it is almost always a GET or a POST request  The HTTP <form> tag has an attribute action, whose value can be "get" or "post"  The "get" action results in the form information being put after a ? in the URL  Example: http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF- 8&q=servlets  The & separates the various parameters  Only a limited amount of information can be sent this way  "put" can send large amounts of information
  • 13. 13 Important servlet methods, II  The service method dispatches the following kinds of requests: DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE  A GET request is dispatched to the doGet(HttpServletRequest request, HttpServletResponse response) method  A POST request is dispatched to the doPost(HttpServletRequest request, HttpServletResponse response) method  These are the two methods you will usually override  doGet and doPost typically do the same thing, so usually you do the real work in one, and have the other just call it  public void doGet(HttpServletRequest request, HttpServletResponse response) { doPost(request, response); }
  • 14. 14 A “Hello World” servlet (from the Tomcat installation documentation) public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " + "Transitional//EN">n"; out.println(docType + "<HTML>n" + "<HEAD><TITLE>Hello</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF5E6">n" + "<H1>Hello World</H1>n" + "</BODY></HTML>"); } } Don’t worry, we’ll take this a little at a time!
  • 15. 15 The superclass  public class HelloServlet extends HttpServlet {  Every class must extend GenericServlet or a subclass of GenericServlet  GenericServlet is “protocol independent,” so you could write a servlet to process any protocol  In practice, you almost always want to respond to an HTTP request, so you extend HttpServlet  A subclass of HttpServlet must override at least one method, usually one doGet, doPost, doPut, doDelete, init and destroy, or getServletInfo
  • 16. 16 The doGet method  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  This method services a GET request  The method uses request to get the information that was sent to it  The method does not return a value; instead, it uses response to get an I/O stream, and outputs its response  Since the method does I/O, it can throw an IOException  Any other type of exception should be encapsulated as a ServletException  The doPost method works exactly the same way
  • 17. 17 Parameters to doGet  Input is from the HttpServletRequest parameter  Our first example doesn’t get any input, so we’ll discuss this a bit later  Output is via the HttpServletResponse object, which we have named response  I/O in Java is very flexible but also quite complex, so this object acts as an “assistant”
  • 18. 18 Using the HttpServletResponse  The second parameter to doGet (or doPost) is HttpServletResponse response  Everything sent via the Web has a “MIME type”  The first thing we must do with response is set the MIME type of our reply: response.setContentType("text/html");  This tells the client to interpret the page as HTML  Because we will be outputting character data, we need a PrintWriter, handily provided for us by the getWriter method of response: PrintWriter out = response.getWriter();  Now we’re ready to create the actual page to be returned
  • 19. 19 Using the PrintWriter  From here on, it’s just a matter of using our PrintWriter, named out, to produce the Web page  First we create a header string: String docType = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " + "Transitional//EN">n";  This line is technically required by the HTML spec  Browsers mostly don’t care, but HTML validators do care  Then use the println method of out one or more times out.println(docType + "<HTML>n" + "<HEAD> ... </BODY></HTML>");  And we’re done!
  • 20. 20 Input to a servlet  A GET request supplies parameters in the form URL ? name=value & name=value & name=value  (Illegal spaces added to make it more legible)  Actual spaces in the parameter values are encoded by + signs  Other special characters are encoded in hex; for example, an ampersand is represented by %26  Parameter names can occur more than once, with different values  A POST request supplies parameters in the same syntax, only it is in the “body” section of the request and is therefore harder for the user to see
  • 21. 21 Getting the parameters  Input parameters are retrieved via messages to the HttpServletRequest object request  Most of the interesting methods are inherited from the superinterface ServletRequest  public Enumeration getParameterNames()  Returns an Enumeration of the parameter names  If no parameters, returns an empty Enumeration  public String getParameter(String name)  Returns the value of the parameter name as a String  If the parameter doesn’t exist, returns null  If name has multiple values, only the first is returned  public String[] getParameterValues(name)  Returns an array of values of the parameter name  If the parameter doesn’t exist, returns null
  • 22. 22 Enumeration review  An Enumeration is almost the same as Iterator  It’s an older class, and the names are longer  Example use:  Enumeration e = myVector.elements(); while (e.hasMoreElements()) { System.out.println(e.nextElement()); }
  • 23. 23 Example of input parameters public void doGet(HttpServletRequest request, HttpServletResponse response) { ... stuff omitted ... out.println("<H1>Hello"); String names[] = request.getParameterValues("name"); if (names != null) for (int i = 0; i < names.length; i++) out.println(" " + names[i]); out.println("!"); }
  • 24. 24 Java review: Data from Strings  All parameter values are retrieved as Strings  Frequently these Strings represent numbers, and you want the numeric value  int n = new Integer(param).intValue();  double d = new Double(param).doubleValue();  byte b = new Byte(param).byteValue();  Similarly for short, float, and long  These can all throw a NumberFormatException, which is a subclass of RuntimeException  boolean p = new Boolean(param).booleanValue();  But:  char c = param.charAt(0);
  • 25. 25 What’s left?  We’ve covered enough so far to write simple servlets, but not enough to write useful servlets  We still need to be able to:  Use configuration information  Authenticate users  Keep track of users during a session  Retain information across different sessions  Make sure our servlets are thread safe  Communicate between servlets  But remember: The most difficult program in any language is Hello World!