CSC 2720 Building Web Applications

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
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.
10-Jun-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
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.
Michael Brockway Application Integration Servlets l Introduction & Overview l HTTP Servlets l HTTP get Requests l HTTP post Requests l Multi-tier Applications.
Java Servlets.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
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.
Robinson_CIS285Winter2005 Servlets CIS January 2005 Mary Robinson.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
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.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Servlet Lifecycle Lec 28. Servlet Life Cycle  Initialize  Service  Destroy Time.
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.
Java Servlets & Java Server Pages Lecture July 2013.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
@2008 Huynh Ngoc Tin Chapter #2 JAVA SERVLET PRGRAMMING.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
L.MARIA MICHAEL VISUWASAM UNIT-4
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.
Servlets.
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.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
ORIGINAL BY WENDY LIU CURRENT API: Java Servlet and JSP 1.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
SERVLET THETOPPERSWAY.COM
Introduction To HTML Dr. Magdi AMER. HTML elements.
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Chapter 4 Request and Response. Servlets are controlled by the container.
1 Lecture 8 George Koutsogiannakis/Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Java Servlets References: Karen Anewalt, Mary Washington College.
Introduction to Servlets
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Pre-assessment Questions
Chapter 26 Servlets.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Objectives In this lesson you will learn about: Need for servlets
CS122B: Projects in Databases and Web Applications Winter 2019
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Overview of Server-Side Scripting Client sends a request via HTTP protocol A HTTP request consists of A request method: GET, POST, HEAD, PUT, etc. A URI that identifies the requested resource Header fields A body (which can be empty) Web server locates the corresponding server-side script and dispatches the HTTP request to the script. The server-side script processes the data embedded in the HTTP request and produces a HTTP response. The web server returns the generated HTTP response to the client.

Server-Side Scripting with Java Servlet Servlets are the Java platform technology of choice for extending and enhancing Web servers. A servlet is a module of Java code that is executed at the server side to process a request and generates a response based on that request. A servlet is not a standalone Java program nor it is a CGI-script written in Java. A servlet is an object with a specific interface and it can only be "executed" in a special environment known as servlet container. The Servlet technology offers a framework to write, deploy, and run servlets. It also serves as a foundation for other Java-based server-side technologies. e.g., JSP and JSF.

Servlet Application Architecture HTTP Request Servlet Container Browser HTTP Response Static Content HTTP Request HTTP Server Browser Static Content HTTP Response Servlet Container Servlet

Servlet Container A servlet container is a specialized web server or a component of a web server that supports servlet execution. It is responsible for Managing the lifecycle of servlets (load, initialize, dispatch requests, destroy, etc.) Mapping a URL to a particular servlet Providing access controls to the hosted resources Providing services defined in the Servlet API such as managing sessions, etc.

The Tomcat Container Apache Tomcat 6.0 Supports Servlet 2.5 and JavaServer Pages 2.1 The one bundled with NetBeans 6.0 is version 6.0.14 http://jakarta.apache.org/tomcat/ If you want to test your Servlets (without NetBeans), typically you have to Install and configure the Tomcat web server Set environment variables such as CLASSPATH Create proper directory structure for your web applications

How a Servlet Work Receive Request Send Response Is servlet loaded? up to date? Load Servlet Process Request No Yes Loaded by the container the first time a servlet is requested Handle the request Resides in memory and waits for future requests A servlet may get reloaded if modified

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorldServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println( "<html><head><title>Hello World Servlet</title>" + "</head><body>" + "Hello World" + "</body></html>" ); out.close(); } A servlet that output "Hello World".

Writing a Servlet Create a public class as a subclass of javax.servlet.http.HttpServlet Import the Java Servlet packages javax.servlet.* javax.servlet.http.* Override one or more doXXX() methods to process HTTP request and to produce HTTP response Typically, we override doGet(), doPost(), or both

