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

Unit_III_Web Application Development Using JSP & Servlets

The document provides an overview of servlets, a server-side technology in Java used for handling client requests and generating dynamic responses. It covers key features, architecture, lifecycle, and methods for creating servlets, as well as handling HTTP requests and managing cookies and sessions. Additionally, it discusses the differences between GET and POST methods, along with the advantages and disadvantages of using servlets.

Uploaded by

Vaishnavi Dubey
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)
32 views

Unit_III_Web Application Development Using JSP & Servlets

The document provides an overview of servlets, a server-side technology in Java used for handling client requests and generating dynamic responses. It covers key features, architecture, lifecycle, and methods for creating servlets, as well as handling HTTP requests and managing cookies and sessions. Additionally, it discusses the differences between GET and POST methods, along with the advantages and disadvantages of using servlets.

Uploaded by

Vaishnavi Dubey
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/ 26

Unit-III

MCA 2nd semester (BMC201)


Web Application development using JSP & Servlets
Servlet Overview:
Servlet is a server-side technology that handles client requests, processes them, and
generates dynamic responses.
Servlets are Java programs that run on a web server and handle requests from web clients
(usually web browsers). They act as a middle layer between the client requests and server
responses, generating dynamic web content. Servlets are part of Java's server-side
technologies and are used to create web applications.

Key Features of Servlets:

 Platform-independent: Written in Java, servlets can run on any platform that


supports Java.
 Efficient: Once loaded, they remain in memory, which allows for faster response
times.
 Scalable: Can handle multiple client requests by creating multiple threads.
 Secure: Can use the standard Java security model, making them more secure than
traditional CGI scripts.

Servlet Architecture:

The architecture of servlets is based on a client-server model and follows the request-
response paradigm. The main components of the servlet architecture include:

1. Web Browser (Client):


o The client, usually a web browser, sends an HTTP request to the web
server.
2. Web Server:
o The web server receives the client request and passes it to the servlet
container (like Apache Tomcat or Jetty) if the request is for a servlet.
3. Servlet Container (Servlet Engine):
o The servlet container is responsible for managing the lifecycle of servlets. It
handles tasks such as loading the servlet, initializing it, invoking it to
handle requests, and unloading it.
o The container creates a new thread to handle each client request, allowing
the server to serve multiple requests simultaneously.

1
4. Servlet:
o The servlet processes the client request by executing the business logic and
interacting with databases or other resources as needed.
o It generates a response (often in the form of HTML or JSON) and sends it
back to the client through the servlet container.
5. Response:
o The response generated by the servlet is sent back to the web server, which
in turn sends it to the client's web browser.

Diagram: Servlet Architecture


Client (Web Browser)
|
| HTTP Request
|
Web Server
|
| Request passed to
| Servlet Container
|
Servlet Container
| |
| | Servlet Instance (runs service method)
| |
| HTTP Response
|
Web Server
|
| Response sent to
| Client (Web Browser)
Servlet Hierarchy:
The Servlet interface is the root interface of the servlet class hierarchy.
All Servlets need to either directly or indirectly implement the Servlet
interface.

2
interface

class

class

How to create servlet:


Ist Method:
class MyServlet implements Servlet
{

}
Note: It defines servlet life-cycle method only.

IInd Method:
class MyServlet extends GenericServlet
{

}
Note: When we want to create protocol independent servlet. It does not require request
and response.
IIIrd Method:

class MyServlet extends HttpServlet


{

}
Note: It is used when we want http specific method and request & response object.
Some commonly used http methods are:

3
1. GET: - The GET method is used to retrieve information from the given server
using a given URI(User Recourse Identifier ).
2. HEAD:- Same as GET, but transfer the status line and header section only.
3. POST:- A POST request is used to send data to the server , for example customer
information , file upload etc. using HTML forms.
4. PUT:- Replaces all current representations of the target resource with the
uploaded content.
5. DELETE:- Removes all current representations of target resource given by a URI.

Note: We have to create one file i.e., “Deployment Descriptor” file i.e., “web.xml”
Advantages
 The prime functionality of a servlet is that they are independent of server
