Download lec_6_SSD1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming with Java
Lecture 6
Elements of a Java Servlet
Planning Servlet Development
Guidelines for Java Development
Introduction to Information Systems
The
Welcome
Servlet
•
•
•
•
•
•
•
•
/**
* Author: ssd1-dev-srt
* Date: May'03
* Description: Servlet that displays a welcome message.
*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
•
•
•
•
public class Welcome extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
•
•
•
•
•
/**
* Indicate the content type (for example, text/html),
* being returned by the response
*/
response.setContentType("text/plain");
•
•
•
•
/**
* Retrieve an output stream to use to send data to the client
*/
PrintWriter out = response.getWriter();
•
•
•
•
•
•
/**
* Write the response
*/
out.println("Welcome to iCarnegie!");
}
}
2
Introduction to Information Systems
The Welcome Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
• First few statements with import keyword known as
import directives
• These lines make pre-defined code from the packages
java.io and javax.servlet available to the servlet.
• import java.io.* imports all the classes contained in
the package java.io, which are required by the servlet
for any I/O tasks
• import javax.servlet.* and import javax.servlet.http.*
imports all the classes contained in the package
java.servlet and import javax.servlet.http respectively
3
Introduction to Information Systems
public class Welcome extends HttpServlet {
public void doPost (HttpServletRequest
request,
Identifiers and
HttpServletResponse response)
Keywords
throws ServletException, IOException {
• public class Welcome extends HttpServlet starts a class definition,
included within “{“ and “}”, referring to servlet named Welcome
• Servlet receives a doPost message when the form is submitted, if
form method attribute set to post
• Hence doPost message described by expressing information about
the kinds of objects that can send this message to the servlet
• resources needed by the message to execute, and the types of errors
that may occur during its execution included in method definition
4
Introduction to Information Systems
public class Welcome extends HttpServlet {
public void doPost (HttpServletRequest request,
Request and
HttpServletResponse response)
response Objects
• resources needed by the doPost message are specified by
the code: HttpServletRequest request,
HttpServletResponse response
• Request and Response are objects of above classes
imported earlier
• When the doPost message received by the servlet, the
request object enables the servlet to access all information
related to the browser request that invoked the servlet,
including HTML form input
• response object enables the servlet to send its response
5
back to the browser
Introduction to Information Systems
Steps to process doPost - I
1.
2.
3.
4.
5.
6.
7.
8.
/**
* Author: ssd1-dev-srt
* Date: May'03
* Description: Servlet that displays a welcome message.
*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
9.
10.
11.
12.
public class Welcome extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
• inform the browser that it
should expect plain text from
the server
• servlet sends the
setContentType message to
the response object
• setContentType message
needs one resource to
execute, and this resource is
specified by the code
"text/plain" indicating that
the servlet will generate plain
text
13.
14.
15.
16.
/**
* Indicate the content type (for example, text/html),
* being returned by the response
*/
17.
response.setContentType("text/plain");
18.
19.
20.
21.
/**
* Retrieve an output stream to use to send data to the client
*/
PrintWriter out = response.getWriter();
22.
23.
24.
25.
26.
27.
/**
* Write the response
*/
out.println("Welcome to iCarnegie!");
}
}
Introduction to Information Systems
6
Steps to process
doPost - II
1.
2.
3.
4.
5.
/**
* Author: ssd1-dev-srt
* Date: May'03
* Description: Servlet that displays a welcome message.
*/
6.
7.
8.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
• getWriter returns an object of the
class Welcome extends HttpServlet {
PrintWriter class identified by out 9.10. public
public void doPost(HttpServletRequest request,
11.
HttpServletResponse response)
after it completes execution.
12.
throws ServletException, IOException {
/**
• PrintWriter is a pre-defined class 13.
14.
* Indicate the content type (for example, text/html),
* being returned by the response
that processes messages to output15.
16.
*/
17.
response.setContentType("text/plain");
text to the browser.
18.
/**
• send println message to the out 19. * Retrieve an output stream to use to send data to the
client
object obtained in the previous 20. */
21.
PrintWriter out = response.getWriter();
step.
22.
/**
23.
* Write the response
• println requires actual text
24.
*/
message to be displayed i.e.
25.
out.println("Welcome to iCarnegie!");
26.
}
"Welcome to iCarnegie!“ here
27. }
7
Introduction to Information Systems
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>
<HTML>
<HEAD>
<TITLE>WelcomeForm</TITLE>
</HEAD>
<BODY bgcolor='#fdf5e6'>
<H1 ALIGN="center">Forms and Servlets</H1>
<FORM action='/servlet/Welcome' method='post'>
<BR>
<BR>
<BR>
<CENTER>
Please enter your name:
<INPUT type='text' size='20' name='Name' value=''>
<BR>
<BR>
<BR>
<INPUT type='submit' value='Done' name='userRequest'>
</CENTER>
</FORM>
</BODY>
</HTML>
WelcomeForm.
html
Introduction to Information Systems
Running a Java Program
• Load WelcomeForm.html with the Load HTML
command on the Actions menu of the workbench
• Load Welcome.class with the Load Java command
on the Actions menu of the workbench
• Select WelcomeForm.html from the Content
directory within the workbench
• Select Open in Browser command on the Actions
menu.
• “Welcome” servlet invoked when form submitted,
and browser displays the welcome message sent by
the servlet
Introduction to Information Systems
9
Sending HTML to browser
1. Define setContentType message to the response object as
response.setContentType("text/html");
2. Write HTML code for the web page.
3. Servlet needs to send println message to out object for
every line of HTML code
4. Compile the new servlet file, which sends messages as
part of a web page.
5. Use a form to invoke this servlet using action attribute of
the form element.
6. Run the servlet file after loading servlet and form files into
the iCarnegie workbench.
10
Introduction to Information Systems
Getting User Input - I
• WelcomeForm.html allowed user input which had no
significance for the form itself.
• To obtain user input, servlet needs to send getParameter
message to request, which is an HttpServletRequest object
as bellow.
String userName = request.getParameter("Name");
• When the request processes the getParameter message,
the result is an instance of the String class identified by the
name userName.
• getParameter takes the parameter "Name", which
identifies the name of the input text control in the form
11
Introduction to Information Systems
Getting User Input - II
• Change println message to include user input using string
concatenation (using “+”)
out.println("Welcome to iCarnegie, " + userName + "!");
• Try out PersonalWelcome servlet as listed in the reading as
an exercise.
12
Introduction to Information Systems
Debugging a Servlet
• Servlet execution can be monitored in order to
examine run-time errors.
• Add System.out.println messages to display progress
of servlet execution in the console window of the
workbench.
• These are similar out.println messages as below.
System.out.println(" Adding the welcome message next.");
13
Introduction to Information Systems
Planning Servlet Development
•
•
•
•
•
Thinking Ahead
Defining the Problem
Planning the Solution
Coding the Servlet
Testing and Evaluating the Servlet
14
Introduction to Information Systems
Thinking Ahead
• Consider the task of developing a Java servlet to handle
one the forms from the web site of a travel agency.
• Further, we would explore writing the servlet according
to specification provided.
• Ensure you have J2SE SDK and the iCarnegie Servlet
Workbench correctly installed before you move on.
• Define the problem first rather then jumping into
coding.
15
Introduction to Information Systems
Specification for the problem
• Given an HTML form TravelRequestForm.html
referring to 3 images and containing the following:
– A single-line text input control named Name
– A single-line text input control named PhoneNumber
– A radio button input control named Destination that has
three options:
• New York
• San Francisco
• Washington
– A submit button labeled Submit Request
• FORM action= '/servlet/TravelRequest‘, method=post .
16
Introduction to Information Systems
Our goal
• Develop a servlet called TravelRequest that
processes user input from the form in
TravelRequestForm.html.
• Servlet responds with an HTML Web page that
displays the following information:
– A confirmation message that includes the user's name
obtained from the form, and informs the user that he
or she will be contacted soon
– An image of some landmark from the travel
destination selected by the user on the form
• Use TravelRequest template from the course
17
Introduction to Information Systems
Planning the Solution - I
• Tasks to be done by servlet are the following :
1. Indicate the content type being returned by the
response
2. Retrieve an output stream to send data to the client
3. Get user input from the form: name and
destination
4. Start by building the Web page header
5. Add the image
6. Add the confirmation message, with the name
7. End by building the Web page footer
18
Introduction to Information Systems
Planning the Solution - II
• Two major components of the Web page:
• Confirmation message with user’s name,
depending on text input controls
• Image, depends on the radio button control
19
Introduction to Information Systems
Getting inputs into Servlet
• Servlet needs from the form: name and
destination
• Sending getParameter message to the
HttpServletRequest object to obtain value of
– radio button input control Destination from the
name of the image file for the destination city
– get the value of the text input control Name
20
Introduction to Information Systems
Generate Web page
• servlet must output all the HTML code for the
Web page the build it.
• IMG tag that uses the specification of the
image file input by user, required to display
image for destination
• A line of text that is the concatenation of the
message text with the user's' name, required
for confirmation message.
• servlet needs an out.println statement per line
of HTML code of the Web page
21
Introduction to Information Systems
Planing to code
• Build a Web page with a header, a footer, and a string in
the body. Test by submitting TravelRequestForm.html
• Write the code to obtain the user's choice of destination
and to construct a Web page with the image for it.
Verify for selected destination
• Write the code to obtain the user's name and substitute
in the confirmation message. Verify if name is displayed.
• While doing above, edit TravelRequest.java, compile the
servlet and run the servlet using
TravelRequestForm.html
22
Introduction to Information Systems
Final Servlet Code -I
• import java.io.*;
• import javax.servlet.*;
• import javax.servlet.http.*;
• public class TravelRequest extends HttpServlet {
•
•
•
•
•
•
•
•
•
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
/**
* Indicate the content type (for example, text/html),
* being returned by the response */
response.setContentType("text/html");
/**
* Retrieve an output stream to use to send data to the client */
PrintWriter out = response.getWriter();
23
Introduction to Information Systems
Final Servlet Code -II
•
•
•
•
•
•
•
•
•
•
•
•
/** Get the user input from the form : name and destination */
String destination = request.getParameter("Destination");
String name = request.getParameter(“Name");
/** Start by building the web page header */
out.println(
"<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>iCarnegie Travel Agency</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
/**Add the image */
out.println("<IMG src='/" + destination + "' alt='" + destination + "'>");
24
Introduction to Information Systems
Final Servlet Code -II
/** Add the confirmation message, with the name */
out.println("Hello, “ + name + “!”);
out.println(
"Thanks for your request. You will be contacted
shortly.");
/**End by building the web page footer */
out.println("</BODY>");
out.println("</HTML>");
} // end-doPost
}
25
Introduction to Information Systems
Evaluating the Servlet
• save the Web page to a file such as Test.html
• Ensure Test.html validates against the WDG
HTML Validator
• Compile and re-validation after every change
• Result- the sample response shows the
message after the image, while our response
shows the message next to the image.
• (Hint: try using one or two more out.println
statements in your servlet)
26
Introduction to Information Systems
Guidelines for Java Development
•
•
•
•
•
The Process of Programming
The Java API Documentation
Coding Style
Commenting Source Code
Javadoc
27
Introduction to Information Systems
Process of Programming
• Definition Phase
– Define and/or redefine the problem
• Planning Phase
– Plan a solution to the problem
• Coding Phase
– Code the solution
• Evaluation Phase
– Evaluate and test everything
28
Introduction to Information Systems
Notes on Process
• Process becomes significant as the complexity of
programs increases.
• Most of the time spent in evaluation and testing
• Evaluate your restatement to ensure correct
problem being solved.
• Use divide-and-conquer to solve a big problem.
• Code the small piece, inspect, and validate before
moving to next piece.
• More time spent on process implies less time spend
programming.
29
Introduction to Information Systems
Java API Documentation
• one or more of (APIs) need to be used for Java
• API provides a set of classes and methods to a
programmer, thus providing a e-usable
foundation to build upon.
• Java has its own Java API Documentation site
that is useful for finding accurate information
fast
• For example, classes can be looked up at the
Java Servlet Specification site.
30
Introduction to Information Systems
Coding Style
• Code should be written so as to be readable: by the
author at a later time
• Others expected to work on it for extending
functionality or debugging
• Code should be efficient, to function as expected in
the most optimal way in terms of time and usage of
system resources.
• This comes with experience and thorough
knowledge of the language.
• Java Coding Conventions document presents an
exhaustive set of rules and guidelines for writing Java
Code
31
Introduction to Information Systems
Commenting Source Code
• Comments an essential element of documenting code.
• Well-commented code is more maintainable for other
developers, and reduces Software's cost of ownership.
• Well-written comments should explain the purpose of
the class near the beginning of the class.
• Each method should have at least one comment
immediately before the method name to explain its
purpose
• Important to express the intent behind the code than
just re-stating.
32
Introduction to Information Systems
Javadoc
• Java SDK offers a tool for documenting code
called Javadoc.
• If comments typed in a specified format,
Javadoc program runs on your class and
generates HTML document containing your
comments in Java's standard documentation
format.
• For more information on Javadoc, refer to
http://java.sun.com/j2se/javadoc/index.html
33
Introduction to Information Systems