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.

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.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Technology Overview JAVA Servlets CS-611 S. Witherspoon.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
MC365 Application Servers: Servlets. Today We Will Cover: What a servlet is The HTTPServlet and some of its more important methods How to configure the.
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.
1 CS6320 – Why Servlets? L. Grewe 2 What is a Servlet? Servlets are Java programs that can be run dynamically from a Web Server Servlets are Java programs.
Servlets CS-328 Dick Steflik. What is a servlet A Java application run on a thread of the webserver in response to an HTTP GET or POST request. The servlet.
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.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
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.
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.
Java Omar Rana University of South Asia. Course Overview JAVA  C/C++ and JAVA Comparison  OOP in JAVA  Exception Handling  Streams  Graphics User.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
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.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
1 CS122B: Projects in Databases and Web Applications Spring 2015 Notes 03: Web-App Architectures Professor Chen Li Department of Computer Science CS122B.
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
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.
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.
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,
SERVLET THETOPPERSWAY.COM
Chapter 4 Request and Response. Servlets are controlled by the container.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
CS122B: Projects in Databases and Web Applications Spring 2017
Introduction to Servlets
CS122B: Projects in Databases and Web Applications Winter 2017
Servlets.
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Pre-assessment Questions
Servlet API and Lifecycle
Chapter 26 Servlets.
CS122B: Projects in Databases and Web Applications Winter 2018
Introduction to Servlets
CS122B: Projects in Databases and Web Applications Spring 2018
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
Presentation transcript:

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 server side software component, written in java that dynamically extends the functionality of a server. Unlike applets servlets don’t display GUI. Unlike applets servlets don’t display GUI. It works behind the scene on server and results of servlet’s processing are returned to the client. It works behind the scene on server and results of servlet’s processing are returned to the client.

What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request- response programming model. A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request- response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

A servlet is an instance of a class that implements the java.servlet.Servlet interface. A servlet is an instance of a class that implements the java.servlet.Servlet interface. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

javax.servlet.GenericServlet Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable javax.servlet.GenericServlet Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable GenericServlet defines a generic, protocol-independent servlet. GenericServlet defines a generic, protocol-independent servlet. GenericServlet gives a blueprint and makes writing servlet easier. GenericServlet gives a blueprint and makes writing servlet easier. GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet implements the log method, declared in the ServletContext interface. GenericServlet implements the log method, declared in the ServletContext interface. To write a generic servlet, it is sufficient to override the abstract service method. To write a generic servlet, it is sufficient to override the abstract service method.

javax.servlet.http.HttpServlet Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable javax.servlet.http.HttpServlet Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable HttpServlet defines a HTTP protocol specific servlet. HttpServlet defines a HTTP protocol specific servlet. HttpServlet gives a blueprint for Http servlet and makes writing them easier. HttpServlet gives a blueprint for Http servlet and makes writing them easier. HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet. HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.

Advantages Capable of running in same process space as the web server. Capable of running in same process space as the web server. Compiled. Compiled. Crash resistant Crash resistant Cross platform Cross platform Durable Durable Dynamically loaded across the network Dynamically loaded across the network Extensible Extensible Multithreaded Multithreaded Protocol independent Protocol independent Written in java Written in java

Functions Dynamically build and return an HTML file based on client request. Dynamically build and return an HTML file based on client request. Process user input of HTML Form and return appropriate response. Process user input of HTML Form and return appropriate response. Facilitate communication among many clients. Facilitate communication among many clients. Interact with server resources like database, other application. Interact with server resources like database, other application. Multiplayer games. Multiplayer games.

HTTP Request Structure It is a stateless protocol. It is a stateless protocol. Server does not have the overhead of tracking client connections. Server does not have the overhead of tracking client connections. HTTP transactions are either a request or response. HTTP transactions are either a request or response. Servlet can overcome the stateless nature of HTTP by tracking client state using session information stored in URL, hidden fields or cookies. Servlet can overcome the stateless nature of HTTP by tracking client state using session information stored in URL, hidden fields or cookies.