configuration, and they are pretty much compatible with any of web server.
 Servlets are also protocol-independent, supporting FTP, HTTP, SMTP, etc.,
protocols to the fullest.
 Servlets inherit Java's property of portability and hence are compatible with
nearly any web server.
Disadvantages
 Designing a servlet can be pretty laborious.
 Exceptions must be handled while designing a servlet since they are not
thread-safe.
 Developers may need additional skills to program a servlet.
Example: MyServlet.java
package in.sp.backend;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out=resp.getWriter();
out.print("I am in doGet method");
System.out.println("I am in doGet method");

4
}
}

Web.xml
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>in.sp.backend.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/aaa</url-pattern>
</servlet-mapping>

Servlet Life Cycle:


The lifecycle of a servlet is managed by the servlet container, and it involves the
following stages:
1. Loading and Instantiation:
o When a servlet is first requested, the servlet container loads it into memory
and creates an instance of the servlet class.
2. Initialization (init method):
o The container calls the init() method only once when the servlet is first
created.
o This method is used to perform any initialization tasks (e.g., opening
database connections).
3. Request Handling (service method):
o For each client request, the servlet container calls the service() method.
o The service() method determines the type of request (GET, POST, etc.) and
calls the appropriate method (doGet(), doPost(), etc.) to handle it.
4. Destruction (destroy method):
o When the servlet is no longer needed or the server shuts down, the servlet
container calls the destroy() method.
o This method is used to release any resources that the servlet may be
holding.

5
6
Introduction to HTTP Requests in Servlets:

In servlets, HTTP requests are handled by doGet() and doPost() methods. The servlet container
(e.g., Apache Tomcat) routes GET requests to doGet() and POST requests to doPost(). Each
method receives two parameters:

 HttpServletRequest request: Contains client request data.


 HttpServletResponse response: Allows the servlet to return a response.

Basic Structure of a Servlet:


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 MyServlet extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Handle GET requests here
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Handle POST requests here
}
}
Handling HTTP GET Requests in Servlets:

The doGet() method is used to retrieve information from the server without affecting
server data (safe operation). GET requests pass data through the URL query string.

@Override

7
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Get parameters from the query string

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

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

// Set response content type

response.setContentType("text/html");

// Write response to the client

response.getWriter().println("<html><body>");

response.getWriter().println("<h1>Hello, " + name + "</h1>");

response.getWriter().println("<p>Your age is " + age + "</p>");

response.getWriter().println("</body></html>");

Handling HTTP POST Requests in Servlets:

The doPost() method is used when the client sends data that affects the server, like
form submission. POST requests pass data within the body, not the URL, making
them more secure for sensitive information.

Example: Handling a POST Request

Imagine an HTML form sending data to the servlet:

<form action="MyServlet" method="POST">

<input type="text" name="username" placeholder="Enter your name" />

8
<input type="password" name="password" placeholder="Enter your password" />

<button type="submit">Submit</button>

</form>

Servlet Code to Handle the POST Request:

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Get parameters from the request body

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

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

// Processing (e.g., validating user credentials)

boolean isValidUser = "admin".equals(username) &&"1234".equals(password);

// Set response content type

response.setContentType("text/html");

// Write response to the client

response.getWriter().println("<html><body>");

9
if (isValidUser) {

response.getWriter().println("<h1>Welcome, " + username + "</h1>");

} else {

response.getWriter().println("<h1>Invalid Credentials</h1>");

response.getWriter().println("</body></html>");

Redirecting Requests to Other Resources:


Redirecting requests in servlets is essential for handling client requests and directing them to
the appropriate resource (like another servlet, JSP, or external URL).
Redirecting Requests in Servlets

In servlet-based web applications, redirecting a request to another resource is


common for navigation, session handling, and request forwarding. There are two
main ways to redirect a request in servlets:

1. Client-Side Redirect (using HttpServletResponse.sendRedirect())


2. Server-Side Forwarding (using RequestDispatcher)
1. Client-Side Redirect: HttpServletResponse.sendRedirect()

When using sendRedirect(), the server instructs the client (usually a browser) to
make a new request to a different URL. This method is typically used when you
need to redirect the user to an external resource, another web application, or a
different domain.

Syntax:
java
Copy code
response.sendRedirect("URL");
Example
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Redirect to an external URL

10
response.sendRedirect("https://www.example.com");
}
2. Server-Side Forwarding: RequestDispatcher

