Servlets.

Slides:



Advertisements
Similar presentations
Servlets & JSPs - Sharad Ballepu.
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
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.
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.
Session-02.
Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
SERVLET Ch-6. Introduction Web development is all about communication. In this case, communication between 2 parties, over the HTTP protocol: The 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.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
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.
1 Lecture 10 Server-side Programming: Java Servlets.
Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.
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.
1 Chapter 2 The Web Tier  Web Applications and Web ContainersWeb Applications and Web Containers  Dynamic Content CreationDynamic Content Creation 
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
CSC 2720 Building Web Applications
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.
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.
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.
Chapter 6 Server-side Programming: Java Servlets
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.
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.
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.
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.
Java Servelets. A servlet is a server side software component, written in java that dynamically extends the functionality of a server. A servlet is a.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
K. K. Wagh Polytechnic, Nashik
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.
Distributed Web Systems Java Servlets Lecturer Department University.
Introduction to Servlets
Servlets.
Server Side Programming
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Servlet API and Lifecycle
Chapter 26 Servlets.
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:

Servlets

What can you build with Servlets? Search Engines E-Commerce Applications Shopping Carts Product Catalogs Intranet Applications Groupware Applications: bulletin boards file sharing

Servlets vs. CGI A Servlet does not run in a separate process. Browser 1 Web Server Browser 2 Browser N Perl 1 Perl 2 Perl N A Servlet does not run in a separate process. A Servlet stays in memory between requests. A CGI program needs to be loaded and started for each CGI request. There is only a single instance of a servlet which answers all requests concurrently. Browser 1 Web Server Browser 2 Browser N Servlet

Benefits of Java Servlets Performance The performance of servlets is superior to CGI because there is no process creation for each client request. Each request is handled by the servlet container process. After a servlet has completed processing a request, it stays resident in memory, waiting for another request. Portability Like other Java technologies, servlet applications are portable. Rapid development cycle As a Java technology, servlets have access to the rich Java library that will help speed up the development process. Robustness Servlets are managed by the Java Virtual Machine. Don't need to worry about memory leak or garbage collection, which helps you write robust applications. Widespread acceptance Java is a widely accepted technology.

Definitions A servlet is a Java class that can be loaded dynamically into and run by a special web server. This servlet-aware web server, is known as servlet container. Servlets interact with clients via a request-response model based on HTTP. Therefore, a servlet container must support HTTP as the protocol for client requests and server responses. A servlet container also can support similar protocols such as HTTPS (HTTP over SSL) for secure transactions.

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

How Servlets Work is servlet No Receive loaded? Request Yes is servlet current? No Load Servlet Yes Send Response Process Request

Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet javax.servlet.http.HttpServlet

Generic Servlet & HTTP Servlet Client request Server service ( ) response HTTPServlet Browser request doGet ( ) HTTP Server service ( ) response doPost ( )

Interface javax.servlet.Servlet The Servlet interface defines methods to initialize a servlet to receive and respond to client requests to destroy a servlet and its resources to get any startup information to return basic information about itself, such as its author, version and copyright. Developers need to directly implement this interface only if their servlets cannot (or choose not to) inherit from GenericServlet or HttpServlet. Life Cycle Methods

GenericServlet - Methods void init(ServletConfig config) Initializes the servlet. void service(ServletRequest req, ServletResponse res) Carries out a single request from the client. void destroy() Cleans up whatever resources are being held (e.g., memory, file handles, threads) and makes sure that any persistent state is synchronized with the servlet's current in-memory state. ServletConfig getServletConfig() Returns a servlet config object, which contains any initialization parameters and startup configuration for this servlet. String getServletInfo() Returns a string containing information about the servlet, such as its author, version, and copyright.

Servlet Life Cycle Initialization Service Concurrent Threads doGet() doPost() doDelete() doHead() doTrace() doOptions() Concurrent Threads of Execution In the Request Processing phase a JSP page is handled exactly like a regular servlet. Servlets follow a three-phase life cycle: initialization, service, and destruction, with initialization and destruction typically performed once, and service performed many times. Initialization is the first phase of the Servlet life cycle and represents the creation and initialization of resources the Servlet may need to service requests. For example open a db connection, read ancillary files, get runtime parameters. All Servlets must implement the javax.servlet.Servlet interface. This interface defines the init() method to match the initialization phase of a Servlet life cycle. When a container loads a Servlet, it invokes the init() method before servicing any requests. The service phase of the Servlet life cycle represents all interactions with requests until the Servlet is destroyed. The Servlet interface matches the service phase of the Servlet life cycle to the service() method. The service() method of a Servlet is invoked once per each request and is responsible for generating the response to that request. By default a Servlet is multi-threaded, meaning that typically only one instance of a Servlet is loaded by a JSP container at any given time. Initialization is done once, and each request after that is handled concurrently by threads executing the Servlet’s service() method. This implies that a developer needs to be careful in synchronizing shared resources. The destruction phase of the Servlet life cycle represents when a Servlet is being removed from use by a container. The Servlet interface defines the destroy() method to correspond to the destruction life cycle phase. Each time a Servlet is about to be removed from use, a container calls the destroy() method, allowing the Servlet to gracefully terminate and tidy up any resources it might have created. For example closing files, db connections. Init() and destroy() methods can be overwritten by the JSP page author. Service() methos is generated automatically during translation phase and should neve be overwritten. Destruction destroy()