3 parts of HTTP transactions A single request or response line A single request or response line – / HTTP/ e.g. –GET /index.html HTTP/1.1 –Response line contains an HTTP status code. HTTP/ OK Date:……………………….GMTServer:Last-modified: Content-type: text/html Content-length:….bytes

501 error is generated by the server when a servlet is sent an HTTP request that it does not handle. E.g. if you write your servlet to handle only GET requests, but it receives a POST request, a 501 status will return. 501 error is generated by the server when a servlet is sent an HTTP request that it does not handle. E.g. if you write your servlet to handle only GET requests, but it receives a POST request, a 501 status will return.

HTTP headers HTTP headers –A set of fields used to exchange information between client and server. –Client uses the headers to tell the server about its configuration and the document types it’ll accept. –Server uses the header to return information about the requested document. HTTP Body HTTP Body –Optionally used by client to send any additional information. –The server uses the body to return the requested document.

HTTP Methods GET is used to request information from server. GET is used to request information from server. POST is used to send data to the server. POST is used to send data to the server. GET can also be used to pass information in form of query string in URL and POST can be used for request. GET can also be used to pass information in form of query string in URL and POST can be used for request. Information sent as GET is visible to the client and append at URL. Information sent as GET is visible to the client and append at URL. POST sends data directly after the header, in body of message and doesn’t append at URL. POST sends data directly after the header, in body of message and doesn’t append at URL.

HEAD HEAD –If client wants information about a document but does not want the document to be returned. PUT PUT –Requests to server to store the body at a specified URL DELETE DELETE –Requests the removal of data at URL TRACE TRACE –Used for debugging. The HTTP body is simply returned by the server.

Servlet Environement The web server provides support for servlets with extensions called servlet containers. The web server provides support for servlets with extensions called servlet containers. Servlet Containers Functions: Servlet Containers Functions: –Network services over which request / response are sent. –Registers the servlet against one or more URL –Manage servlet life cycle –Decodes MIME (Multipurpose Internet Mail Extensions) requests –Constructs MIME response –Support HTTP protocol –Enforce security restrictions on environment.

Advantage of Servlets Over CGI Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technologies. (More importantly, servlet developers get paid more than Perl programmers :-). Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technologies. (More importantly, servlet developers get paid more than Perl programmers :-). Efficient. Efficient. –With traditional CGI, a new process is started for each HTTP request. –If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. –With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. –Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. –With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like. Convenient. Convenient. –You already know Java. –Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.