The RequestDispatcher interface allows you to forward a request from one servlet
to another resource on the server side without the client knowing. This is useful
when you want to keep the request and response intact and only transfer processing
to another resource within the same application.

Obtaining a RequestDispatcher:
RequestDispatcher dispatcher = request.getRequestDispatcher("relativeURL");
Syntax for Forwarding:
dispatcher.forward(request, response);
Example
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Forwarding to a JSP page
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-
INF/result.jsp");
dispatcher.forward(request, response);
}
Differences Between sendRedirect() and forward()
Feature sendRedirect() forward()

Type Client-side redirect Server-side forward

Yes, the URL in the browser


URL Change changes No, the URL remains the same

Request and Response New request initiated Original request forwarded

Only forwards within the same


Resource Location Can redirect to external resources app

Attributes/Parameters Not preserved in the new request Preserved and passed to the target

Status Code Sends HTTP 302 response No new response sent to client

11
Difference between doGet() and doPost() in Java Servlets:

Both doGet() and doPost() are methods in the HttpServlet class used to handle HTTP requests
from clients, but they differ in how they transmit data and are used in different scenarios.

Aspect doGet() doPost()


Purpose Handles HTTP GET requests Handles HTTP POST requests
Data is appended to the URL (visible in Data is sent in the request body (not
Data Visibility
the address bar) visible)
Data Length Limited (depends on URL length, e.g., No practical limit (can send large
Limit ~2048 chars) amounts of data)
Use Case Used for retrieving data Used for sending or updating data
More secure (parameters hidden in
Security Less secure (parameters visible in URL)
body)
Caching Can be cached by browser Cannot be cached by default
Can be bookmarked (URL contains Cannot be bookmarked (no data in
Bookmarking
data) URL)

Cookies in servlet

Cookies are a mechanism in Java servlets for storing small pieces of information
on the client side, allowing servlets to retain user-specific data across multiple
requests. They’re commonly used for session management, personalizing content,
and tracking user activity.

How Cookie works

By default, each request is considered as a new request. In cookies technique, we


add cookie with response from the servlet. So cookie is stored in the cache of the
browser. After that if request is sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old user.

12
Types of Cookie
There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the
browser.

Persistent cookie

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.

Advantage of Cookies

1. Simplest technique of maintaining the state.


2. Cookies are maintained at client side.

Disadvantage of Cookies

1. It will not work if cookie is disabled from the browser.


2. Only textual information can be set in Cookie object.

Creating and Sending Cookies:


To create a cookie in a servlet, use the Cookie class. A cookie has a name and a
value, both of which are strings.

Cookie cookie = new Cookie("username", "KIPM");


Setting Cookie Properties:

After creating a cookie, you can set various properties, such as the maximum age
(lifetime) and path.

13
cookie.setMaxAge(60 * 60 * 24); // Cookie will last for one day
cookie.setPath("/"); // Cookie accessible to the entire application
Sending a Cookie to the Client:

To send a cookie from a servlet to the client,use HttpServletResponse.addCookie():

response.addCookie(cookie);
Example Code: Creating and Sending a Cookie

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException {
Cookie userCookie = new Cookie("username", "KIPM");

userCookie.setMaxAge(60 * 60 * 24); // 1 day


response.addCookie(userCookie);
response.getWriter().println("Cookie has been set.");
}

Retrieving Cookies
To retrieve cookies sent by the client, use the HttpServletRequest.getCookies() method.

This returns an array of Cookie objects.

Cookie[] cookies = request.getCookies();

