L.MARIA MICHAEL VISUWASAM UNIT-4

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
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.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
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.
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.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
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.
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 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 and JSP.
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.
Web server and web browser It’s a take and give policy in between client and server through HTTP(Hyper Text Transport Protocol) Server takes a request.
Introduction to servlet programming Pertemuan 6 Matakuliah: Web Programming Tahun: 2009.
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 
AN OVERVIEW OF SERVLET TECHNOLOGY SERVER SETUP AND CONFIGURATION WEB APPLICATION STRUCTURE BASIC SERVLET EXAMPLE Java Servlets - Compiled By Nitin Pai.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
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.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Copyright, 1996 © Dale Carnegie & Associates, Inc. Presented by Hsiuling Hsieh Christine Liu.
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.
Chapter 6 Server-side Programming: Java Servlets
1 CS122B: Projects in Databases and Web Applications Spring 2015 Notes 03: Web-App Architectures Professor Chen Li Department of Computer Science CS122B.
_______________________________________________________________________________________________________________ E-Commerce: Fundamentals and Applications1.
1 MSCS 237 Overview of web technologies (A specific type of distributed systems)
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.
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.
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.
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
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Chapter 4 Request and Response. Servlets are controlled by the container.
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.
1 Lecture 8 George Koutsogiannakis/Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
1 Web Programming with Servlets & JSPs WEB APPLICATIONS – AN OVERVIEW.
Introduction to Servlets
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
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
COP 4610L: Applications in the Enterprise Spring 2005
CS122B: Projects in Databases and Web Applications Winter 2019
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

L.MARIA MICHAEL VISUWASAM UNIT-4 SERVLET 4/25/2017 L.MARIA MICHAEL VISUWASAM UNIT-4

Where are we? JAVA Object-oriented design Introduction Advanced topics 4/25/2017 Where are we? JAVA Object-oriented design Introduction Advanced topics Server-side coding 10. JDBC 4. Object Classes 1. Intro to Java, Course 7. Inheritance 11.Streams 2. Java lang. basics 6. Exception Handling 13. Servlets 5. Encapsulation 14. JSP 3. Arrays 8. Polymorphism 12. Networking 9. Abstract classes and Interfaces Newbie Programmers Designers Developers Professionals L.MARIA MICHAEL VISUWASAM UNIT -4

Outline Concepts Features javax.servlet.Servlet Example: get and send a page to client Example: post Session tracking Cookie, HttpSession Practical examples

Today’s buzzwords Applets Servlets Session tracking Java programs capable of running within a web browser Servlets Java code running on server side Session tracking Keeping context information during a session of browsing related web pages

What is java servlet ? 1. A servlet is a small java program that runs within a web server. 2. Servlets receive and respond to requests from web clients, usually across HTTP. 3. Servlet is an opposite of applet as a server-side applet. Applet is an application running on client while servlet is running on server.

= What is Java Servlets? Servlet Browser Java-enabled Web Server 4/25/2017 What is Java Servlets? Servlet module run inside request/response-oriented server Browser Java-enabled Web Server Servlet Database HTML form Servlets are to Servers what Applets are to Browsers Servlet = Applet 1. 서블릿의 개념 - 서버측에서 클라이언트측의 요구를 받아 그에 대한 처리를 한 후 결과를 되돌리는 모듈이다. 2. 애플릿/서블릿 애플릿은 서버측에서 작성되었지만, 코드가 클라이언트로 다운로드되어 실행되는 반면, 서블릿은 서버 측에서 직접 실행되어 그 결과만 반환된다는 점에서 오히려 CGI와 비슷하다. 하지만,CGI보다는 요구와 결과를 처리하는 방법이 더 쉽다. 3. JDK의 기본 패키지가 아니다. 서블릿을 작성하려면, JDK외에 JSDK(98년 중반 현재 2.0까지 발표)를 다운로드받아야 한다. 4. 서블릿을 동작시키려면, 서블릿 실행을 처리할 수 있는 웹 서버 또한 존재해야 한다. Server Browser L.MARIA MICHAEL VISUWASAM UNIT -4

Example use of servlet Processing data POST over HTTPs using HTML form as purchase order or credit card data Allowing collaborative between people such as on-line conferencing Many servlet can chain together among Web servers to reduce load on one Web server.

Why Use Servlets ? One of the reasons that Java became popular is Applets. but there are problems with Applets Browser compatibility Download bandwidth Server-side Java the code is executed on the server side not the client side a dynamically loaded module that services requests from a Web server

Servlets (contd.) vs. Common Gateway Interface (CGI) create new process for each request most platform independent CGI language - Perl start a new instance of interpreter for every request CGI runs in a completely separate process from the Web server vs. Server-Side JavaScript only available on certain web servers vs. Active Server Pages (ASP)

Servlet Communication Web browser request servlet by specified URL as http://www.host.com/servlet/servletName Web server call service() method in ServletLoader class which will dynamically load a specified servlet name from a special directory call servlet.

Servlet vs CGI Servlet run as light weight thread in process. CGI run as heavy weight process.

