Upload
rudolph-small
View
299
Download
1
Embed Size (px)
Citation preview
Chapter 3
Servlet Basics
Servlet Basics 1. Recall the Servlet Role2. Basic Servlet Structure3. A simple servlet that generates plain text4. A servlet that generates HTML5. Servlets and packages6. Some utilities that help build HTML7. The servlet life cycle8. Servlet debugging strategies
1. Recall the Servlet Role
Read the explicit data sent by the client
Read the implicit HTTP request data sent by the browser
1. Recall the Servlet Role
Generate the results Send the explicit data (i.e., the
document) to the client Send the implicit HTTP response
data
2. Basic Servlet Structure Listing 3.1 outlines a basic servlet
that handles GET requests
2. Basic Servlet Structure GET requests are the usual type of browser
requests for Web pages A browser generates this request when the
user enters a URL on the address line, follows a link from a Web page
Or submits an HTML form that either does not specify a METHOD or specifies METHOD="GET"
Post method: Submit button
2. Basic Servlet Structure
Servlets extend HttpServlet override doGet or doPost, depending on
whether the data is being sent by GET or by POST
Servlet can take the same action for both GET and POST requests, simply have doGet call doPost.
2. Basic Servlet Structure Both doGet and doPost take two arguments :
HttpServletRequest HttpServletResponse The HttpServletRequest gets at all of the
incoming data. The HttpServletResponse specifies outgoing
information such as HTTP status codes (200, 404, etc.) and response headers (Content-Type, Set-Cookie, etc.).
HttpServletResponse obtains a PrintWriter, use to send document content back to the client.
2. Basic Servlet Structure doGet and doPost throw two exceptions:
ServletException IOException Require to include them in the method declaration.
Import classes: java.io (for PrintWriter, etc.) javax.servlet (for HttpServlet, etc.) javax.servlet.http (for HttpServletRequest and
HttpServletResponse).
3. A Servlet That Generates Plain Text
3.1. Hello World Problem3.2. Hello World Solution3.3. A Servlet That Generates Plain
Text
3.1. Hello World Problem
Write a program that shows “Hello World” as below:
3.2. Hello World Solution
3.3. A Servlet That Generates Plain Text
First, reviewing the process of installing, compiling, and running this simple servlet server is set up properly CLASSPATH refers to the necessary
three entries execute successfully
3.3. A Servlet That Generates Plain Text Second
type "javac HelloWorld.java" ->create HelloWorld.class
Third move HelloWorld.class to the directory that
server uses to store servlets that are in the default Web application
install_dir/.../WEB-INF/classes Last
Invoke servlet. Using either the default URL of
http://host/servlet/ServletName
4. A Servlet That Generates HTML
4.1. Hello Problem4.2 Hello Solution4.3. A servlet that generates HTML
4.1. Hello Problem
Write a program that shows an HTML with content “Hello” as below:
4.2. Hello Solution
4.3. A Servlet That Generates HTML
To generate HTML, add three steps to the process just shown: Tell the browser that you're sending it
HTML. Modify the println statements to build
a legal Web page. Check your HTML with a formal
syntax validator.
4.3. A Servlet That Generates HTML
response.setContentType("text/html"); Servlets to generate Excel spreadsheets
(content type application/vnd.ms-excel—see Section 7.3),
JPEG images (content type image/jpeg—see Section 7.5),
and XML documents (content type text/xml)
println statements output HTML
5. Servlet Packaging
5.1. Hello Problem with Packaging5.2. Hello Packaging Solution5.3. Servlet Packaging
5.1. Hello Problem with Packaging
Shows the servlet accessed by means of the default URL
5.2. Hello Packaging Solution
5.3. Servlet Packaging Since even a single Web application can be large,
need the standard Java solution for avoiding name conflicts: packages
Step Place the files in a subdirectory that matches the
intended package name Insert a package statement in the class file package somePackage install_dir/webapps/ROOT/WEB-INF/classes/coreservlets Listing 3.4 coreservlets/HelloServlet2.java
6. Simple HTML-Building Utilities
An HTML document is structured as follows:
Listing 3.5 coreservlets/ServletUtilities.java Listing 3.6 coreservlets/HelloServlet3.java
6. Simple HTML-Building Utilities
6. Simple HTML-Building Utilities
6. Simple HTML-Building Utilities
Result of http://localhost/servlet/coreservlets.HelloServlet3
7. The Servlet Life Cycle When the servlet is first created, its init
method is invoked, so init is where you put one-time setup code.
After this, each user request results in a thread that calls the service method of the previously created instance.
The service method then calls doGet, doPost, or another doXxx method, depending on the type of HTTP request it received.
Finally, if the server decides to unload a servlet, it first calls the servlet's destroy method.
7. The Servlet Life Cycle
The service Method Each time the server receives a
request for a servlet, the server spawns a new thread and calls service
The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc., as appropriate
7. The Servlet Life Cycle The init method definition looks like this: public void init() throws ServletException
{ // Initialization code... } The init method performs two varieties of
initializations: general initializations and initializations controlled by initialization
parameters.
General Initializations Init: creates or loads some data that will
be used throughout the life of the servlet, or it performs some one-time computation.
Listing 3.7 shows a servlet that uses init to do two things. First, it builds an array of 10 integers, complex
calculations . So, doGet looks up the values that init
computed, instead of generating them each time. The results of this technique are shown in Figure 3-6.
General Initializations Book The destroy Method :
asked by the server administrator Or the servlet is idle for a long time It closes database connections, halt background threads, write cookie lists or hit counts to disk,
and perform other such cleanup activities
8. Servlet Debugging Strategies Use print statements Use an integrated debugger in your IDE. Use the log file. Write separate classes Look at the HTML source. Look at the request data separately Look at the response data separately Stop and restart the server.
Practice Exercise Problem 1: Create a servlet page that view all the
month and day of month of 2011. Problem 2: Create a servlet page that view all of lucky
numbers from 1 to 1000.A lucky number is an integer number that have sum of
digits mod 10 equal 7For example:
7 is lucky number16 is lucky number ( 1 + 6 = 7 and 7 % 10 = 7)250 is lucky number (1 + 5 + 0 = 7 and 7 % 10 = 7)962 is lucky number ( 9 + 6 + 2 = 17 and 17 % 10 = 7)