Writing a Servlet Within the doGet() or doPost() methods, we typically perform the following tasks: Retrieve the data from HTTP request e.g.: Form data, parameters encoded in the URL, cookies, HTTP header fields Process the retrieved data Generate the content of the HTTP response: e.g.: Add header fields, set cookies, generate HTML codes, etc.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletEx1 extends HttpServlet { public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { // Retrieving value of parameters named "x" and "y" String x = req.getParameter("x"); String y = req.getParameter("y"); String sum = "Undefined"; // Process the data (calculate the sum) try { int v1 = Integer.parseInt(x); int v2 = Integer.parseInt(y); sum = "" + (v1 + v2); // Store the result as string } catch (Exception e) { } A servlet that adds the value of two parameters.

PrintWriter out = res.getWriter(); out.println( "<html><head><title>ServletEx1: Adding 2 #'s</title>" + "</head><body>" ); out.println("Value of x is: " + x + "<br />"); out.println("Value of y is: " + y + "<br />"); out.println("Their sum is: " + sum + "<br />"); out.println("</body></html>"); out.close(); } // End of doGet() } // end of class ServletEx1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

Getting Parameters Instance methods of HttpServletRequest for retrieving parameter values: String getParameter(String paramName) Use this method when a parameter has at most one value String [] getParameterValues(String paramName) Use this method if a parameter can have multiple values Both methods return null if the specified parameter does not exist. Instance methods of HttpServletRequest for retrieving all parameter names: java.util.Enumeration getParameterNames()

Parameter names are case sensitive. Getting Parameters Parameter names are case sensitive. Parameter values are retrieved as strings. You need to write code to convert them from strings to respective data types. Always validate the parameter values before processing the data Users may omit or mistype the values in a form. Hackers can bypass HTML form and JavaScript validation and generate HTTP POST/GET request programmatically.

Servlets Packages Package: javax.servlet Package: javax.servlet.http Contains many interfaces and abstract classes for protocol independent generic servlets Package: javax.servlet.http Contains interfaces and abstract classes for servlets that understand HTTP protocols Extends from the interfaces and classes used in the generic servlets Ref: Java Servlet 2.3 API documentation Servlet implemented by GenericServlet extended by HttpServlet extended by MyServlet

Characteristics of Servlet Class Every servlet directly or indirectly implements the javax.servlet.Servlet interface. That means, every servlet contains the following methods: void init(ServletConfig config) void service(ServletRequest req, ServletResponse res) void destroy() ServletConfig getServletConfig() String getServletInfo() A servlet container interacts with a servlet through these methods.

Servlet Life Cycles Initialization Handling Requests Termination The servlet's init() method is called once in a servlet's lifetime when a servlet is first loaded. If an exception is thrown or uncaught in init(), the servlet won't run. Handling Requests The servlet's service() method is called whenever a servlet is needed to service a request. A servlet can serve multiple requests concurrently (The container create threads to serve multiple requests) Termination The servlet's destroy() method is called once when the servlet is being unloaded from memory.

init() destroy() service() Servlet Life Cycles Overload this method only if you need to perform a task once in a servlet's lifecycle. e.g.: To open a database connection destroy() Overload this method only if you need to perform some cleanup tasks before a servlet is being unloaded from memory. e.g.: To close a database connection or to remove some temporary files service() Overload this method only if you need to handle ALL types of HTTP requests (GET, POST, DELETE, HEADER, PUT, etc.) To handle a specific type of HTTP requests, we can just overload one of doXXX() methods.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyPrimitiveServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle POST request } public void doGet(HttpServletRequest request, // Handle GET request HttpServlet implemented the method service() which dispatches various types of request (GET, POST, etc.) to the proper doXXX() methods respectively. Subclass should override at least one of the doXXX() methods.

HttpServletRequest object To obtain the data encapsulated in a HTTP request Form data, cookies, header fields, body contents Query string and additional path info embedded in the URL To obtain additional info about a request e.g.: The name of authentication scheme used To obtain info about the requester e.g.: Client's host name, IP address, etc. To obtain session information associated with the current request To carry additional data between servlets when a request is dispatched or forwarded from one servlet to another.

HttpServletResponse object To send data in the request body This object contains an output buffer which can be obtained via ServletOutputStream getOutputStream() Suitable for writing binary data java.io.PrintWriter getWriter() Suitable for writing texts Only one of the above methods can be called. Data written to the output buffer is sent to the client in the request body. To add header fields, add/set cookies, set content type, set status code, send error code and error message, send redirection instruction

ServletConfig object The ServletConfig object can be obtained by calling getServletConfig() The object contains some info specified in web application deployment/configuration file – web.xml Servlet's name Parameters to be passed to the servlet e.g., URL of the database A ServletContext object

ServletContext object A ServletContext object contains APIs for a servlet to communicate with its servlet container. e.g.: Get server info and version of the servlet API Write to the log file Get the MIME type of a file Dispatch requests There is one context per "web application" per servlet container. A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file. Servlets belong to the same application can share data through the ServletContext object.

Summary Fundamentally, all server-side scripts work in the following manner: Obtains data from a HTTP request Processes the data Produces HTTP response Java Servlet technology provides a framework to write, deploy and execute servlets. Serlvet APIs help programmers to Obtain data from a HTTP request (HttpServletRequest) Obtain info from the servlet container (ServletConfig and ServletContext) Set data in a HTTP response (HttpServletResponse) Manage session information (HttpServletRequest and HttpSession) References: "Java for the Web with Servlets, JSP, and EJB" by Budi Kurniawan Wiki: Java Servlets (http://en.wikipedia.org/wiki/Java_Servlet) Servlet Essentials (http://www.novocode.com/doc/servlet-essentials/)