Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 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.

3 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.

4 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

5 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

6 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... }

7 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 {-----}

8 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..--- }

9 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

10 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

11 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( ); } }

12 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

13 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

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

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

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

17 Open a browser and call the Servlet using following URL http://localhost:8080/ServletApp/firstservlet

18 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(); }

19 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

20 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

21 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.

22 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

23 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 {-------}

24 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

25 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

26 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(); }

27 web.xml some VoteServlet some /first index.html

28 Output: Mr/Ms Venkat Bombotula is eligble to vote

29 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

30 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 - --- }

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

32 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 }

33 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

34 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 - --- }

35 Getting Context-parameters(Global variables) from web.xml to servlet ctx ContextServlet ctx /global Driver oracle.jdbc.driver.OracleDriver URL jdbc:oracle:thin:@localhost:1521:xe

36 username system password nie123

37 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");

38 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


Download ppt "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."

Similar presentations


Ads by Google