0% found this document useful (0 votes)
0 views

wt-unit5

asdjfgh

Uploaded by

g731046
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

wt-unit5

asdjfgh

Uploaded by

g731046
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Web Technology (BCS502)

Unit 5 2024-25
B.TECH.(CSIT) SEMESTER -V
1: Servlets: Servlet Overview and Architecture, Interface Servlet and the Servlet Life Cycle

2. Servlets handling HTTP get Requests, Handling HTTP post Requests, Redirecting Requests to Other

Resources, Session Tracking, Cookies, Session Tracking with Http Session

3. Java Server Pages (JSP): Introduction, Java Server Pages Overview, A First Java Server Page
Example, Implicit Objects, Scripting, Standard Actions, Directives, Custom Tag Libraries

Faculty
Dr. Aadarsh Malviya
(Associate Professor Department of CSE)

Dronacharya Group of Institutions


Plot No. 27, Knowledge Park-3, Greater Noida, Uttar Pradesh 201308

Affiliated to

Dr. A P J Abdul Kalam Technical University


Lucknow, Uttar Pradesh 226031
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

1. Servlets: Servlet Overview and Architecture, Interface Servlet and the Servlet Life Cycle
Servlets are a key component in Java web development, acting as server-side programs designed to handle client
requests, process them, and respond dynamically. They are part of the Java EE (Enterprise Edition) platform,
providing an efficient way to develop dynamic web applications.
1. Servlet Overview and Architecture
Overview:
 A servlet is a Java class used to extend the capabilities of servers that host applications accessed by web
clients. Servlets can respond to any type of requests, but they are commonly used to handle HTTP requests
in web applications.
 They run on a servlet container (like Apache Tomcat or Jetty) within a web server or an application server.
The container manages the lifecycle, security, and resource management of servlets.
Architecture:
 Servlets follow a request-response model, typically for HTTP requests and responses. They integrate with
other Java technologies (like JSP and EJB) to create a multi-tiered, scalable application.
 The Servlet Container manages servlet instances, handles client requests, ensures proper resource
allocation, and provides essential services (e.g., multithreading, concurrency handling, request/response
management, and session management).
2. Interface Servlet and the Servlet Life Cycle
Interface Servlet:
 The javax.servlet.Servlet interface is the core interface in the servlet API. Every servlet must implement
this interface (either directly or through the HttpServlet class).
 This interface defines five essential methods:
o init(ServletConfig config): Called once when the servlet is first loaded into memory. Used for
initializing resources or configuration needed by the servlet.
o service(ServletRequest request, ServletResponse response): Called each time the server receives a
request for this servlet. This method handles the client request and generates a response.
o destroy(): Called when the servlet is about to be removed from memory, allowing it to release
resources.
o getServletConfig(): Returns configuration details for this servlet, mainly useful within the init
method.
o getServletInfo(): Returns information about the servlet, such as author, version, or other details.
Servlet Life Cycle:
The servlet lifecycle is defined by three main stages:
1. Initialization (init method):
o When a servlet is first requested, it is loaded into memory, and the container calls the init() method
once to initialize the servlet.
o Any resources or configurations needed for processing requests are set up here.
2. Request Handling (service method):
o For each client request, the servlet container calls the service() method of the servlet.
o service() identifies the type of request (like GET, POST, PUT, DELETE in HttpServlet) and
delegates to corresponding methods (doGet(), doPost(), etc., in HttpServlet subclasses).
o This is the main method where business logic is executed, and responses are generated and sent
back to the client.
3. Termination (destroy method):
o When a servlet is no longer needed or the server is shutting down, the container calls the destroy()
method.
o In destroy(), any resources such as database connections or open files are released to prevent
memory leaks.
Example Servlet Life Cycle Flow:
1. Servlet class is loaded and instantiated.
2. init() method is invoked to initialize the servlet.

1
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

3. service() method is called for each client request.


4. destroy() method is called when the servlet is removed from memory.
This lifecycle provides an efficient way to handle multiple requests while sharing resources across them, as the
service() method is called for each request without creating new servlet instances.

2. Servlets handling HTTP get Requests, Handling HTTP post Requests, Redirecting Requests to Other
Resources, Session Tracking, Cookies, Session Tracking with Http Session

Servlets are widely used in Java web applications for handling HTTP requests, managing session information, and
ensuring secure communication between clients and servers. Here’s a detailed look at how servlets handle GET
and POST requests, redirect requests, and manage session tracking using cookies and the HttpSession API.
1. Handling HTTP GET Requests
HTTP GET requests are typically used for retrieving information from the server without modifying any data. In
servlets, GET requests are handled by overriding the doGet() method in the HttpServlet class.
Example:
java
Copy code
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<h1>Handling GET Request</h1>");

