1 / 32

Java Servlets

Java Servlets. Agenda:. What is a servlet? The Advantages of Servlets Over "Traditional" CGI Servlet Architecture The Servlet Life Cycle Types of Servlets How servlets work? javax.servlet & javax.servlet.http packages. What Is a Servlet?.

Download Presentation

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

  2. Agenda: • What is a servlet? • The Advantages of Servlets Over "Traditional" CGI • Servlet Architecture • The Servlet Life Cycle • Types of Servlets • How servlets work? • javax.servlet & javax.servlet.http packages

  3. What Isa Servlet? • Servlets are server-side Java applications, as opposed to client-side applets or standalone  applications. • While servlets are compatible with many different types of servers, typically they are used in web servers, as a replacement for CGI scripts or Active-Server Pages (ASP).

  4. In generic terms, a servlet is any class that can be invoked and executed on a server, most likely on behalf of a client. Unlike applets, which do their work on the client, servlets do their work on the server • Another way of phrasing what servlets do is "server-side Java." Since servlets are written in Java and are part of the J2EE specification, they have access to all the functionality and cross-platform portability of the Java programming language.

  5. The Advantages of Servlets Over "Traditional" CGI • Efficient • Threads instead of OS processes, one servlet copy,persistence • With servlets, the Java virtual machine stays running and handles each request with a lightweight Java thread, not a heavyweight operating system process. • Servlets, however, remain in memory even after they complete a response, so it is straightforward to store arbitrarily complex data between client requests. • Convenient • Servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such high-level utilities • Powerful • Sharing data, pooling & persistence

  6. The Advantages of Servlets Over "Traditional" CGI ……..contd • Portable • Run on virtually all operatings systems and web servers • Secure • No shell escapes, no buffer overflows • Inexpensive cbt: array bounds checking and other memory protection features are a central part of the Java programming language

  7. Servlets Architecture: • Following diagram shows the position of Servelts in a Web Application.

  8. Servlets Tasks: Servlets perform the following major tasks: • Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. • Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. • Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. • Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. • Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

  9. Servlets must implement the interface javax.servlet.Servlet. There are two main types of servlets:  Generic servlets extend javax.servlet.GenericServlet. Generic servlets are protocol independent, meaning that they contain no inherent support for HTTP or any other transport protocol.  HTTP servlets extend javax.servlet.http.HttpServlet. These servlets have built-in support for the HTTP protocol and are much more useful in an Browser environment Types of Servlets

  10. So basically Generic Servlets are non web based servlets and Http servlets are web based servlets All Servlets must implement a service() method. This method is responsible for handling requests made to the Servlet. For generic Servlets, you simply override the service() method to provide routines for handling requests. HTTP Servlets provide a service method that automatically routes the request to another method in the servlet based on which HTTP transfer method is used, so for HTTP Servlets you would override doPost() to process POST requests, doGet() to process GET requests, and so on. Types of Servlet…contd

  11. How servlets work? • Servlets are created and managed at run time by the Servlet engine, that runs inside the Java server. • The input data on which servlets operate is encapsulated in an object called the request object. A Servlets response to a query is encapsulated in an object called the response object. • Servlets call EJBs to perform business logic functions. Servlets call JSPs to perform page layout functions. • Servlets control user sessions in order to provide some persistence of user information between interactions. • Servlets can be a part of a particular application, or they can reside separately in order to be available to multiple applications. The latter type are said to be members of the generic ("Default") application. • Servlets can be dynamically reloaded while the server is running • Servlets are addressable as URLs. The buttons on your application's pages usually point to servlets. Servlets can also call other servlets. 

  12. Servlets Packages: • Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification. • Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects. • These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1. • Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current compiler.

  13. Interfaces Servlet ServletRequest ServletResponse ServletConfig ServletContext RequestDispatcher SingleThreadModel Classes GenericServlet ServletInputStream ServletOutputStream Exceptions ServletException UnavailableException Package javax.servlet

  14. Interface Summary Interface Summary RequestDispatcher RequestDispatcher Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. Servlet Servlet Defines methods that all servlets must implement. Defines methods that all servlets must implement. ServletConfig ServletConfig A servlet configuration object used by a servlet container used to pass information to a servlet during initialization. A servlet configuration object used by a servlet container used to pass information to a servlet during initialization. ServletContext ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. ServletRequest ServletRequest Defines an object to provide client request information to a servlet. Defines an object to provide client request information to a servlet. ServletResponse ServletResponse Defines an object to assist a servlet in sending a response to the client. Defines an object to assist a servlet in sending a response to the client. SingleThreadModel SingleThreadModel Ensures that servlets handle only one request at a time. Ensures that servlets handle only one request at a time.

  15. Class Summary GenericServlet Defines a generic, protocol-independent servlet. ServletInputStream Provides an input stream for reading binary data from a client request, including an efficient readLine method for reading data one line at a time. ServletOutputStream Provides an output stream for sending binary data to the client. Exception Summary ServletException Defines a general exception a servlet can throw when it encounters difficulty. UnavailableException Defines an exception that a servlet throws to indicate that it is permanently or temporarily unavailable.

  16. Interfaces HttpServletRequest HttpServletResponse HttpSession HttpSessionBindingListener HttpSessionContext SingleThreadModel Classes HttpServlet HttpUtils Cookie HttpSessionBindingEvent Package javax.servlet.http

  17. Interface Summary HttpServletRequest Extends the ServletRequest interface to provide request information for HTTP servlets. HttpServletResponse Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. HttpSession Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. HttpSessionBindingListener Causes an object to be notified when it is bound to or unbound from a session. HttpSessionContext Deprecated.As of Java(tm) Servlet API 2.1 for security reasons, with no replacement. Class Summary Cookie Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. Sent to an object that implements HttpSessionBindingListener when the object is bound to or unbound from the session HttpSessionBindingEvent HttpUtils Provides a collection of methods that are useful in writing HTTP servlets.

  18. ServletContext Interface • ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web application or servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application • ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)

  19. ServletConfig Interface • A servlet configuration object used by a servlet container to pass information to a servlet during initialization. • All of its initialization parameters can ONLY be set in deployment descriptor • The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

  20. ServletContext ServletConfig The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets. ServletConfig has a SESSION SCOPE.. [LOCAL SCOPE......which is mostly used for initialising purpose]. javax.servlet.ServletConfig has page scope • The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application. • ServletContext has a APPLICATION SCOPE .. [GLOBALLY ACCESSIBLE ACROSS THE PAGES]

  21. Difference between ServletConfig and ServletContext • Signature: public interface ServletContextServletContext is implemented by the servlet container for all servletto communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web application is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM. • The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in <context-param> tags in web.xml file. • Example code:<context-param><param-name>globalVariable</param-name><param-value>javapapers.com</param-value></context-param>

  22. Difference between ServletConfig and ServletContext • Signature: public interface ServletConfigServletConfig is implemented by the servlet container to initialize a single servletusing init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class. • Example code:<servlet><servlet-name>ServletConfigTest</servlet-name><servlet-class>com.javapapers.ServletConfigTest</servlet-class><init-param><param-name>topic</param-name><param-value>Difference between ServletConfig and ServletContext</param-value></init-param></servlet>

  23. Steps to Write a Basic Servlet • Import the appropriate packages and classes, including: • import javax.servlet.*;import javax.servlet.http.*;import java.io.*; • Extend javax.servlet.http.HttpServlet. • public class HelloWorldServlet extends HttpServlet{ • Implement a service() method. The main function of a servlet is to accept an HTTP request from a Web Browser, and return an HTTP response. This work is done by your servlet's service() method. The service methods include response objects that you use to create output and request objects used to receive data from the client. • public void service(HttpServlet Request req,HttpServletResponse res) throws IOException{

  24. Steps to Write a Basic Servlet…..contd • Set the content type. • res.setContentType("text/html"); • Obtain a PrintWriter object to use for output. • PrintWriter out = res.getWriter(); • Create some HTML using the PrintWriter object • out.println("<html><head><title>Hello World!</title></head>");out.println("<body><h1>Hello World!</h1></body></html>");}} • Compile the servlet

  25. Program - 1 import javax.servlet.*; import java.io.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest req, ServletResponse res) { try{ PrintWriter output=res.getWriter(); output.println("<html><body bgcolor=blue text=red>"); output.println("<b> HELLO WORLD</b>"); output.println("</body></html>"); }catch(Exception e){} } }

  26. Program - 2 Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests. Sample Code for Hello World: Following is the sample source code structure of a servlet example to write Hello World: // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

  27. // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<html><head><title>Hello World!</title></head>"); out.println("<body><h1>” +message+ “</h1></body></html>"); } public void destroy() { // do nothing. } }

  28. Compiling a Servlet: • Let us put above code of HelloWorld.java file and put this file in C:\ServletDevel (Windows) then you would need to add these directories as well in CLASSPATH. Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows: C:\ServletDevel> javac HelloWorld.java • If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any other library in Hello World program. • This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software Development Kit (JDK). For this command to work properly, you have to include the location of the Java SDK that you are using in the PATH environment variable. • If everything goes fine, above compilation would produce HelloWorld.class file in the same directory.

  29. Servlet Deployment: • By default, a servlet application is located at the path <Tomcat-installation-directory>/webapps/ROOT and the class file would reside in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes. • If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class. • For now, let us copy HelloWorld.class into <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/ Note: Instead of ROOT, you can also create your own directory and create the WEB-INF structure in it and place your program there.

  30. <web-app> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app> Above entries to be created inside web.xml file. There could be various entries in this table already available, but never mind. You are almost done, now let us start tomcat server using <Tomcat-installation-directory>\bin\startup.bat (on windows) and finally type http://localhost:8080/HelloWorld in browser's address box.

  31. If everything goes fine, you would get following result:

  32. THANK YOU……

More Related