1 / 38

Servlets

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

Download Presentation

Servlets

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Servlets By B. VenkateswarluM.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 • init()-The servlet is initialized by calling the init () method • service()-The servlet calls service() method to process a client's request • destroy()-The servlet is terminated by calling the destroy() method Finally, servlet is garbage collected by the garbage collector of the JVM

  5. ServletLifecycle 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

  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. 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 • Development of a Web application ServletApp ServletApp WEB-INF

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

  11. Create a Servlet Class as follows 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("<html>"); out.println("<head>"); out.println("<title>WelcomeServlet</title>"); out.println("</head>"); out.println("<body bgcolor="pink">"); out.println("<h1>HelloWorld</h1>"); out.println("</body>"); out.println("</html>"); out.close( ); } } • Step4:

  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 <web-app> <servlet> <servlet-name>some</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>some</servlet-name> <url-patteren>/firstservlet</url-patteren> </servlet-mapping> </web-app> OUTPUT: Hello World

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

  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 http://localhost:8080/ServletApp/firstservlet

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

  19. web.xml <web-app> <servlet> <servlet-name>two</servlet-name> <servlet-class>DateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>two</servlet-name> <url-patteren>/second</url-patteren> </servlet-mapping> </web-app> 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. Servlet Development void init(ServletConfig) void destroy() void service(ServletRequest, ServletResponse) ServletConfiggetServletConfig() String getServletInfo() javax.servlet.Servlet implements javax.servlet.GenericServlet init(ServletConfig) init() ……. Does not implement service() method (Abstract) extends doxxx(HttpServletRequest, HttpServletResponse) protected service( HttpServletRequest, HttpServletResponse) public service(ServletRequest, ServletResponse) javax.servlet.http.HttpServlet (Abstract)

  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 • <html> • <head> • <title>Homepage</title> • </head> • <body bgcolor="skyblue"> • <form name="myform" method=get action="/first"> • FirstName<input type=text name=fname><br> • LastName<input type=text name=lname><br> • Age<input type=text name=age><br> • <input type=submit value=verify> • <input type=reset value=cancel> • </form> • </body> • </html> First Name Venkat Bombotula Last Name Age 27 Verify Cancel

  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("<html>"); • out.println("<body>"); • String fn=request.getParameter("fname"); • String ln=request.getParameter("lname"); • intag=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("</body>"); • out.println("</html>"); • out.close(); • } • }

  27. web.xml • <web-app> • <servlet> • <servlet-name>some</servlet-name> • <servlet-class>VoteServlet</servlet-class> • </servlet> • <servlet-mapping> • <servlet-name>some</servlet-name> • <url-patteren>/first</url-patteren> • </servlet-mapping> • <welcome-file-list> • <welcome-file>index.html</welcome-file> • </welcome-file-list> • </web-app>

  28. Output: Mr/Ms VenkatBombotula 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 Servletavailabe in web.xml • Userful to get information of a perticularServlet

  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(HttpServletRequestrequest,HttpServletResponse response) • { • ServletConfig sc=getServletConfig(); • ---- • //Use sc object here • - --- • } • }

  31. Getting Initialization parameters(Local variables)from web.xml to servlet • <web-app> • <servlet> • <servlet-name>in</servlet-name> • <servlet-class>InitServlet</servlet-class> • <init-param> • <param-name>SNo</param-name> • <param-value>09A11A1227</param-value> • </init-param> • <init-param> • <param-name>SName</param-name> • <param-value>Sai Ram</param-value> • </init-param> • </servlet> • <servlet-mapping> • <servlet-name>in</servlet-name> • <url-pattern>/init</url-pattern> • </servlet-mapping> • </web-app>

  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(HttpServletRequestreq,HttpServletResponseresp) • 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+"<br>"); • } • } 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(HttpServletRequestrequest,HttpServletResponse response • { • ---- • ServletConfig sc=getServletConfig(); • ServletContext cg=sc.getServletContext(); • //Use cg object here • ---- • } • } • 2. public class TestServlet extends HttpServlet • { • public void service(HttpServletRequestrequest,HttpServletResponse response) • { • ServletContext cg=getServletContext(); • ---- • //Use cg object here • - --- • } • }

  35. Getting Context-parameters(Global variables)from web.xml to servlet • <web-app> • <servlet> • <servlet-name>ctx</servlet-name> • <servlet-class>ContextServlet</servlet-class> • </servlet> • <servlet-mapping> • <servlet-name>ctx</servlet-name> • <url-pattern>/global</url-pattern> • </servlet-mapping> • <context-param> • <param-name>Driver</param-name> • <param-value>oracle.jdbc.driver.OracleDriver</param-value> • </context-param> • <context-param> • <param-name>URL</param-name> • <param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value> • </context-param>

  36. <context-param> • <param-name>username</param-name> • <param-value>system</param-value> • </context-param> • <context-param> • <param-name>password</param-name> • <param-value>nie123</param-value> • </context-param> • </web-app>

  37. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class ContextServlet extends HttpServlet { public void service(HttpServletRequestreq,HttpServletResponseresp) 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

More Related