Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming with Java Lecture 6 Elements of a Java Servlet

Similar presentations


Presentation on theme: "Programming with Java Lecture 6 Elements of a Java Servlet"— Presentation transcript:

1 Programming with Java Lecture 6 Elements of a Java Servlet
   Planning Servlet Development  Guidelines for Java Development

2 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!"); }

3 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

4 Identifiers and Keywords
public class Welcome extends HttpServlet { public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Identifiers and Keywords 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

5 Request and response Objects
public class Welcome extends HttpServlet { public void doPost (HttpServletRequest request, HttpServletResponse response) Request and 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 back to the browser

6 Steps to process doPost - I
/** * 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!"); } 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

7 Steps to process doPost - II
/** * 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!"); } getWriter returns an object of the PrintWriter class identified by out after it completes execution. PrintWriter is a pre-defined class that processes messages to output text to the browser. send println message to the out object obtained in the previous step. println requires actual text message to be displayed i.e. "Welcome to iCarnegie!“ here

8 <!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>
<HEAD> <TITLE>WelcomeForm</TITLE> </HEAD> <BODY bgcolor='#fdf5e6'> <H1 ALIGN="center">Forms and Servlets</H1> <FORM action='/servlet/Welcome' method='post'> <BR> <CENTER> Please enter your name: <INPUT type='text' size='20' name='Name' value=''> <INPUT type='submit' value='Done' name='userRequest'> </CENTER> </FORM> </BODY> </HTML> WelcomeForm.html

9 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

10 Sending HTML to browser
Define setContentType message to the response object as response.setContentType("text/html"); Write HTML code for the web page. Servlet needs to send println message to out object for every line of HTML code Compile the new servlet file, which sends messages as part of a web page. Use a form to invoke this servlet using action attribute of the form element. Run the servlet file after loading servlet and form files into the iCarnegie workbench.

11 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

12 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.

13 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.");

14 Planning Servlet Development
Thinking Ahead Defining the Problem Planning the Solution Coding the Servlet Testing and Evaluating the Servlet

15 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.

16 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 .

17 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

18 Planning the Solution - I
Tasks to be done by servlet are the following : Indicate the content type being returned by the response Retrieve an output stream to send data to the client Get user input from the form: name and destination Start by building the Web page header Add the image Add the confirmation message, with the name End by building the Web page footer

19 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

20 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

21 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

22 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

23 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();

24 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 + "'>");

25 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 }

26 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)

27 Guidelines for Java Development
The Process of Programming The Java API Documentation Coding Style Commenting Source Code Javadoc

28 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

29 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.

30 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.

31 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

32 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.

33 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


Download ppt "Programming with Java Lecture 6 Elements of a Java Servlet"

Similar presentations


Ads by Google