Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Chapter 3 servlet & jsp


Published on

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

Chapter 3 servlet & jsp

  1. 1. Servlets
  2. 2. Servlets  Java Servlet is a java object file developed as a component and runs on the server.  Servlets are programs that run on a Web or application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server  Servlets is a component can be invoked from HTML. Note:  Servlets cannot run independently as a main application like the java applet, the servlet does not have main method.
  3. 3. Servlets  Servlet do not display a graphical interface to the user.  A servlet’s work is done at the server and only the results of the servlet’s processing are returned to the client in the form of HTML.  A Servlet is a Java technology-based Web component, managed by a container that generates dynamic content.  Like other Java technology-based components, Servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
  4. 4. Predessor of servlet  In the early days of the web u have to use the Common Gateway interface(CGI) to perform server side processing of forms and interaction with the datadase.  Later microsoft ASP technology enable server side processing using Vbscript, Javascript.
  5. 5. Difference Between Servlet & CGI  The advantages of using servlets are their fast performance and ease of use combined with more power over traditional CGI (Common Gateway Interface).  Traditional CGI scripts written in Java have a number of disadvantages when it comes to performance  When an HTTP request is made, a new process is created for each call of the CGI script. This overhead of process creation can be very system-intensive, especially when the script does relatively fast operations. Thus, process creation will take more time than CGI script execution.  Java servlets solve this, as a servlet is not a separate process. Each request to be handled by a servlet is handled by a separate Java thread within the Web server process, omitting separate process forking (split) by the HTTP domain.
  6. 6. Difference Between Servlet & CGI  Simultaneous CGI request causes the CGI script to be copied and loaded into memory as many times as there are requests.  However, with servlets, there are the same amount of threads as requests, but there will only be one copy of the servlet class created in memory that stays there also between requests.  A servlet can be run by a servlet engine in a restrictive environment, called a sandbox. This is similar to an applet that runs in the sandbox of the Web browser. This makes a restrictive use of potentially harmful servlets possible.
  7. 7. Advantages of Servlets  Platform Independence: Servlets are written entirely in java so these are platform independent. Servlets can run on any Servlet enabled web server.  Performance  Due to interpreted nature of java, programs written in java are slow.  But the java Servlets runs very fast. These are due to the way Servlets run on web server.  For any program initialization takes significant amount of time. But in case of Servlets initialization takes place first time it receives a request and remains in memory till times out or server shut downs.
  8. 8.  Extensibility Java Servlets are developed in java which is robust, well- designed and object oriented language which can be extended or polymorphed into new objects. So the java Servlets take all these advantages and can be extended from existing class to provide the ideal solutions.  4. Safety Java provides very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension.  5. Secure Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.
  9. 9. Life cycle of a servlet • Init () Method • Service () Method • Destroy() method Init () Method:-  During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling the init() method.  The container passes an object implementing the ServletConfig interface via the init() method.  This configuration object allows the servlet to access name- value initialization parameters from the web application.
  10. 10. • Service () Method:- ◦ After initialization, the servlet can service client requests. each request is serviced in its own separate thread. ◦ The Web container calls the service() method of the servlet for every request. ◦ The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. ◦ The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester. • Destroy() method:- ◦ Finally, the Web container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet.
  11. 11. Types of servlets • Generic Servlets: Generic Servlets are protocal independent that is they do not contain any inherent support for any protocal. Generic Servlets handle request by overriding the services() method. • HTTP Servlets: HTTP Servlets are HTTP protocal specific. This makes it very useful in a browser environment. In case of HTTP Servlets, service() method route the request to another method based on which HTTP transfer method is used.
  12. 12. Using Tomcat for Servlet Development  To create servlets, you will need access to a servlet development environment.  Tomcat is an open-source product maintained by the Jakarta Project of the Apache Software Foundation.  It contains the class libraries, documentation, and runtime support that you will need to create and test servlets.
  13. 13. Servlet API  Two packages contain the classes and interfaces that are required to build servlets.  javax.servlet  javax.servlet.http. They constitute the Servlet API.  These packages are not part of the Java core packages. Instead, they are standard extensions provided by Tomcat.  The Servlet API has been in a process of ongoing development and enhancement. The current servlet specification is version 2.4,
  14. 14. Simple Servlet program import*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); } }
  15. 15. public class ServletTemplate extends HttpServlet { Declaring a class Name of the class Subclass the httpservlet class to create a servlet
  16. 16. public void doGet(HttpServletRequest request, HttpServletResponse response) You are overriding the doget method that comes from the httpservlet class The parameter is a httpsevletrequest object that you are naming request The parameter is a httpsevletresponse object that you are naming response
  17. 17. throws ServletException, IOException You are declaring that the doget method can throw two exceptions ServletException, IOException
  18. 18. Executing Servlet Program Setting Class path 1. My computer->Properties->Advance->Environment Variables-> Edit User Variable Variable name: path Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program Filesservlet.jar; Edit System Variable Variable name: CLASSPATH Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program Filesservlet.jar;%.%;
  19. 19. 2. Running the servlet in cmd prompt C:Documents and Settingseec-cs>cd C:>cd C:Program FilesApache Tomcat 4.0webappsexamplesWEB-INFclasses C:Program FilesApache Tomcat 4.0webappsexamplesWEB-INFclasses>javac HelloW C:Program FilesApache Tomcat 4.0webappsexamplesWEB-INFclasses>
  20. 20. 3. Start Tomcat 4. Open IE and type below link  http://localhost:8080/examples/servlet/H elloWorld
  21. 21. javax.servlet Package  The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.  The following table summarizes the core interfaces that are provided in this package.  All servlets must implement this interface or extend a class that implements the interface.
  22. 22. Reading Servlet Parameters  The ServletRequest interface includes methods that allow you to read the names and values of parameters that are included in a client request
  23. 23. javax.servlet.http package Classes
  24. 24. HttpServletRequest Interface  The HttpServletRequest interface enables a servlet to obtain information about a client request.
  25. 25. HttpServletResponse Interface The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.
  26. 26. HttpSession Interface  The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session.
  27. 27. HttpSessionBindingListener Interface  The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session.
  28. 28. Handling HTTP Requests and Responses  Servlets can be used for handling both the GET Requests and the POST Requests.  The HttpServlet class is used for handling HTTP GET / POST Requests as it has some specialized methods that can efficiently handle the HTTP requests.  These methods are: ◦ doGet( ) ◦ doPost( ) ◦ doPut( ) ◦ doDelete( ) ◦ doOptions( ) ◦ doTrace( ) ◦ doHead( )
  29. 29.  An individual developing Servlets for handling HTTP Requests needs to override one of these methods in order to process the request and generate a response. The servlet is invoked dynamically when an end-user submits a form.  If Form method attribute value is GET, then doGet( ) method of servlet will be called, if method=”POST” doPost( ) method of servlet which is mentioned as action will be called.  Ex: <form action=”sampleServlet” method=”GET”>  In above example since method is GET, sampleServlet’s doGet( ) will be called.
  30. 30.  Both doGet( ) and doPost( ) takes two arguments objects of HttpServletRequest and HttpServletResponse classes.  Ex: public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException  public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException  In above example req is an object of HttpServletRequest class which contains the incoming information (information passed by client program).  The res is an object of HttpServletResponse class which contains the outgoing information (response back to client).
  31. 31. Getting request data  The request object of HttpServletRequest class contains the incoming request data sent by client program.  By using the following methods we can get the request parameter values.  Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request.  The parameters are stored as a set of name-value pairs. Multiple parameter values can exist for any given parameter name. The following methods of the ServletRequest interface are available to access parameters: ◦ getParameter ( ) ◦ getParameterNames ( ) ◦ getParameterValues ( )
  32. 32.  getParameter ( ) method is used to access single value, takes name of input parameter as an argument and returns a string object. Ex: String s=req.getParameter(“user”);  getParameterValues ( ) method is used to access multiple value entered by user in a client program, it takes name of input parameter as an argument and returns a array of string object.  Ex: String [ ] lang=req.getParameterValues (“language”);
  33. 33. When we want to access all the parameters of a form, we make use of Enumeration object and its methods as shown below. Ex: Enumeration en; String pname; String pvalue; en = request.getParameterNames(); while (en.hasMoreElements()) { pname = (String) en.nextElement(); pvalue= request.getParameterValues(pname); for(int i=0;i<pvalue.length;i++) { out.println(pvalue[i]); } }
  34. 34. Cookies  Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting the same Web site or domain later.  To send cookies to the client, a servlet would create one or more cookies with the appropriate names and values via new Cookie(name, value).  A Cookie is created by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value. Neither the name nor the value should contain whitespace or any of: [ ] ( ) = , " / ? @ : ;  Ex: Cookie userCookie = new Cookie("user", "uid1234");
  35. 35.  The cookie is added to the Set-Cookie response header by means of the addCookie method of HttpServletResponse.  Cookie userCookie = new Cookie("user", "uid1234");  response.addCookie(userCookie);
  36. 36. The getXXX( ) method can be used to retrieve the attribute XXX of a cookie object, which returns the string value. For example getName( ) used to retrieve the name of a cookie. The setXXX( ) method is used to set the value of XXX attribute of a cookie, which accepts the value as argument which need to be set. Ex: c.setValue(“123”); It sets Value attribute of cookie c as 123.
  37. 37. Servlet-Sessions  There are a number of problems that arise from the fact that HTTP is a "stateless" protocol.  In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions.  This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce.  When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying?
  38. 38.  Servlets provide an outstanding technical solution: the HttpSession API.  “A session is created each time a client requests service from a Java servlet. The servlet processes the request and responds accordingly, after which the session is terminated.”
  39. 39. JSP - Java Server Pages Introduction  JSP is one of the most powerful, easy-to-use, and fundamental tools in a Web-site developer's toolbox.  JSP combines HTML and XML with Java servlet (server application extension) and JavaBeans technologies to create a highly productive environment for developing and deploying reliable, interactive, high-performance platform- independent Web sites.  JSP facilitates the creation of dynamic content on the server.
  40. 40.  It is part of the Java platform's integrated solution for server-side programming, which provides a portable alternative to other server- side technologies, such as CGI.  JSP integrates numerous Java application technologies, such as Java servlet, JavaBeans, JDBC, and Enterprise JavaBeans.  It also separates information presentation from application logic and fosters a reusable component model of programming.
  41. 41. Advantages of JSP over Servlets  Servlet use println statements for printing an HTML document which is usually very difficult to use. JSP has no such tedious task to maintain.  JSP needs no compilation, CLASSPATH setting and packaging.  In a JSP page visual content and logic are seperated, which is not possible in a servlet.  There is automatic deployment of a JSP; recompilation is done automatically when changes are made to JSP pages.  Usually with JSP, Java Beans and custom tags web application is simplified.
  42. 42. Fundamental JSP Tags  JSP tags are an important syntax element of Java Server Pages which start with "<%" and end with "%>" just like HTML tags. JSP tags normally have a "start tag", a "tag body" and an "end tag". JSP tags can either be predefined tags or loaded from an external tag library.  Fundamental tags used in Java Server Pages are classified into the following categories:-  Declaration tag  Expression tag  Directive tag  Scriptlet tag  Comments
  43. 43. Declaration tag  The declaration tag is used within a Java Server page to declare a variable or method that can be referenced by other declarations, scriptlets, or expressions in a java server page.  A declaration tag does not generate any output on its own and is usually used in association with Expression or Scriplet Tags.  Declaration tag starts with "<%!" and ends with "%>" surrounding the declaration. Syntax :- <%! Declaration %> Example: <%! int var = 1; %> <%! int x, y ; %>
  44. 44. Expression tag  An expression tag is used within a Java Server page to evaluate a java expression at request time.  The expression enclosed between "<%=" and "%>" tag elements is first converted into a string and sent inline to the output stream of the response. Syntax :- <%= expression %> Example: <%= new java.util.Date() %>
  45. 45. Directive tag  Directive tag is used within a Java Server page to specify directives to the application server .  The directives are special messages which may use name-value pair attributes in the form attr="value". Syntax :- <%@directive attribute="value" %>
  46. 46. Where directive may be: 1. page: page is used to provide the information about it. Example: <%@page language="java" %> 2. include: include is used to include a file in the JSP page. Example: <%@ include file="/header.jsp" %> 3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags). Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
  47. 47. Scriptlet tag  A Scriptlet tag is used within a Java Server page to execute a java source code scriplet which is enclosed between "<%" and "%>" tag elements.  The output of the java source code scriplet specified within the Scriptlet tag is executed at the server end and is inserted in sequence with rest of the web document for the client to access through web browser. Syntax :- <% java code %>
  48. 48. Comments  Comments tag is used within a Java Server page for documentation of Java server page code.  Comments surrounded with "<%/*" and "*/%" tag elements are not processed by JSP engine and therefore do not appear on the client side web document but can be viewed through the web browser’s "view source" option.  Syntax :- <%-- comment -- %>
  49. 49. Request String  The browser generates a user request string whenever the submit is selected.  The User request string consists of the URL and the query string. http://localhost:8080/examples/test/reg.jsp?fname=“bob”&lna me=“smith”  The getParameter(name) is the method used to parse a value of a specified field. <% string firstname = request.getParameter(fname) string lastname = request.getParameter(lname) %>
  50. 50. User Sessions  A JSP program must be able to track a session as a client moves between HTML pages and JSP programs. There are three commonly used methods to track a session. 1. Using Hidden Field 2. Using Cookies 3. Using JavaBean
  51. 51. Cookies  Cookies is a small piece of information created by a JSP program that is stored on the Client’s hard disk by the browser.  You can create and read a cookie by using methods of the cookie class and the response object. Example: how to create a cookie <HTML> <HEAD> <TITLE>JSP PROGRAMMING </TITLE> </HEAD> <BODY> <%! String MyCookieName = “userId”; String MyCookieValue = “Jk12345”; Response.addCookie(new Cookie(MyCookieName, MyCookieValue)); %> </BODY> </HTML>
  52. 52. HOW TO READ A COOKIE <HTML> <HEAD> <TITLE> JSP Programming</TITLE> </HEAD> <BODY> <%! String MyCookieName=“userID”; String MyCookieValue; String Cname,Cvalue; int found=0; Cookie[] cookies=request.getCookies(); for(int i=0;i<cookies.length;i++){ CName=cookies[i].getName(); CValue= cookie[i].getValue(); if(MyCookieName.equals(cookieNames[i])){ found=1; MyCookieValue=CookieValue; } } if(found==1){ %> <p> Cookie name =<% MYCookieName%></p> <p> Cookie Value=<% MyCookieValue %></p> <&}> </BODY> </HTML>
  53. 53. Session Objects  A JSP database system is able to share information among JSP programs within a session by using a session object.  Each time a session is created, a unique ID is assigned to the session and stored as a cookie