String name = request.getParameter("name");


response.getWriter().println("Hello, " + name + "!");
}
}
In this example, the doGet() method:
 Retrieves a query parameter (e.g., name).
 Generates an HTML response for the client.
To trigger a GET request, clients usually use a URL with parameters (e.g.,
https://example.com/getServlet?name=John).
2. Handling HTTP POST Requests
HTTP POST requests are used to send data to the server, often for processing or storing. In servlets, POST
requests are handled by overriding the doPost() method in the HttpServlet class.
Example:
java
Copy code
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PostServlet extends HttpServlet {

2
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");

String username = request.getParameter("username");


String password = request.getParameter("password");

response.getWriter().println("<h1>Handling POST Request</h1>");


response.getWriter().println("Username: " + username + "<br>");
response.getWriter().println("Password: " + password);
}
}
In this example, the doPost() method processes form data (e.g., username and password) sent in the request body,
not as URL parameters.
3. Redirecting Requests to Other Resources
Servlets can redirect requests to other resources, either on the same server or on a different server. This can be
done using sendRedirect() in the HttpServletResponse object or using RequestDispatcher for internal forwarding.
Using sendRedirect():
java
Copy code
response.sendRedirect("https://example.com/otherPage");
This method redirects the client to a different URL, typically causing a new GET request to the target resource.
Using RequestDispatcher:
java
Copy code
RequestDispatcher dispatcher = request.getRequestDispatcher("/otherServlet");
dispatcher.forward(request, response);
The RequestDispatcher approach forwards the request internally, so the URL in the client’s browser does not
change, and the request attributes are retained.
4. Session Tracking
HTTP is a stateless protocol, so session tracking is essential to maintain user-specific data across multiple
requests. Servlet API offers several methods for tracking sessions:
a. Cookies
Cookies are small pieces of data stored on the client’s browser, often used to maintain session information. The
servlet can send cookies to the client using the HttpServletResponse object.
Example:
java
Copy code
import javax.servlet.http.Cookie;

Cookie userCookie = new Cookie("username", "JohnDoe");


userCookie.setMaxAge(60 * 60); // Sets cookie to expire in 1 hour
response.addCookie(userCookie);
To read cookies, the servlet uses the getCookies() method on HttpServletRequest:
java
Copy code
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
String userName = cookie.getValue();
response.getWriter().println("Welcome back, " + userName);

3
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

}
}
b. Session Tracking with HttpSession
HttpSession provides a straightforward way to store session information on the server. Each client has a unique
session ID associated with it.
Example:
java
Copy code
import javax.servlet.http.HttpSession;

// Creating a session or retrieving the existing one


HttpSession session = request.getSession();
session.setAttribute("user", "JohnDoe");

// Retrieving session attributes


String user = (String) session.getAttribute("user");
response.getWriter().println("Welcome, " + user);

// Invalidating the session


session.invalidate();
 Creating a Session: getSession() either creates a new session or retrieves the existing one.
 Setting Attributes: setAttribute() stores data that persists across multiple requests from the same client.
 Invalidating the Session: invalidate() can be called to end a session and clear any stored data.
Session Timeout: The session timeout can be configured in the web.xml or programmatically using
session.setMaxInactiveInterval().
Summary of Key Concepts:
 GET requests retrieve data, while POST requests send data.
 Redirection can be done with sendRedirect() or RequestDispatcher.
 Session tracking uses cookies and HttpSession to maintain user-specific data across requests.
These servlet features are essential for creating interactive, user-focused web applications where data continuity
and user management are crucial.

Java Server Pages (JSP): Introduction, Java Server Pages Overview, A First Java Server Page Example, Implicit
Objects, Scripting, Standard Actions, Directives, Custom Tag Libraries
JavaServer Pages (JSP) are a technology in Java used for developing dynamic web content. They allow
embedding Java code directly into HTML pages, making it easier to develop web applications with a mixture of
static and dynamic content. JSP pages are compiled into servlets by the server and managed within a servlet
container like Tomcat.
1. Introduction to JavaServer Pages (JSP)
 JSPs simplify web development by separating the business logic (in Java classes) from the presentation
layer (in JSP files).
 They are designed to be more accessible to web designers by allowing HTML and Java code to be
intermingled.
 JSP pages have a .jsp file extension and are translated by the server into servlets before execution.
2. JavaServer Pages Overview
 JSP pages work in conjunction with servlets and provide a more readable way of generating dynamic