Advantage of servlet over CGI PlatForm Independence Servlets can run on any platform. PERL also can be moved from platform to platform while CGI such as C are not portable. Performance Servlets only needs be loaded once, while CGI programs needs to be load for every request so that servlet should performs faster than CGI Security While CGI can do many insecure things, java provided security in language level.

Servlet Lifecycle Server loads Servlets - run init method 4/25/2017 Servlet Lifecycle No Concurrency Issue Server runs init only once, not per request Server loads Servlets - run init method Servlets Accept Request from Clients and return Data back - run service method service must be thread-safe - multiple service method at a time if that is impossible, servlet must implement SingleThreadModel interface Server removes Servlets - run destroy method destroy must be thread-safe - when server runs destroy, other threads might be accessing shared resources Server reloads Servlets - run init method L.MARIA MICHAEL VISUWASAM UNIT -4

Methods of the Servlet Interface Description destroy( ) Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. getServletConfig( ) Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. getServletInfo( ) Returns information about the servlet, such as author, version, and copyright. init( ) Called by the servlet container to indicate to a servlet that the servlet is being placed into service. service( ) Called by the servlet container to allow the servlet to respond to a request.

Servlet Overview and Architecture (cont.) Servlets are more commonly used when a small portion of the content sent to the client is static text or markup. In fact, some servlets do not produce content. Rather, they perform a task on behalf of the client, then invoke other servlets or JSPs to provide a response. Note that in most cases servlet and JSP technologies are interchangeable. The server that executes a servlet is referred to as the servlet container or servlet engine. Servlets and JSP have become so popular that they are now supported directly or with third-party plug-ins by most major Web servers and application servers (servers that execute applications to generate dynamic Web pages in response to requests).

Servlet Overview and Architecture (cont.) Servlet Container HTTP request HTTP request Web Browser Web Server Servlet    Servlet HTTP response HTTP response Database We’ll look at servlets that implement the request-response model between clients and servers using the HTTP protocol. This architecture is shown in the diagram above.

Servlet Overview and Architecture (cont.) Explanation of the architecture diagram on previous page A client application sends an HTTP request to the server. The servlet container receives the request and directs it to be processed by the appropriate servlet. The servlet does its processing, which may include interacting with a database or other server-side components, such as other servlets or JSPs. The servlet returns its results to the client – normally in the form of an HTML, XHTML, or XML document to display in a browser.

Servlet classes Example Interface Servlet Define the standard way in which a network server will access a servlet. All servlet classes must (fundamentally) implement this interface. GenericServlet Defines a generic, protocol-independent servlet. For servlet that is not intended to use with Web server. To write an HTTP servlet for use on the Web, extend HttpServlet instead. HttpServlet For Servlet that is intended to use with Web server. This class adds HTTP-specific to work with a Web server context

Servlet Structure All servlet classes and interfaces that form the API are found in the javax.servlet package. All servlets, no matter what type of server they are destined to be used with, implement the javax.servlet.Servlet interface. This interface defines the basic functionality that a servlet must possess

Servlet Interface The servlet packages define two abstract classes that implement interface Servlet – class GenericServlet (from the package javax.servlet) and class HttpServlet (from the package javax.servlet.http). These classes provide default implementations of some Servlet methods. Most servlets extend either GenericServlet or HttpServlet and override some or all of their methods. The GenericServlet is a protocol-indpendent servlet, while the HttpServlet uses the HTTP protocol to exchange information between the client and server. We’re going to focus exclusively on the HttpServlet used on the Web.

Servlet Interface (cont.) HttpServlet defines enhanced processing capabilities for services that extend a Web server’s functionality. The key method in every servlet is service, which accepts both a ServletRequest object and a ServletResponse object. These object provide access to input and output streams that allow the servlet to read data from and send data to the client. If a problem occurs during the execution of a servlet, either ServletExceptions or IOExceptions are thrown to indicate the problem.

HttpServlet Class Servlets typically extend class HttpServlet, which overrides method service to distinguish between the various requests received from a client web browser. The two most common HTTP request types (also known as request methods) are get and post. A get request retrieves information from a server. Typically, an HTML document or image. A post request sends data to a server. Typically, post requests are used to pass user input to a data-handling process, store or update data on a server, or post a message to a news group or discussion forum. Class HttpServlet defines methods doGet and doPost to respond to get and post requests from a client.

HTTPServlet Class (cont.) Methods doGet and doPost are invoked by method service, which is invoked by the servlet container when a request arrives at the server. Method service first determines the request type, the invokes the appropriate method for handling such a request. In addition to methods doGet and doPost, the following methods are defined in class HttpServlet: doDelete (typically deletes a file from the server) doHead (client wants only response headers no entire body) doOptions (returns HTTP options supported by server) doPut (typically stores a file on the server) doTrace (for debugging purposes)

HTTPServletRequest Interface Every invocation of doGet or doPost for an HttpServlet receives an object that implements interface HttpServletRequest. The servlet container creates an HttpServletRequest object and passes it to the servlet’s service method, which in turn, passes it to doGet or doPost. This object contains the clients’ request and provides methods that enable the servlet to process the request.