HttpServlet - Methods void doGet (HttpServletRequest request, HttpServletResponse response) handles GET requests void doPost (HttpServletRequest request, handles POST requests void doPut (HttpServletRequest request, handles PUT requests void doDelete (HttpServletRequest request, handles DELETE requests

Servlet Request Objects provides client request information to a servlet. the servlet container creates a servlet request object and passes it as an argument to the servlet's service method. the ServletRequest interface define methods to retrieve data sent as client request: parameter name and values attributes input stream HTTPServletRequest extends the ServletRequest interface to provide request information for HTTP servlets

HttpServletRequest - Methods Enumeration getParameterNames() an Enumeration of String objects, each String containing the name of a request parameter; or an empty Enumeration if the request has no parameters java.lang.String[] getParameterValues (java.lang.String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. java.lang.String getParameter (java.lang.String name) Returns the value of a request parameter as a String, or null if the parameter does not exist.

HttpServletRequest - Methods Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent with this request. java.lang.String getMethod() Returns the name of the HTTP method with which\thi request was made, for example, GET, POST, or PUT. getQueryString() Returns the query string that is contained in the request URL after the path. HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, creates one.

Servlet Response Objects Defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method.

HttpServletResponse - Methods java.io.PrintWriter getWriter() Returns a PrintWriter object that can send character text to the client void setContentType (java.lang.String type) Sets the content type of the response being sent to the client. The content type may include the type of character encoding used, for example, text/html; charset=ISO-8859-4 int getBufferSize() Returns the actual buffer size used for the response

Steps to Running a Servlet Create a directory structure under Tomcat for your application. Write the servlet source code. Compile your source code. deploy the servlet Run Tomcat Call your servlet from a web browser

Create a Directory Structure The webapps directory is the Tomcat installation dir (CATALINA_HOME) is where you store your web applications. A web application is a collection of servlets and other contents installed under a specific subset of the server's URL namespace. A separate directory is dedicated for each servlet application. Create a directory called myApp under the webapps directory. Create the src and WEB-INF directories under myApp, and create a directory named classes under WEB-INF. The src directory is for your source files, and the classes directory under WEB-INF is for your Java classes. If you have html files, you put them directly in the myApp directory. The admin, ROOT, and examples directories are for applications created automatically when you install Tomcat

Write the Servlet Code Servlets implement the javax.servlet.Servlet interface. Because most servlets extend web servers that use the HTTP protocol to interact with clients, the most common way to develop servlets is by specializing the javax.servlet.http.HttpServlet class. The HttpServlet class implements the Servlet interface by extending the GenericServlet base class, and provides a framework for handling the HTTP protocol. Its service() method supports standard HTTP requests by dispatching each request to a method designed to handle it. In myApp/src, create a file called TestingServlet.java

Servlet Example 1: import java.io.*; 2: import javax.servlet.*; 3: import javax.servlet.http.*; 4: 5: public class MyServlet extends HttpServlet 6: { 7: protected void doGet(HttpServletRequest req, 8: HttpServletResponse res) 9: { 10: res.setContentType("text/html"); 11: PrintWriter out = res.getWriter(); 12: out.println( "<HTML><HEAD><TITLE> Hello You!” + 13: “</Title></HEAD>” + 14: “<Body> HelloYou!!!</BODY></HTML>“ ); 14: out.close(); 16: } 17: }

An Example of Servlet (I) Lines 1 to 3 import some packages which contain many classes which are used by the Servlet (almost every Servlet needs classes from these packages). The Servlet class is declared in line 5. Our Servlet extends javax.servlet.http.HttpServlet, the standard base class for HTTP Servlets. In lines 7 through 16 HttpServlet's doGet method is getting overridden

An Example of Servlet (II) In line 11 we use a method of the HttpServletResponse object to set the content type of the response that we are going to send. All response headers must be set before a PrintWriter or ServletOutputStream is requested to write body data to the response. In line 12 we request a PrintWriter object to write text to the response message. In lines 13 and 14 we use the PrintWriter to write the text of type text/html (as specified through the content type).

An Example of Servlet (III) The PrintWriter gets closed in line 15 when we are finished writing to it. In lines 18 through 21 we override the getServletInfo() method which is supposed to return information about the Servlet, e.g. the Servlet name, version, author and copyright notice. This is not required for the function of the HelloClientServlet but can provide valuable information to the user of a Servlet who sees the returned text in the administration tool of the Web Server.

Compile the Servlet Compile the Servlet class The resulting TestingServlet.class file should go under myApp/WEB-INF/classes

Deploy the Servlet In the Servlet container each application is represented by a servlet context each servlet context is identified by a unique path prefix called context path For example our application is identified by /myApp which is a directory under webapps. The remaining path is used in the selected context to find the specific Servlet to run, following the rules specified in the deployment descriptor.

Deployment Descriptor The deployment descriptor is a XML file called web.xml that resides in the WEB-INF directory whitin an application. <web-app xmlns=http://java.sun.com/xml/ns/j2ee……> <display-name>test</display-name> <description>test example</description> <servlet> <servlet-name>Testing</servlet-name> <servlet-class>TestingServlet</servlet-class> </servlet> <servlet-mapping> <url-pattern>/servlet/TestingServlet</url-pattern> </servlet-mapping> </web-app>

Run the Servlet To execute your Servlet, type the following URL in the Browser’s address field: http://localhost/myApp/servlet/myServlet

Running service() on a single thread By default, servlets written by specializing the HttpServlet class can have multiple threads concurrently running its service() method. If you would like to have only a single thread running a service method at a time, then your servlet should also implement the SingleThreadModel interface. This does not involve writing any extra methods, merely declaring that the servlet implements the interface.

Example public class SurveyServlet extends HttpServlet implements SingleThreadModel { /* typical servlet code, with no threading concerns * in the service method. No extra code for the * SingleThreadModel interface. */ ... }