Servlets By B. Venkateswarlu M.Tech Assoc Prof IT(Dept) Newton’s Institute of Engineering By B. Venkateswarlu M.Tech Assoc Prof IT(Dept) Newton’s Institute.

Slides:



Advertisements
Similar presentations
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
Advertisements

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 Stoney Jackson
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.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
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.
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 Life Cycle. The Servlet Life Cycle A servlet life cycle can be defined as the entire process from its creation till the destruction. The following.
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 and JSP.
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.
SERVLETS.
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.
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. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
AN OVERVIEW OF SERVLET TECHNOLOGY SERVER SETUP AND CONFIGURATION WEB APPLICATION STRUCTURE BASIC SERVLET EXAMPLE Java Servlets - Compiled By Nitin Pai.
1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send .
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.
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.
Servlets Server-Side Software. Objective What is a servlet? Where do servlets fit in? What can servlets do? Why are servlets better than CGI? Servlet.
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.
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.
Servlets Included in the J2EE.
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.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
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.
Java Servlets Java Server Pages (JSP)
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
April 20023CSG11 Electronic Commerce Java (2) John Wordsworth Department of Computer Science The University of Reading Room 129,
Chapter 4 Request and Response. Servlets are controlled by the container.
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.
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
Introduction to Java Servlets
Presentation transcript:

Servlets By B. Venkateswarlu M.Tech Assoc Prof IT(Dept) Newton’s Institute of Engineering By B. Venkateswarlu M.Tech Assoc Prof IT(Dept) Newton’s Institute of Engineering

Servlets Servlets are java objects which are capable of extending functionality of web server Servlets are server side Java programs Servlets are Java classes that process the request dynamically Servlets are used to process the HTTP requests and generate the HTML response.

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. Servlet is an opposite of applet as a server-side applet. Applet is an application running on client while servlet is running on server.

Servlet Life Cycle A servlet life cycle can be defined as the entire process from its creation till the destruction The following are the paths followed by a servlet 1. init()-The servlet is initialized by calling the init () method 2. service()-The servlet calls service() method to process a client's request 3. destroy()-The servlet is terminated by calling the destroy() method Finally, servlet is garbage collected by the garbage collector of the JVM

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

Init(): The init method is designed to be called only once It is called when the servlet is first created, and not called again for each user request. The init() method simply creates or loads some data that will be used throughout the life of the servlet Look like this: public void init() throws ServletException { // Initialization code... }

Service(): The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {-----}

Destroy(): The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. After the destroy() method is called, the servlet object is marked for garbage collection public void destroy() { -- // Finalization code..--- }

Development of a Web application Step1: Create a directory to place everything related to the web application. This directory can be called as “Web Root” or “Document Root” Ex: C:\ServletApp Step 2: Under Web Root create a directory with the name WEB-INF Ex: C:\ServletApp\WEB-INF ServletApp WEB-INF

Step 3: Under WEB-INF create two directories a)classes b)lib WEB-INF classeslib ServletApp Root Directory or Webroot Used to place jar files Used to place Servlet.class files

Create a Servlet Class as follows Step4: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException { response.setContentType("text/html"); PrintWriter out=response.getWriter( ); out.println(" "); out.println(" WelcomeServlet "); out.println(" "); out.println(" HelloWorld "); out.println(" "); out.close( ); } }

Step5: Set the CLASSPATH with servlet-api.jar file and compile created Servlet class C:\>ServletApp>WEB-INF>classes>set CLASSPATH=%CLASSPATH%; C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar;. C:\>ServletApp>WEB-INF>classes>javac HelloServlet.java

Step6:Create web.xml file under WEB-INF directory web.xml some HelloServlet some /firstservlet web.xml some HelloServlet some /firstservlet OUTPUT: Hello World OUTPUT: Hello World

Developed Application. ServletApp WEB-INF classes lib web.xml *.jar HelloServlet.java HelloServlet.class

Deployment copy the developed web application and place in Tomcat Web Server’s webapps directory

Running Start the Server Goto All Programs-> Apache Tomcat 6.0-> Configure Tomcat

Open a browser and call the Servlet using following URL

Servlet program for displaying current date. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class DateServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException { response.setContentType("text/html"); PrintWriter out=response.getWriter( ); out.println(" "); Date d=new Date(); out.println("Today Date is"+d); out.println(" "); out.close(); }

web.xml two DateServlet two /second web.xml two DateServlet two /second Output: Today Date is Mon Feb 27 09:15:36 PDT 2012 Output: Today Date is Mon Feb 27 09:15:36 PDT 2012

Servlet API The Servlet API consists of classes and interfaces needed to build servlets. These classes and interfaces come in two packages 1. javax.servlet 2. javax.servlet.http