content.
 JSPs use various tags and expressions that allow Java code, expressions, and HTML to coexist.
 They support the Model-View-Controller (MVC) architecture by allowing JSP to act as the "view," while
servlets and other Java classes manage the business logic (the "controller" and "model").
3. A First Java Server Page Example

4
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

Here's a simple JSP example that outputs a personalized greeting:


jsp
Copy code
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>First JSP Example</title>
</head>
<body>
<h1>Welcome to JavaServer Pages!</h1>
<%
String name = request.getParameter("name");
if (name != null) {
out.println("Hello, " + name + "!");
} else {
out.println("Hello, Guest!");
}
%>
</body>
</html>
In this example:
 <%@ page ... %> is a directive setting the page properties.
 <% ... %> encloses Java code embedded within the HTML, such as retrieving and displaying a name
parameter from the request.
4. Implicit Objects in JSP
JSP provides several implicit objects that are available without needing to declare or create them explicitly:
 request: Represents the HttpServletRequest object, which contains client request information.
 response: Represents the HttpServletResponse object, used to send responses to the client.
 session: Represents the HttpSession object for managing session data.
 application: Represents the ServletContext, which provides information about the application
environment.
 out: An instance of JspWriter used to send output to the client.
 config: Represents the servlet configuration, useful for accessing initialization parameters.
 pageContext: Provides access to various page-level information.
 page: Refers to the current instance of the JSP page itself.
 exception: Represents the Throwable object, available only in error pages.
5. Scripting in JSP
JSP supports different scripting elements to embed Java code:
 Scriptlets (<% ... %>): Allows Java code to be embedded within the JSP. This is executed each time the
page is requested.
jsp
Copy code
<% int count = 10; %>
 Expressions (<%= ... %>): Outputs the result of a Java expression to the client. Expressions are evaluated
and written to the output stream.
jsp
Copy code
<%= "The count is: " + count %>
 Declarations (<%! ... %>): Declares variables or methods at the class level (outside the _jspService
method generated by the JSP engine).

5
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

jsp
Copy code
<%! int myVariable = 5; %>
6. Standard Actions in JSP
JSP provides standard actions to control the behavior of the page and perform operations such as including other
resources or forwarding requests:
 <jsp:include page="..."/>: Includes content from another resource at runtime.
 <jsp:forward page="..."/>: Forwards the request to another page or servlet.
 <jsp:param name="..." value="..."/>: Used within <jsp:include> or <jsp:forward> to pass parameters.
 <jsp:useBean id="..." class="..." />: Instantiates or locates a JavaBean.
 <jsp:setProperty ... />: Sets properties on a JavaBean.
 <jsp:getProperty ... />: Retrieves properties from a JavaBean.
7. Directives in JSP
Directives provide global settings for a JSP page and control how the JSP is processed:
 Page Directive (<%@ page ... %>): Sets page-level attributes, such as contentType, language, and
errorPage.
jsp
Copy code
<%@ page contentType="text/html" language="java" %>
 Include Directive (<%@ include file="..." %>): Includes content from another file at translation time
(static include).
jsp
Copy code
<%@ include file="header.jsp" %>
 Taglib Directive (<%@ taglib uri="..." prefix="..." %>): Declares a custom tag library, allowing usage
of custom tags in JSP.
jsp
Copy code
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
8. Custom Tag Libraries
Custom tag libraries (taglibs) allow developers to define their own tags to encapsulate complex functionality and
reuse it across JSPs. Tag libraries make JSP pages cleaner and more modular.
 Java Standard Tag Library (JSTL): A set of commonly used custom tags provided by Java, including
tags for core operations, formatting, SQL, and XML processing.
o Core Tag Library: Commonly used tags like <c:if>, <c:forEach>, and <c:choose> provide
conditional processing and iteration.
o Example of using JSTL to loop over a list:
jsp
Copy code
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach var="item" items="${myList}">
<p>${item}</p>
</c:forEach>
 Custom Tags: Developers can create their own tag libraries by implementing Java classes and defining
the tags in a tag library descriptor (TLD) file.
Summary of JSP Key Features
 Scripting Elements: Enable dynamic content with scriptlets, expressions, and declarations.
 Standard Actions: Perform tasks like including content and working with JavaBeans.
 Directives: Control page settings, include files, and define tag libraries.
 Custom Tag Libraries: Reusable components that simplify JSP code and enhance readability.
JSP technology facilitates a clean MVC architecture, where servlets handle business logic, and JSP files provide

6
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

the presentation layer for a dynamic and interactive user experience.

You might also like