Deleting Cookies
To delete a cookie, set its maximum age to zero and add it again to the response.
This instructs the browser to delete the cookie.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {

14
Cookie deleteCookie = new Cookie("username", "");
deleteCookie.setMaxAge(0); // Set max age to zero to delete the cookie
response.addCookie(deleteCookie);

response.getWriter().println("Cookie has been deleted.");


}
Session Tracking with Http Session:
Session tracking is a mechanism to maintain state (data) about a client across
multiple requests in a web application. The HttpSession interface in Java servlets
provides a simple way to manage user sessions on the server side.
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.

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

Example of using HttpSession


index.html
. <form action="servlet1">
. Name:<input type="text" name="userName"/><br/>
. <input type="submit" value="go"/>
. </form>
FirstServlet.java
. import java.io.*;
. import javax.servlet.*;
. import javax.servlet.http.*;
.
.
. public class FirstServlet extends HttpServlet {

16
.
. public void doGet(HttpServletRequest request, HttpServletResponse respon
se){
. try{
.
. response.setContentType("text/html");
. PrintWriter out = response.getWriter();
.
. String n=request.getParameter("userName");
. out.print("Welcome "+n);
.
. HttpSession session=request.getSession();
. session.setAttribute("uname",n);
.
. out.print("<a href='servlet2'>visit</a>");
.
. out.close();
.
. }catch(Exception e){System.out.println(e);}
. }
.
. }
SecondServlet.java
. import java.io.*;
. import javax.servlet.*;
. import javax.servlet.http.*;
.
. public class SecondServlet extends HttpServlet {
.
. public void doGet(HttpServletRequest request, HttpServletResponse respon
se)
. try{
.
. response.setContentType("text/html");
. PrintWriter out = response.getWriter();
17
.
. HttpSession session=request.getSession(false);
. String n=(String)session.getAttribute("uname");
. out.print("Hello "+n);
.
. out.close();
.
. }catch(Exception e){System.out.println(e);}
. }
.
.
. }
web.xml
. <web-app>
.
. <servlet>
. <servlet-name>s1</servlet-name>
. <servlet-class>FirstServlet</servlet-class>
. </servlet>
.
. <servlet-mapping>
. <servlet-name>s1</servlet-name>
. <url-pattern>/servlet1</url-pattern>
. </servlet-mapping>
.
. <servlet>
. <servlet-name>s2</servlet-name>
. <servlet-class>SecondServlet</servlet-class>
. </servlet>
.
. <servlet-mapping>
. <servlet-name>s2</servlet-name>
. <url-pattern>/servlet2</url-pattern>
. </servlet-mapping>
.

18
. </web-app>
.
Java Server Pages (JSP):
 JSP stands for Java Server Pages.
 JSP is a server side technology which is used to create dynamic web pages.
 JSP is an advanced version of Servlet Technology.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and development. It
provides some additional features such as Expression Language, Custom Tags, etc.
Advantages of JSP

1. Ease of Development:
1. Combines Java and HTML in a single file.
2. Platform Independent:

1. Runs on any server supporting Java EE.


3. Integration with Java:

1. Easily integrates with Java classes, servlets, and other technologies.


4. Rich Libraries:

1. Includes JSTL (JavaServer Pages Standard Tag Library) and supports


custom tag libraries.

To embed Java code in JSP we can use below tags:


1. Scripting Tag:
<% some Java code %>
2. Expression Tag:
<%= an expression %>
3. Declaration Tag:
<%! variable declaration & method definition %>
4. Directive Tag:
<%@ directives %>

19
5. Comment Tag:
<%- any text -%>
6. Action Tag:
<jsp:actionName/>
Lifecycle of a JSP:

The lifecycle of a JSP (Java Server Page) defines the stages it goes through from
its creation to destruction. It consists of the following phases:

1. Translation Phase

 The JSP file is translated into a Java Servlet by the JSP container.
 This is done the first time the JSP page is requested or when it is updated.

2. Compilation Phase

 The translated Servlet code is compiled into a .class file.

3. Loading and Initialization Phase

 The compiled Servlet is loaded into memory.


 The jspInit() method is called to perform any required initialization.

