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

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

Embed Size (px)

Citation preview

Slide 1

ServletsByB. Venkateswarlu M.TechAssoc Prof IT(Dept)Newtons Institute of Engineering

ServletsServlets are java objects which are capable of extending functionality of web serverServlets are server side Java programsServlets are Java classes that process the request dynamicallyServlets 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 destructionThe following are the paths followed by a servletinit()-The servlet is initialized by calling the init () methodservice()-The servlet calls service() method to process a client's requestdestroy()-The servlet is terminated by calling the destroy() methodFinally, servlet is garbage collected by the garbage collector of the JVM

Servlet LifecycleServer loads Servlets- run init methodServlets Accept Request fromClients and return Data back- run service methodServer removes Servlets- run destroy methodNo Concurrency IssueServer runs init only once, not per requestservice must be thread-safe- multiple service method at a timeif that is impossible, servlet must implement SingleThreadModel interfaceServer reloads Servlets- run init methoddestroy must be thread-safe- when server runs destroy, other threadsmight be accessing shared resourcesInit():The init method is designed to be called only onceIt 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 servletLook 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 ServletAppServletAppWEB-INFStep 3: Under WEB-INF create two directories a)classes b)lib

WEB-INFclasseslibServletAppRoot Directory or WebrootUsed to place jar filesUsed to place Servlet .class filesCreate a Servlet Class as followsStep4:

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(""); out.println("WelcomeServlet"); out.println(""); out.println(""); out.println("HelloWorld"); out.println(""); out.println(""); out.close( ); } }

Step5:Set the CLASSPATH with servlet-api.jar file and compile created Servlet classC:\>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

someHelloServlet

some/firstservlet

OUTPUT: Hello World

Developed Application.ServletAppWEB-INFclasseslibweb.xml*.jarHelloServlet.javaHelloServlet.classDeploymentcopy the developed web application and place in Tomcat Web Servers webapps directory

Running

Start the ServerGoto All Programs->Apache Tomcat 6.0->Configure Tomcat

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

http://localhost:8080/ServletApp/firstservlet

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(""); out.println(""); Date d=new Date(); out.println("Today Date is"+d); out.println(""); out.println(""); out.close(); } }

web.xml

twoDateServlet

two/second

Output: Today Date is Mon Feb 27 09:15:36 PDT 2012

Servlet APIThe Servlet API consists of classes and interfaces needed to build servlets.These classes and interfaces come in two packages 1. javax.servlet2. javax.servlet.httpJavax.servlet packageIt 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.Servletjavax.servlet.GenericServletjavax.servlet.http.HttpServletvoid init(ServletConfig)void destroy()void service(ServletRequest, ServletResponse)ServletConfig getServletConfig()String getServletInfo()init(ServletConfig)init().Does not implement service() methoddoxxx(HttpServletRequest, HttpServletResponse)protected service( HttpServletRequest, HttpServletResponse)public service(ServletRequest, ServletResponse)

implementsextends(Abstract)(Abstract)Servlet DevelopmentThere are 3 ways to develop a servlet1. 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 packageIt 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.HttpSessionEvent4.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

VenkatBombotula27First NameLast NameAgeVerifyCancelServlet Programimport 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(""); 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.println(""); out.close(); } }

web.xml

someVoteServlet

some/first

index.html

Output:Mr/Ms Venkat Bombotula is eligble to voteServletConfig Object:One per Servlet ObjectIt 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.xmlUserful to get information of a perticular Servlet Different ways to get access to ServletConfig object1. 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

inInitServlet

SNo09A11A1227

SNameSai Ram

in/init

Getting Initialization parameters(Local variables)from web.xml to servletimport 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 applicationWeb server creates this object when application is deployedWeb server destroys this object when web application is undeployed or reloaded or stopped Useful to gather context parameters or global unic parameters from web.xmlUserful to get information of entire application

Different ways to get access to ServletContext object1. 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

ctxContextServlet

ctx/global

Driveroracle.jdbc.driver.OracleDriver

URLjdbc:oracle:thin:@localhost:1521:xe

usernamesystem

passwordnie123

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 driverClass.forName(driver);//connect with dbConnection con=DriverManager.getConnection(url,user,pass);out.println("Connected With DB using ContextParameters");}catch (Exception e){e.printStackTrace();}}}OUTPUT:Connected With DB using ContextParameters