HTTPServletRequest Methods Cookie[] getCookies() – returns an array of Cookie objects stored on the client by the server. Cookies are used to uniquely identify clients to the server. String getLocalName() – gets the host name on which the request was received. String getLocalAddr() – gets the IP address on which the request was received. int getLocalPort() – gets the IP port number on which the request was received. String getParameter( String name) – gets the value of a parameter set to the servlet as part of a get or post request.

HTTPServletResponse Methods void addCookie (Cookie cookie) – adds a Cookie to the header of the response to the client. ServletOutputStream getOutputStream() – gets a byte-based output stream for sending binary data to the client. PrintWriter getWriter() – gets a character-based output stream for sending text data (typically HTML formatted text) to the client. void SetContentType (String type) – specifies the content type of the response to the browser to assist in displaying the data. void getContentType() – gets the content type of the response.

Example of an HTTP Servlet - GET/HEAD methods 4/25/2017 Example of an HTTP Servlet - GET/HEAD methods public class SimpleServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // set header field first res.setContentType("text/html"); // then get the writer and write the response data PrintWriter out = res.getWriter(); out.println("<HEAD><TITLE> SimpleServlet</TITLE></HEAD> <BODY>"); out.println("<h1> SimpleServlet Output </h1>"); out.println("</BODY>"); out.close(); } public String getServletInfo() { return "A simple servlet"; } } L.MARIA MICHAEL VISUWASAM UNIT -4

Accessing web-based servlets Assume the servlets' class file has been placed in the server's servlets directory. The servlet can be called by including /servlet/ before the servlet name in the URL. For example, if you set the class name of the sample servlet to TestServlet, then it could be accessed using http://<hostname>/servlet/TestServlet

Creating a Web Application (cont.) The most basic web application in Tomcat will require the creation of a directory inside the webapps directory to hold the web application. For this first example, we’ll create a subdirectory called first-examples. Create this directory inside the webapps directory of Tomcat.

Creating a Web Application (cont.) Within the first-examples directory we need to create a directory that will hold the configuration and all of the resources for the web application. This directory must be called WEB-INF. The most important and only required element in WEB-INF is the file web.xml. The web.xml file controls everything specific to the current web application. We’ll look at this file in more detail later as we add to it, but for now we’ll look only at the components of this file that are essential for a very simple web application. The next page illustrates our initial web.xml file.

Creating a Web Application (cont.) The web-app tag Optional display-name tag. Used by administrator tools. Optional description for reading the xml file. Servlet declaration. Specifies the name of the servlet, the implementing class file, and any initialization parameters. Servlet mapping associates a servlet name with a class of URLs. One servlet may be configured to handle multiple sets of URLs, however, only one servlet can handle any given URL.

Creating a Web Application (cont.) With these directories and files in place, Tomcat will be able to respond to a request for the page from a client athttp://localhost:8080/first-examples/WelcomeServlet.html. Other HTML and JSP pages can be added at will, along with images, MP3 files, and just about anything else. Although what we have just seen is all that is required to create a minimal web application, much more is possible with a knowledge of how web applications are arranged and we will see this as we progress through this technology. The next few slides illustrate the execution of our simple web application (a welcome servlet).

Execution of the WelcomeServlet Client invokes the WelcomeServlet page from the web application named first-examples. This is the XHTML file that generates the output shown above which informs the client how to invoke the servlet. Page 30

Execution of the WelcomeServlet servlet Page 31

An XHTML Document The XHTML document shown on page 30 provides a form that invokes the servlet defined on page 23. The form’s action attribute (/first-examples/welcome1) specifies the URL path that invokes the servlet. The form’s method attribute indicates that the browser sends a get request to the server, which results in a call to the servlet’s doGet method. We’ll look at how to set-up the URL’s and deployment structure in the next set of notes.

Set-Up For First Web Application The exact set-up you need to use for setting up your web application in Tomcat is summarized on the next couple of pages. In the Tomcat webapps folder create a directory named first-examples. In the top level of first-examples copy the WelcomeServlet.html file from the course code page. In the top level of first-examples create a directory named WEB-INF. When steps 2 and 3 are complete the top level of first-examples should look like the picture at the top of the next page.

Set-Up For First Web Application (cont.) Top level of first-examples. Copy the web.xml configuration file from the course code page into the WEB-INF directory. At the top level of the WEB-INF directory create a directory named classes. When steps 5 and 6 are complete, the WEB-INF directory should look like the picture on the top of the next page.

Set-Up For First Web Application (cont.) Copy the WelcomeServlet.java file from the course code page into the classes directory and compile it to produce the WelcomeServlet.class file which should also reside in the classes directory. (The .java file does not need to reside in this directory for a servlet, but it is handy to keep the source in the same place.) Top level of WEB-INF.

Set-Up For First Web Application (cont.) Once the classes directory looks like the one shown above. You are ready to invoke the servlet from a web browser. Start Tomcat and enter the URL http://localhost:8080/WelcomeServlet.html. Tomcat and the servlet will do the rest. If all goes well you should see the output that was shown on page 31. The classes directory