SERVLET (1).pdf
Document Details
Uploaded by ClearerHouston
Punyashlok Ahilyadevi Holkar Solapur University
Full Transcript
ADVANCED JAVA UNIT 2 SERVLET A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Servlet are small program that execute on the...
ADVANCED JAVA UNIT 2 SERVLET A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Servlet are small program that execute on the server side of a web connection. They are java program that runs inside a java capable HTTP server. Advantages of servlet over CGL When comparing Servlets with CGI (Common Gateway Interface), it’s important to recognize that both technologies serve the purpose of enabling dynamic content on web pages by allowing web servers to interact with backend applications. However, Servlets offer several advantages over CGI that have made them a preferred choice in many scenarios: 1.Performance and Scalability: - Instance Reuse: Servlets are loaded into memory once and persist across multiple requests. Unlike CGI scripts, which spawn a new process for each request, servlets handle multiple requests using a single instance. This reduces memory consumption and CPU time, significantly enhancing performance. - Multithreading: Servlets can handle multiple requests concurrently using Java threads, leading to better utilization of system resources and improved scalability. 2. Portability: - Servlets are written in Java, which is platform-independent. This allows servlets to run on any operating system that has a compatible Java Virtual Machine (JVM), making the applications portable across various server platforms. 3. Integration with Java Ecosystem: 1 - Being a part of the Java ecosystem, servlets can easily integrate with other Java technologies such as JDBC for database access, JNDI for directory services, and various Java EE (Enterprise Edition) components like JSP (JavaServer Pages), EJB (Enterprise JavaBeans), and JavaMail for enterprise-level services. - This integration is seamless and leverages the robust, object-oriented capabilities of Java, enhancing the functionality and maintainability of web applications. 4. Robust API: - The Servlet API provides a rich set of functionalities to manage sessions, cookies, and context data, and to parse different types of requests including multipart data. CGI, by contrast, requires the developer to handle these aspects manually, which can be error- prone and cumbersome. 5. Security: - Servlets benefit from Java’s built-in security features, including the Java security manager and access to robust third-party security libraries. This makes servlet-based applications more secure compared to traditional CGI scripts, which might be written in less secure languages or depend on external libraries for security features. 6. Efficient Resource Management: - Servlets allow for efficient management of resources such as database connections, which can be pooled and reused for different requests. In CGI, each script execution typically opens and closes database connections independently, which is less efficient, particularly under high load. 7. Community and Support:- - Java and Servlets have a large developer community and extensive documentation, which facilitates troubleshooting and development. Also, many commercial and open- 2 source tools and servers support servlets, providing more options and resources for developers. Features of servlet Servlets are Java programs that run on a server and handle client requests, typically in a web application. Here are some key features of servlets: 1. Platform Independence: Servlets are written in Java, which means they can run on any platform with a Java Virtual Machine (JVM). 2. Server-Side Processing: They handle requests from web clients (browsers) and generate responses, typically in the form of HTML or other content types. 3. Integration with Web Servers: Servlets operate within a web server or servlet container (like Apache Tomcat), which provides the necessary environment for their execution. 4. Request and Response Handling: Servlets handle HTTP requests and responses using methods like `doGet()`, `doPost()`, `doPut()`, `doDelete()`, etc. 5. Session Management: They can manage sessions using `HttpSession`, which allows for tracking user interactions over multiple requests. 6. Concurrency: Servlets support multiple simultaneous requests and can handle them concurrently using threads. 7. Lifecycle Methods: Servlets have lifecycle methods such as `init()`, `service()`, and `destroy()` that manage their initialization, request processing, and cleanup. 8. Support for Cookies and URL Rewriting: They can use cookies or URL rewriting to maintain state across requests. 3 9. Request Dispatching: Servlets can forward requests to other resources (like JSPs or other servlets) or include responses from other resources. 10. Configurable via Deployment Descriptor: Servlets can be configured using the `web.xml` deployment descriptor file, where you can define servlet mappings and initialization parameters. These features make servlets a powerful tool for developing web applications in Java. Introducing servlet API :- The Servlet API is a set of Java interfaces and classes provided by the Java Servlet specification. It is part of the Java EE (Enterprise Edition) platform and enables developers to create server-side components for web applications. Here’s an introduction to the key components of the Servlet API: 1. `javax.servlet` Package: - ServletInterface: The core interface that all servlets implement. It defines essential methods like `init()`, `service()`, and `destroy()` that manage the servlet lifecycle. - GenericServletClass: A convenience class that implements the `Servlet` interface and provides default implementations for methods, which can be extended by developers. - ServletRequest Interface: Represents the request from a client and provides methods to access request parameters, attributes, and other details. - ServletResponse Interface: Represents the response sent to the client and provides methods to send data back to the client, such as setting content type and writing data. 4 - ServletConfig Interface: Provides configuration information for a servlet, such as initialization parameters. - ServletContextInterface: Provides a way to communicate with the web container and other servlets in the same application, allowing access to application-wide parameters and resources. 2. `javax.servlet.http` Package: - HttpServletClass: A subclass of `Generic Servlet` that simplifies handling HTTP requests by providing methods like `doGet()`, `doPost()`, `doPut()`, `doDelete()`, etc. It is the most commonly used class for HTTP-based web applications. - HttpServletRequestInterface: Extends `ServletRequest` and provides additional methods specific to HTTP requests, such as retrieving HTTP headers, query parameters, and session information. - HttpServletResponseInterface: Extends `ServletResponse` and includes methods for manipulating HTTP-specific response headers and content. -HttpSession Interface: Manages session data for a particular user across multiple requests, allowing storage of user-specific information. 5 Servlet Lifecycle 1. Servlet class is loaded. 2. Servlet instance is created. 3. init method is invoked. 4. service method is invoked. 5. destroy method is invoked. 6 1) Servlet class is loaded The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. 2) Servlet instance is created The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init method is invoked The web container calls the init method only once after creating the servlet instance. The init me 7 javax.servlet.Servlet interface. Syntax of the init method is given below: 1. public void init(ServletConfig config) throws ServletException 4) service method is invoked The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below: 1. public void service(ServletRequest request, ServletResponse response) 2. throws ServletException, IOException 5) destroy method is invoked The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below: 1. public void destroy() Working with Generic servlet and Http servlet When working with a generic server and an HTTP servlet, you’re typically dealing with Java Servlets which are server-side components used to handle requests and responses in web applications. 8 1. **Setup Your Development Environment:** - **JDK (Java Development Kit):** Ensure you have the JDK installed. - **IDE (Integrated Development Environment):** Use an IDE like IntelliJ IDEA, Eclipse, or NetBeans for Java development. 2. **Create a Dynamic Web Project:** - In your IDE, create a new Dynamic Web Project. This will include directories for Java source files and web resources. 3. **Create a Servlet Class:** - A Servlet is a Java class that handles HTTP requests and responses. It extends `HttpServlet` and overrides methods like `doGet()` or `doPost()`. 4. **Configure the Servlet:** - **Web.xml:** Traditionally, you configure your servlet in the `web.xml` file under `WEB-INF`. 5. **Deploy and Test:** - **Server:** Deploy your web application to a server like Apache Tomcat. This can be done through your IDE or manually by placing the WAR file in the server’s `webapps` directory. - **Testing:** Access your servlet via a web browser or tools like `curl` by navigating to `http://localhost:8080/yourapp/myservlet`. 6. **Handling Requests and Responses:** - **Request Handling:** Use methods of `HttpServletRequest` to retrieve parameters, headers, and other request information. 9 - **Response Handling:** Use `HttpServletResponse` to set response headers, status codes, and write the response content. Difference Between Generic servlet and Http servlet 10 Sr.No Generic servlet Http servlet 1 All methods are concrete except All methods are concrete (non-abstract). service() method. service() method service() is non-abstract method is abstract. 2 service() should be overridden service() method need not be overridden. being abstract in super interface. 3 Extends Object and implements Extends GenericServlet and implements interfaces Servlet, ServletConfig interface Serializable and Serializable. 4 It is a must to use service() method Being service() is non-abstract, it can be as it is a callback method replaced by doGet() or doPost() methods. 5 Direct subclass of Servet interface. Direct subclass of GenericServlet. 6 Defined javax.servlet package. Defined javax.servlet.http package. 7. All the classes and interfaces All the classes and interfaces present in belonging to javax.servlet package javax.servlet.http package are protocol are protocol independent. dependent (specific to HTTP). 8 Not used now-a-days. Used always. 11 Request dispatcher interface The `RequestDispatcher` interface in Java Servlets is used to forward a request from a servlet to another resource, such as another servlet, a JSP (JavaServer Pages), or an HTML file. It allows you to include the content of another resource in the response or to forward the request to another resource for further processing. Here’s an overview of how to use the `RequestDispatcher` interface: 1.forward(ServletRequest request, ServletResponse response) - Forwards the request from the servlet to another resource. - The `response` object passed to `forward` is the same one that will be used by the target resource. RequestDispatcher dispatcher = request.getRequestDispatcher(“/targetResource”); Dispatcher.forward(request, response); 2. include(ServletRequest request, ServletResponse response) - Includes the content of another resource in the response. - The response from the included resource is merged with the current response, which allows for the inclusion of HTML content, JSPs, etc. RequestDispatcher dispatcher = request.getRequestDispatcher(“/includeResource”); Dispatcher.include(request, response); 12 Use of request dispatcher in java In Java, a RequestDispatcher is an interface used in servlets to forward a request from one resource (like a servlet, JSP, or HTML file) to another resource within the same server. It provides a way to encapsulate and manage the handling of requests in a web application. 1.Forwarding a Request: To forward a request from one servlet to another resource, use the forward method. This method transfers control from the servlet to another resource, and the response is generated by the forwarded resource. For example: java RequestDispatcher dispatcher = request.getRequestDispatcher("targetServlet"); dispatcher.forward(request, response); 2.Including Content: To include content from another resource (e.g., a JSP file) in the current response, use the include method. This method allows a servlet or JSP to include the output of another resource. For example: java RequestDispatcher dispatcher = request.getRequestDispatcher("includedPage.jsp"); dispatcher.include(request, response); 13 Session in servlet In Java Servlets, a session is a way to maintain state and data across multiple requests from the same client. This is essential for web applications where you need to preserve user-specific information between interactions with the server. Here’s how you can work with sessions in servlets: 1. Creating and Accessing a Session When a client first interacts with a servlet, you can create or access a session using the HttpSession object, which is obtained from the HttpServletRequest: java HttpSession session = request.getSession(); // Creates a new session if one does not exist To access an existing session without creating a new one, use: java HttpSession session = request.getSession(false); // Returns null if no session exists 2. Storing and Retrieving Attributes You can store data in a session using attributes, which are key-value pairs: java // Storing data in the session 14 session.setAttribute("username", "JohnDoe"); // Retrieving data from the session String username = (String) session.getAttribute("username"); 3. Invalidating a Session To invalidate a session and remove all its attributes: java session.invalidate(); This is typically done during user logout to clear any user-specific data. 4. Session Configuration Sessions can be configured in the web application’s deployment descriptor (web.xml) or programmatically: - *Timeout*: Set session timeout (in minutes) to control how long a session should be kept active. This can be done in web.xml: xml 30 - *Programmatic Configuration*: Set timeout programmatically: java session.setMaxInactiveInterval(30 * 60); // Timeout in second 5. Session Tracking 15 Sessions are typically tracked using cookies, but you can also use URL rewriting if cookies are disabled. The servlet container automatically handles session tracking, but you can manually manage it if needed. Example Servlet Here’s a simple example demonstrating session usage: java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/sessionExample") public class SessionExampleServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Set an attribute in the session session.setAttribute("user", "Alice"); // Retrieve the attribute 16 String user = (String) session.getAttribute("user"); response.setContentType("text/html"); response.getWriter().println("Hello, " + user); } } Cookies A cookie is a small piece of data stored on the client-side which servers use when communicating with client small files of information that a web server generates and sends to a web browser.They’re used to identify a client when sending a subsequent request. They can also be used for passing some data from one servlet to another. Types of cookies There are 2 types of cookies in servlets. 1.Non-persistent cookie 2.Persistent cookie 1.Non-persistent cookie It is valid for single session only. It is removed each time when user closes the browser. 2.Persistent cookie 17 It is valid for multiple session. It is not removed each time when user closes the browser. It is removed only if user logout or signout. Advantages of cookies Simplest technique of maintaining the state. 1. Cookies are maintained at client side. 2. Occupies less memory, do not require any server resources and are stored on the user's computer so no extra burden on server. 3. We can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client’s computer (persistent cookies). 4. Cookies persist a much longer period of time than Session state. Disadvantages of cookies 1. It will not work if cookie is disabled from the browser. 2. Only textual information can be set in Cookie object. 3. Several limitations exist on the size of the cookie text(4kb in general), number of cookies(20 per site in general), etc. 4. User has the option of disabling cookies on his computer from browser’s setting. 5. Cookies will not work if the security level is set to high in the browser. 6. Users can delete a cookies. 7. Users browser can refuse cookies,so your code has to anticipate that possibility. Use of Cookies Method required for using cookies:- 18 public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser. Hidden form filed In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user. In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser. Let's see the code to store value in hidden field. 19 Real application of hidden form field It is widely used in comment form of a website. In such case, we store page id or page name in the hidden field so that each page can be uniquely identified. Advantage of Hidden Form Field 1. It will always work whether cookie is disabled or not. 2. It can be used for anonymous session tracking. 3. All the information is stored in client browser, so it increase the security. Disadvantage of Hidden Form Field: 1. It is maintained at server side. 2. Extra form submission is required on each pages. 3. Only textual information can be used. URL Rewriting 1. URL Rewriting 2. Advantage of URL Rewriting 3. Disadvantage of URL Rewriting In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format: 20 url?name1=value1&name2=value2&?? A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value. Advantage of URL Rewriting 1. It will always work whether cookie is disabled or not (browser independent). 2. Extra form submission is not required on each pages. Disadvantage of URL Rewriting 1. It will work only with links. 2. It can be send only textual information. Using URL Rewriting In this example, we are maintaning the state of the user using link. For this purpose, we are appending the name of the user in the query string and getting the value from the query string in another page. index.html 1. 2. Name: 3. 4. 21 HttpSession In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of HttpSession can be used to perform two tasks: 1. bind objects 2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time. 22 How to get the HttpSession object ? The HttpServletRequest interface provides two methods to get the object of HttpSession: 1. public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one. 2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. Commonly used methods of HttpSession interface 1. public String getId():Returns a string containing the unique identifier value. 2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. 3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. 4. public void invalidate():Invalidates this session then unbinds any objects bound to it. 23 ADVANTAGES AND DISADVANTAGESOF HTTPSESSION Here are the advantages and disadvantages of HttpSession in Advanced Java: Advantages: 1. State Management: HttpSession allows you to store and manage user-specific data across multiple requests, making it easy to maintain session state. 2. Security: HttpSession provides a secure way to store sensitive data, as it is stored on the server-side and not exposed to the client. 3. Flexibility: HttpSession can store any type of object, making it a flexible solution for various use cases. 4. Easy to Implement: HttpSession is easy to implement and use, with a simple API for storing and retrieving data. Disadvantages: 24 1. Server Resource Intensive: HttpSession consumes server resources (memory and CPU), which can lead to performance issues if not managed properly. 2. Scalability Issues: HttpSession can become a bottleneck when scaling applications, as session data needs to be replicated across multiple servers. 3. Session Expiration: HttpSession data can expire, leading to loss of user data if not handled properly. 4. Not Suitable for Large Data: HttpSession is not suitable for storing large amounts of data, as it can lead to performance issues and increased memory usage. 5. Not Shared Across Clusters: HttpSession data is not shared across clusters, making it difficult to use in load-balanced or distributed environments. 25