Unit_III_Web Application Development Using JSP & Servlets
Unit_III_Web Application Development Using JSP & Servlets
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
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.
2
interface
class
class
}
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:
}
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>
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:
@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 {
response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("</body></html>");
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.
8
<input type="password" name="password" placeholder="Enter your password" />
<button type="submit">Submit</button>
</form>
@Override
response.setContentType("text/html");
response.getWriter().println("<html><body>");
9
if (isValidUser) {
} else {
response.getWriter().println("<h1>Invalid Credentials</h1>");
response.getWriter().println("</body></html>");
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()
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.
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.
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
Disadvantage of Cookies
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:
response.addCookie(cookie);
Example Code: Creating and Sending a Cookie
Retrieving Cookies
To retrieve cookies sent by the client, use the HttpServletRequest.getCookies() method.
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);
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:
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:
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
5. Destroy Phase
When the JSP page is no longer needed or the server shuts down, the
jspDestroy() method is called to release resources.
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
<!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
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
response
Used to modify the HTTP response (e.g., setting headers or status codes).
Example:
out
session
24
Stores user-specific data across multiple requests.
Example:
application
config
pageContext
Provides access to all JSP scopes (request, session, application) and page
attributes.
Example
page
exception
25
Used in error pages to handle exceptions.
Example
26