4. Request Processing Phase

 For each client request, the jspService() method is invoked to generate a


dynamic response.
 This is the main method where the JSP page interacts with the client.

5. Destroy Phase

 When the JSP page is no longer needed or the server shuts down, the
jspDestroy() method is called to release resources.

Diagram of JSP Lifecycle:


+--------------------------+
| JSP Page |
+--------------------------+

20

+--------------------------+
| Translation (JSP to |
| Servlet Conversion) |
+--------------------------+

+--------------------------+
| Compilation (Servlet |
| to Class File) |
+--------------------------+

+--------------------------+
| Loading and Initialization|
| (jspInit() method) |
+--------------------------+

+--------------------------+
| Request Processing |
| (jspService() method) |
+--------------------------+

+--------------------------+
| Destroy Phase |
| (jspDestroy() method) |
+--------------------------+

21
A First Java Server Page Example:
Example of a Java Server Page (JSP) that demonstrates how to create and run
your first JSP application.
Steps to Create and Run Your First JSP Example

1. Set Up Your Environment

Ensure you have:

 Apache Tomcat or any other web server installed.


 A Java Development Kit (JDK) installed.
22
 A text editor or an IDE like Eclipse.

2. Create the JSP File

Save the following code as hello.jsp inside the webapps/<YourApplicationName>


directory (e.g., webapps/FirstJSPApp).

<!DOCTYPE html>
<html>
<head>
<title>My First JSP Page</title>
</head>
<body>
<h1>Welcome to JSP!</h1>
<p>The current date and time is: <%= new java.util.Date() %></p>
</body>
</html>
Output:
Welcome to JSP!
The current date and time is: Tue Nov 19 11:34:45 IST 2024

Implicit Objects in jsp:


In JavaServer Pages (JSP), implicit objects are pre-defined objects provided by
the JSP container. These objects are automatically available to developers in a JSP
page without needing explicit declaration or instantiation. They are part of the
javax.servlet and javax.servlet.http packages.
List of Implicit Objects in JSP:
Object Class Description
request HttpServletRequest Represents the HTTP request sent by
the client to the server.
response HttpServletResponse Represents the HTTP response sent by
the server to the client.
out JspWriter Used to send content to the client.
Similar to PrintWriter in servlets.
session HttpSession Represents the session associated with

23
a user.
application ServletContext Represents the application context.
config ServletConfig Provides configuration information for
the JSP page.
pageContext PageContext Provides access to all namespaces
(request, session, application).
page java.lang.Object Refers to the instance of the JSP page
itself.
exception java.lang.Throwable Represents exceptions thrown in the
JSP page (used in error pages only).

request

 Access client request data, such as parameters, headers, and attributes.


 Example:

<p>Client's IP Address: <%= request.getRemoteAddr() %></p>

response

 Used to modify the HTTP response (e.g., setting headers or status codes).
 Example:

<% response.setContentType("text/html"); %>

out

 Used to send output to the client browser.


 Example

<p>Welcome to JSP!<br>The current time is: <%= new java.util.Date() %></p>

session

24
 Stores user-specific data across multiple requests.
 Example:

<% session.setAttribute("userName", "KIPM"); %>


<p>Welcome, <%= session.getAttribute("userName") %>!</p>

application

 Shares data across the entire application (all users).


 Example

<% application.setAttribute("appName", "My JSP App"); %>


<p>Application Name: <%= application.getAttribute("appName") %></p>

config

 Contains initialization parameters for the JSP page.


 Example

<p>Servlet Name: <%= config.getServletName() %></p>

pageContext

 Provides access to all JSP scopes (request, session, application) and page
attributes.
 Example

<% pageContext.setAttribute("greeting", "Hello from JSP!"); %>


<p><%= pageContext.getAttribute("greeting") %></p>

page

 Refers to the JSP page itself (like this in Java).


 Example (not commonly used):

<p>Page object class: <%= page.getClass().getName() %></p>

exception
25
 Used in error pages to handle exceptions.
 Example

<p>Error Details: <%= exception.getMessage() %></p>

26

You might also like