Powerful. Powerful. –Java servlets let you easily do several things that are difficult or impossible with regular CGI. –For one thing, servlets can talk directly to the Web server (regular CGI programs can't). –This simplifies operations that need to look up images and other data stored in standard places. –Servlets can also share data among each other, making useful things like database connection pools easy to implement. –They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations. Portable. Portable. –Servlets are written in Java and follow a well-standardized API. –Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. –Servlets are supported directly or via a plugin on almost every major Web server. Inexpensive. Inexpensive. –There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. –However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. –Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap

Servlet API It doesn’t run as an application rather it is loaded in memory and as instance is created. It doesn’t run as an application rather it is loaded in memory and as instance is created. When a servlet instance is created its init() is called. When a servlet instance is created its init() is called. Servlets are required to respond to new connections to the server. Servlets are required to respond to new connections to the server. When a new connection is detected, a call is made to the service() of the servlet. When a new connection is detected, a call is made to the service() of the servlet. service() takes two parameters defined by interface type called ServletRequest and ServletResponse. service() takes two parameters defined by interface type called ServletRequest and ServletResponse. Servlet class is abstract because service() is defined not implemented; so to implement a servlet, it is necessary to override this method. Servlet class is abstract because service() is defined not implemented; so to implement a servlet, it is necessary to override this method.

Servlet class is not protocol specific. Servlet class is not protocol specific. A subclass of Servlet class, the HttpServlet class is provided to handle http protocol. A subclass of Servlet class, the HttpServlet class is provided to handle http protocol. Two interfaces are defined for use with HttpServlet class Two interfaces are defined for use with HttpServlet class –HttpServletRequest –HttpServletResponse These extend the ServletRequest & ServletResponse. These extend the ServletRequest & ServletResponse.

Life Cycle of Servlet Servlet life cycle is defined by javax.servlet.Servlet inteface. Servlet life cycle is defined by javax.servlet.Servlet inteface. All servlets must implement javax.servlet.Servlet interface to run in a servlet engine. All servlets must implement javax.servlet.Servlet interface to run in a servlet engine.

Servlet Class Instantiation & loading Servlet engine can instantiate more than one servlet instance Initialization init(ServletConfig conf) Ready service() A service() executes for each servlet instance Destruction destroy() Garbage Collection Server no longer has a reference to the object

Servlet init() init() destroy() destroy() getServletConfig() getServletConfig() getServletInfo() getServletInfo() service() service()

GenericServlet init() init() distroy() distroy() log() log() getServletConfig() getServletConfig() getServletContext() getServletContext() getInitParameter() getInitParameter() getInitParameterNames() getInitParameterNames() getServletInfo() getServletInfo() getServletName() getServletName() service() service()

HTTPServlet doGet() doGet() doPost() doPost() doHead() doHead() doDelete() doDelete() doOptions() doOptions() doPut() doPut() doTrace() doTrace() getLastModified() getLastModified() service() service()

Creating servlets protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException Standard HTTP requests like Get and Post are supported by doGet() and doPost(). Standard HTTP requests like Get and Post are supported by doGet() and doPost().

HttpServletRequest getMethod() getMethod() –Returns get/post with which request was made. getQueryString() getQueryString() getRemoteUser() getRemoteUser() getRequestSessionId() getRequestSessionId() getSession(boolean) getSession(boolean) –If FALSE returns current valid session otherwise creates a new session. isRequestedSessionIdValid() isRequestedSessionIdValid() getCookies() getCookies()

HttpServletResponse addCookie(Cookie) addCookie(Cookie) –Add cookie to response encodeUrl(String) encodeUrl(String) sendRedirect(String) sendRedirect(String) sendError(int) sendError(int)

Servlet Context The javax.servlet.ServletContext interface provides a set of methods that the servlet can use to communicate with the web server. The javax.servlet.ServletContext interface provides a set of methods that the servlet can use to communicate with the web server. The ServletContext object is contained within javax.servlet.ServletConfig Object which is provided to the servlet when it is initialized. The ServletContext object is contained within javax.servlet.ServletConfig Object which is provided to the servlet when it is initialized.

Functions of ServletContext Object Set and store attributes that other servlets in the context can access. Set and store attributes that other servlets in the context can access. Log events Log events Obtain URL references to resources. Obtain URL references to resources. Get values assigned to initialization parameters. Get values assigned to initialization parameters. Get the MIME types of files. Get the MIME types of files. Obtain information about the servlet container such as its name and version. Obtain information about the servlet container such as its name and version. A servlet context is associated with a web application and shared by all the servlets within that application. A servlet context is associated with a web application and shared by all the servlets within that application.

Web Application Files and Directory Structure Each web application has a root called the context path. Each web application has a root called the context path. No two applications, in the same Web Server, can have the same context path because this would cause URL conflicts. No two applications, in the same Web Server, can have the same context path because this would cause URL conflicts. Document root is a special directory called WEB-INF. Document root is a special directory called WEB-INF. Contents of WEB-INF are- Contents of WEB-INF are- –Web.xml file web application deployment descriptor –/classes directory –/lib directory storage area for JAR file –/tags directory used to store tag libraries

There may be META-INF directory that contains implementation-specific deployment descriptor and WSDL (Web Service Definition Language) directory. There may be META-INF directory that contains implementation-specific deployment descriptor and WSDL (Web Service Definition Language) directory. /META-INF/MANIFEST.MF /META-INF/MANIFEST.MF /WEB-INF/classes/HTMLPage.class /WEB-INF/classes/HTMLPage.class /WEB-INF/classes/VerifyData.class /WEB-INF/classes/VerifyData.class /WEB-INF/Web.xml /WEB-INF/Web.xml /WEB-INF/sun-Web.xml /WEB-INF/sun-Web.xml /index.html /index.html

Handling Errors HTTP Errors HTTP Errors –XML error-page tag can be used <error-page><error-code>404</error-code><location>/examples/error404.html</location></error-page> –On error, the servlet can use either of the following method to set HTTP status code: public void HttpServletResponse.sendError(int sc) public void HttpServletResponse.sendError(int sc,String msg) –On error servlet can be redirected to another URL –HttpServletResponse.sendRedirect(String location)

Servlet Exceptions Catch all servlet generated exceptions in servlet and take actions accordingly. Catch all servlet generated exceptions in servlet and take actions accordingly. When a fatal error is generated an error message can be displayed When a fatal error is generated an error message can be displayed Catch(RemoteException e){ Res.sendError(503,”Internal Error”); Res.sendRedirect(“/example/ReportErrorPage”);} –During initialization or while handling requests the servlet instance can throw an UnavailableException or ServletException.

Cookie Class Cookie used for session management with HTTP and HTTPS. Cookie used for session management with HTTP and HTTPS. Used to get browsers to hold small data associated with user’s browsing. Used to get browsers to hold small data associated with user’s browsing. Cookies are named and have single value. Cookies are named and have single value. Assigned by the servers using fields added to HTTP response headers. Assigned by the servers using fields added to HTTP response headers. Cookies are saved one at a time into HTTP response headers using javax.servlet.http.HttpServletResponse.addCooki e(). Cookies are saved one at a time into HTTP response headers using javax.servlet.http.HttpServletResponse.addCooki e().

Web browsers are expected to support 20 cookies per host of at least 4KB each. Web browsers are expected to support 20 cookies per host of at least 4KB each. HTTP request fields are retrieved using javax.servlet.http.HttpServletRequest.getC ookie(). HTTP request fields are retrieved using javax.servlet.http.HttpServletRequest.getC ookie(). This returns all cookies found in request. This returns all cookies found in request.

Cookie Class Cookie(String name,String value) Cookie(String name,String value) setDomain(String) setDomain(String) getDomain() getDomain() setMaxAge(int) setMaxAge(int) –Age in sec; 0 to delete getMaxAge() getMaxAge() setValue(String) setValue(String) getValue() getValue() getName() getName()

Example Example FirstServlet.html FirstServlet.html FirstServlet.html FirstServlet.java FirstServlet.java FirstServlet.java STEPS STEPS Set classpath=c:/jsdk2.0/lib/jsdk.jar;C:/jsdk2.0/src Set classpath=c:/jsdk2.0/lib/jsdk.jar;C:/jsdk2.0/src Compile.java file Compile.java file –.class file should be in example directory Run servletrunner Run servletrunner Run FirstServlet.html in browser Run FirstServlet.html in browser –C:\JSDK2.0\examples\FirstServlet.html

Survey.html Survey.html Survey.html Survey.java Survey.java Survey.java

Questions What are two methods of HTTP to send requests to web server? Which should you use to send large amounts of information to the server? What are two methods of HTTP to send requests to web server? Which should you use to send large amounts of information to the server? What are the main uses of ServletContext Object? What are the main uses of ServletContext Object? What are the differences between Generic Servlet and Servlet? What are the differences between Generic Servlet and Servlet? What is pre initialization and lazy initialization of servlet? What is pre initialization and lazy initialization of servlet? Write short notes on Error handling of Servlet. Write short notes on Error handling of Servlet.