Javax.servlet package It contains number of interfaces and classes that establish the framework. Interfaces Classes 1.Servlet 1.GenericServlet 2.ServletConfig 2.ServletInputStream 3.ServletContext 3.ServletOutputStream 4.ServletRequest 4.ServletException 5.ServletResponse 5.UnavailableException Here Servlet interface and GenericServlet class are important.

javax.servlet.Servlet javax.servlet.GenericServlet javax.servlet.http.HttpServlet void init(ServletConfig) void destroy() void service(ServletRequest, ServletResponse) ServletConfig getServletConfig() String getServletInfo() init(ServletConfig) init() ……. Does not implement service() method doxxx(HttpServletRequest, HttpServletResponse) protected service( HttpServletRequest, HttpServletResponse) public service(ServletRequest, ServletResponse) implements extends (Abstract) Servlet Development

There are 3 ways to develop a servlet 1. Take a java class implementing javax.servlet.Servlet interface and provide implementation for all 5 methods. Ex: public class MyServlet implements Servlet { } 2. Take a java class extending form javax.servlet.GenericServlet and provide implementation for service() method Ex:public class MyServlet extends GenericServlet{----} 3.Take a java class extending from javax.servlet.http.HttpServlet and Override either one of the service mehtod or one of the doXXX() methods. Ex: public class MyServlet extends HttpServlet { }

Javax.servlet.http package It contains number of interfaces and classes that are commonly used by servlet developers. Interfaces Classes 1.HttpServletRequest 1.Cookie 2.HttpServletResponse 2.HttpServlet 3.HttpSession 3.HttpSessionEvent 4.HttpSessionBindingListener 4.HttpSessionBindingEvent

Servlet program for reading data from html form. (Verifying Whether the user is eligible to vote or not) index.html Homepage FirstName LastName Age Venkat Bombotula 27 First Name Last Name Age VerifyCancel

Servlet Program import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class VoteServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println(" "); String fn=request.getParameter("fname"); String ln=request.getParameter("lname"); int ag=Integer.parseInt(request.getParameter(“age")); if(ag>=18) out.println(“Mr/Ms”+fn+” “+ln+”is eligible to vote”); else out.println(“Mr/Ms”+fn+” “+ln+”is not eligible to vote”); out.println(" "); out.close(); }

web.xml some VoteServlet some /first index.html

Output: Mr/Ms Venkat Bombotula is eligble to vote

ServletConfig Object: One per Servlet Object It will be created by web server when Servlet object is created and will be destroyed by web server when Servlet object is destroyed. Useful to gather init-parameters(Local variables) of a Servlet availabe in web.xml Userful to get information of a perticular Servlet

Different ways to get access to ServletConfig object 1. public class TestServlet extends HttpServlet { public void init(ServletConfig sc) { ---- //Use sc object here ---- } 2. public class TestServlet extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) { ServletConfig sc=getServletConfig(); ---- //Use sc object here }

Getting Initialization parameters(Local variables) from web.xml to servlet in InitServlet SNo 09A11A1227 SName Sai Ram in /init

Getting Initialization parameters(Local variables) from web.xml to servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InitServlet extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { resp.setContentType("text/html"); PrintWriter out=resp.getWriter(); ServletConfig cg=getServletConfig(); /* String sn=cg.getInitParameter("SNO"); String sna=cg.getInitParameter("SNAME"); out.println(sn+" "+sna); */ Enumeration e=cg.getInitParameterNames(); while(e.hasMoreElements()) { String name=(String)e.nextElement(); String no=cg.getInitParameter(name); out.println(name+" "+no+" "); } } OUTPUT: O9A11A1227 Sai Ram }

ServletContext: One per web application Web server creates this object when application is deployed Web server destroys this object when web application is undeployed or reloaded or stopped Useful to gather context parameters or global unic parameters from web.xml Userful to get information of entire application

Different ways to get access to ServletContext object 1. public class TestServlet extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response { ---- ServletConfig sc=getServletConfig(); ServletContext cg=sc.getServletContext(); //Use cg object here ---- } 2. public class TestServlet extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) { ServletContext cg=getServletContext(); ---- //Use cg object here }

Getting Context-parameters(Global variables) from web.xml to servlet ctx ContextServlet ctx /global Driver oracle.jdbc.driver.OracleDriver URL

username system password nie123

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class ContextServlet extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { try { resp.setContentType("text/html"); PrintWriter out=resp.getWriter(); ServletContext sc=getServletContext(); String driver=sc.getInitParameter("Driver"); String url=sc.getInitParameter("URL");

String user=sc.getInitParameter("username"); String pass=sc.getInitParameter("password"); //load driver Class.forName(driver); //connect with db Connection con=DriverManager.getConnection(url,user,pass); out.println("Connected With DB using ContextParameters"); } catch (Exception e) { e.printStackTrace(); } OUTPUT: Connected With DB using ContextParameters