Programming with Java Lecture 6 Elements of a Java Servlet

Slides:



Advertisements
Similar presentations
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Advertisements

Java Server Pages (JSP)
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Server Side Programming Common Gateway Interface (CGI): Scripts generate Web pages or other files dynamically by processing form data and returning documents.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
An introduction to Java Servlet Programming
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
Servlets. A form The HTML source Chapter 1 Please enter your name and password then press start Name: Password: In Netbeans you can graphically create.
27-Jun-15 Directories and DDs. 2 Web apps A web application is basically a web site that: “Knows who you are”--it doesn’t just give you static pages,
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
Java Servlets and JSP.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
CS 160: Software Engineering September 3 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
A seminar on j2ee by saritha. s. What is J2EE J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Java Servlets and Java Server Pages Norman White Stern School of Business.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Java Servlets and Java Server Pages
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
Java Servlets References: Karen Anewalt, Mary Washington College.
Introduction to Servlets
CS3220 Web and Internet Programming Introduction to Java Servlets
Servlet Fudamentals.
Net-centric Computing
JDBC & Servlet CSE 4504/6504 Lab.
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Java Servlets.
Java Server Pages.
Servlets and Java Server Pages
Client side & Server side scripting
Servlets and JSP 20-Nov-18 servletsJSP.ppt.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Web Search Interfaces.
COP 4610L: Applications in the Enterprise Spring 2005
Java Servlets and JSP.
Web Search Interfaces by Ray Mooney
CS3220 Web and Internet Programming Introduction to Java Servlets
J2EE Lecture 1:Servlet and JSP
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Java Servlets Servlet Overview Servlets and HTML Forms Servlet Basics
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Directories and DDs 25-Apr-19.
Basic servlet structure
Directories and DDs 21-Jul-19.
Servlets: Servlet / Web Browser Communication I
Directories and DDs 14-Sep-19.
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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

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

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

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

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

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

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

<!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

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

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.

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

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.

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

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

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.

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 .

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

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

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

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

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

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

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

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

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 }

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)

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

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

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.

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.

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

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.

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