This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Lecture 15: Servelets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun
What is a Servlet?
A Servlet is a Java program that extends the capabilities of servers. Inherently multi-threaded.
Each request launches a new thread.
Input from client is automatically parsed into a Request variable. A servlet can be thought of as a server-side applet
Applet: a java program that runs within the web browser Servlet: a java program that runs within the web server Servlets are loaded and executed by a web server in the same manner that applets are loaded and executed by a web browser
CSIE33000 Network Programming
Shiow-yang Wu
Servelets 2
Note 1
CSIE33000 Net Programming
Lecture11 Java Servelet
Server-Side Application
Architecture
Applications
Dynamic generates HTML pages Access to database and/or back-end servers etc.
CSIE33000 Network Programming
Servelets 3
Server-Side Application: CGIs
Common Gateway Interface (CGI)
Basically call external program Use standard input and output for data exchange Programming language independent
Weakness
CGI program may not be easily portable to other platform Substantial overhead is incurred in starting the CGI process
CSIE33000 Network Programming
Shiow-yang Wu
Servelets 4
Note 2
CSIE33000 Net Programming
Lecture11 Java Servelet
Servlet Architecture Client (web browser)
HTTP request
Web Server
Servlet Containter
Servlet
HTTP response
The client makes a request via HTTP The web server receives the requests and forwards it to the servlet
If the servlet has not yet been loaded, the web server loads it into the JVM and executes it
The servlet receives the HTTP request and performs some type of process The servlet returns a response to the web server The web server forwards the response to the client
CSIE33000 Network Programming
Servelets 5
Why Use Servlets
Servlets are designed to replace CGI scripts
Platform-independent and extensible
Persistent and fast
CGI scripts are typically written in Perl or C, and are very much tied to a particular server platform Servlet is written in Java, which can easily integrate with existing legacy systems through RMI, CORBA, and/or JNI Servers are loaded only once by the web server and can maintain services between requests (particularly important for maintaining database connections) CGI scripts are transient – a CGI script is removed from memory after it is complete For each browser request, the web server must spawn a new operating system process
Secure
The only way to invoke a servlet from the outside world is through a web server, which can be protected behind a firewall
CSIE33000 Network Programming
Shiow-yang Wu
Servelets 6
Note 3
CSIE33000 Net Programming
Lecture11 Java Servelet
What can you build with servlets
Search engines E-commerce applications Shopping carts Product catalogs Personalization systems Intranet application Groupware applications: bulletin boards, file sharing, etc.
CSIE33000 Network Programming
Servelets 7
Steps of Servlet Processing 1.
Read any data sent by the server
2.
Look up any HTTP information
3.
Generate HTML on the fly
Set the appropriate HTTP headers
6.
Connect to databases, connect to legacy applications, etc.
Format the results
5.
Determine the browser version, host name of client, cookies, etc.
Generate the results
4.
Capture data submitted by an HTML form
Tell the browser the type of document being returned or set any cookies
Send the document back to the client
CSIE33000 Network Programming
Shiow-yang Wu
Servelets 8
Note 4
CSIE33000 Net Programming
Lecture11 Java Servelet
Servlet Life Cycle
Create (Servlet Instantiation):
Initialize (Servlet Initialization):
Handling 0 or more client requests using the service() method
Destroy (Servlet Death):
Initialize the servlet using the init() method
Service (Servlet processing):
Loading the servlet class and creating a new instance
Destroying the servlet using the destroy() method
When HTTP calls for a servlet
Not loaded: Load, Create, Init, Service Already loaded: Service
CSIE33000 Network Programming
Client Form:Client
Servelets 9
ServletEnabled:Server
Http Request
Lookup Static Page or Launch Process/Thread to Create Output Lookup
Launch Servlet
Http Response
Http Response
CSIE33000 Network Programming
Shiow-yang Wu
Launch Thread for Client
On first access launch the servlet program.
Launch separate thread to service each request.
Servelets 10
Note 5
CSIE33000 Net Programming
Lecture11 Java Servelet
Writing Servlets
Install a web server capable of launching and managing servlet programs. Install the javax.servlet package to enable programmers to write servlets. Ensure CLASSPATH is changed to correctly reference the javax.servlet package. Define a servlet by subclassing the HttpServlet class and adding any necessary code to the doGet() and/or doPost() and if necessary the init() functions.
CSIE33000 Network Programming
Servelets 11
Handler Functions
Each HTTP Request type has a separate handler function.
GET -> doGet(HttpServletRequest, HttpServletResponse) POST -> doPost(HttpServletRequest, HttpServletResponse) PUT -> doPut (HttpServletRequest, HttpServletResponse) DELETE -> doDelete (HttpServletRequest, HttpServletResponse) TRACE -> doTrace (HttpServletRequest, HttpServletResponse) OPTIONS -> doOptions (HttpServletRequest, HttpServletResponse)
CSIE33000 Network Programming
Shiow-yang Wu
Servelets 12
Note 6
CSIE33000 Net Programming
Lecture11 Java Servelet
A Servlet Template import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Use "request" to read incoming HTTP headers // (e.g. cookies) and HTML form data (e.g. data the user // entered and submitted). // Use "response" to specify the HTTP response status // code and headers (e.g. the content type, cookies). PrintWriter out = response.getWriter(); // Use "out" to send content to browser } } CSIE33000 Network Programming
Servelets 13
Important Steps Import the Servlet API: import javax.servlet.*; import javax.servlet.http.*;
Extend the HTTPServlet class Full servlet API available at: http://www.java.sun.com/products/servlet/
You need to overrride at least one of the request handlers! Get an output stream to send the response back to the client All output is channeled to the browser. CSIE33000 Network Programming
Shiow-yang Wu
Servelets 14
Note 7
CSIE33000 Net Programming
Lecture11 Java Servelet
doGet and doPost The handler methods each take two parameters: HTTPServletRequest: encapsulates all information regarding the browser request. Form data, client host name, HTTP request headers.
HTTPServletResponse: encapsulate all information regarding the servlet response. HTTP Return status, outgoing cookies, HTML response.
If you want the same servlet to handle both GET and POST, you can have doGet call doPost or vice versa. Public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {doPost(req,res);} CSIE33000 Network Programming
Servelets 15
Hello World Servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("\n" + "<TITLE>Hello WWW\n" + "\n" + "
Single Threaded Example By default, uses shared threads
Single instance of servlet shared by all requests One thread created for each request Class & instance variables are thread-unsafe; auto variables are thread-safe
In some applications, you have to use single thread model, which
Results in new servlet for each request Allows use of instance variables w/o synchronization
CSIE33000 Network Programming
Shiow-yang Wu
Servelets 18
Note 9
CSIE33000 Net Programming
Lecture11 Java Servelet
Single Threaded Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet implements javax.servlet.SingleThreadModel { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { // Code here! } } CSIE33000 Network Programming
Use getParameter() to retrieve parameters from a form by name. Named Field values HTML FORM
In a Servlet String sdiam = request.getParameter("diameter");
CSIE33000 Network Programming
Servelets 23
getParameter() cont’d
getParameter() can return three things: String: corresponds to the parameter. Empty String: parameter exists, but no value provided. null: Parameter does not exist.
CSIE33000 Network Programming
Shiow-yang Wu
Servelets 24
Note 12
CSIE33000 Net Programming
Lecture11 Java Servelet
getParameterValues()
Used to retrieve multiple form parameters with the same name. For example, a series of checkboxes all have the same name, and you want to determine which ones have been selected. Returns an array of Strings.
CSIE33000 Network Programming
Servelets 25
getParameterNames()
Returns an Enumeration object. By cycling through the enumeration object, you can obtain the names of all parameters submitted to the servlet. Note that the Servlet API does not specify the order in which parameter names appear.
CSIE33000 Network Programming
Shiow-yang Wu
Servelets 26
Note 13
CSIE33000 Net Programming
Lecture11 Java Servelet
Circle Servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class circle extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
Specify HTML
throws ServletException, IOException { output. response.setContentType("text/html"); PrintWriter out = response.getWriter();
CSIE33000 Network Programming
Attach a PrintWriter to Response Object Servelets 27