Unit7 Servlets and Java Server Page
Unit7 Servlets and Java Server Page
Unit7 Servlets and Java Server Page
Servlets can dynamically extend the capabilities of servers. Servlets are typically
deployed to a web container, which provides an environment for the servlet to run.
When a user requests a resource from a web application, the web container intercepts
the request and passes it to the appropriate servlet. The servlet processes the request
and generates a response, which is then sent back to the user.
Servlets are built using the Java Servlet API, which is a standard Java interface for
building web applications. To create a servlet, you need to create a Java class that
implements the javax.servlet.Servlet interface. This interface provides methods for
initializing, processing requests, and handling errors.
Servlets can be used to create a wide range of web applications, from simple web
pages to complex web services. They provide a powerful and flexible way to build
server-side applications using Java.
Life cycle of Servlets (very imp. For exam)
The life cycle of a servlet can be divided into five stages:
2. Initialization:
After the servlet instance is created, the servlet container calls the servlet's init()
method. This method is used to initialize the servlet, by loading configuration
parameters and setting up resources that the servlet needs to operate.
3. Request Handling:
Once the servlet is initialized, it is ready to handle the requests. For each
incoming request, the servlet container creates a new thread and calls the
servlet's service() method for processing the request, generating a response,
and sending it back to the client.
4. Destruction:
After when the servlets completes handling the request, then the container will
shut down or unload or destroy the servlet, by calling the servlet's destroy()
method. This method performs any necessary cleanup activities, such as
releasing resources like memory, threads etc. or closing database connections.
The init() and destroy() methods are called only once during the life cycle of a servlet,
while the service() method can be called multiple times for each request. The servlet
container manages the life cycle of the servlet, ensuring that it is created, initialized,
and destroyed correctly.
Servlet API (imp. For short notes in exam)
Servlet API in Java is a set of interfaces and classes that allow Java developers to
create dynamic web applications. Servlet API provides a standard way for Java
developers to create web applications that can be run on any web server that supports
the Java Servlet specification and that can be easily maintained and scaled. It provides
a standard way for web servers to communicate with servlets and vice versa.
The Servlet API in Java contains two main packages containing classes and interfaces:
javax.servlet and javax.servlet.http.
The javax.servlet package provides the core interfaces and classes for creating
servlets. The most important interface in this package is the Servlet interface, which
defines the basic methods that a servlet must implement, such as the init(), service(),
and destroy() methods. Other important interfaces in this package include
ServletConfig, which provides servlets with access to initialization parameters, and
ServletContext, which provides servlets with access to shared resources and context
information.
The javax.servlet.http package builds on top of the javax.servlet package and provides
additional interfaces and classes specifically for handling HTTP requests and responses.
The most important interface in this package is the HttpServletRequest interface, which
provides methods for accessing information about the incoming http request, such as
the request URL and any parameters that were sent. The HttpServletResponse
interface provides methods for generating a http response to the client, such as setting
response headers and writing response data.
NOTE: (When to use HTTP GET and HTTP POST? They are two common methods for sending
data over the internet using the HTTP protocol. HTTP GET is used to retrieve data from a
server. It is typically used when you want to request data from a server, such as a web page or
a file. On the other hand, HTTP POST is used to submit data to a server. It is typically used
when you want to send data to a server to be processed, such as when submitting a form or
uploading a file.)
Example: of servlet program that accepts HTTP GET request and sends the
webpage as data response to client.
(Q. How do you handle HTTP request (GET) using servlet?[5] [2076])
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Example: of servlet program that accepts HTTP POST request and sends the
response to client.
(Q. Create a simple servlet that reads and displays data from HTML form. Assume form
with two fields username and password.(5+5) [2078])
Solution:
Here's an example of a simple servlet that reads and displays data from an HTML form
with two fields - "username" and "password":
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
a. Create a HTML form: The first step is to create an HTML form that collects user
input and submits user inputs to the server by HTTP POST. The form should
have an action attribute that specifies the URL of the Servlet that will process
the form data.
b. Create a Servlet: Next, create a Java Servlet that will handle the form data. The
Servlet should override the doPost() method, which is called when the form is
submitted via HTTP POST.
c. Retrieve form data: Inside the doPost() method, you can retrieve the form data
using the request.getParameter() method. This method takes the name of the
form field as a parameter and returns the value entered by the user.
d. Process form data: Once you have retrieved the form data, you can process it as
required. For example, you could perform validation on the data to ensure it
meets certain requirements or store it in a database.
e. Send response: Finally, you can send a response back to the user to indicate
that the form has been processed. This could be a simple message or a redirect
to a new page.
Example: Servlet program for processing user login forms data sent as HTTP
POST request:
Q. create one simple jsp form that sends username and password using POST request
to a servlet program. also write a simple servlet program that gets that response,
validates the username and password set by that jsp form, and sends the response "
you are valid user, Welcome"
Jsp page or html page:
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form method="post" action="LoginServlet">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
b. Compile the servlet code: Use a Java compiler to compile the servlet code. The
compiled servlet code should be saved in a .class file.
c. Create a web application archive (WAR) file: Create a WAR file that contains the
servlet code, as well as any other files (such as HTML, JSP, or configuration files)
that the servlet needs to run. The WAR file should have a specific directory
structure, including a WEB-INF directory with a web.xml file that describes the
servlet.
d. Deploy the WAR file: Copy the WAR file to the web application container (such as
Tomcat or Jetty). The container will automatically extract the contents of the
WAR file and deploy the servlet.
e. Configure the servlet: Configure the servlet using the web.xml file. This file
specifies the servlet's URL mappings, initialization parameters, and other
settings.
f. Start the web application container: Start the web application container, which
will load the servlet and make it available to clients.
g. Test the servlet: Test the servlet by accessing it through a web browser or using
a tool like curl or Postman. Make sure that the servlet is functioning correctly
and responding to requests as expected.
Note that the exact process of deploying a servlet may vary depending on the specific
web application container being used, and the server being used.
JavaServer Pages(JSP)
JSP stands for JavaServer Pages. It is a server-side technology used to create dynamic
web pages using Java. JSP pages are similar to HTML pages, but they can contain Java
code that is executed on the server before the page is sent to the client.
JSP allows developers to create dynamic web pages that can be customized based on
user input, database content, and other factors. It is a powerful tool for building web
applications that require complex functionality and dynamic content.
JSP (JavaServer Pages) scripting elements or syntaxes are used to embed Java
code into an HTML page. There are four types of scripting elements in JSP:
1. JSP Scriptlet: This is the most commonly used scripting element in JSP. It is
used to enclose Java code that can be executed once during the page
processing. Syntax: <% …java code… %>
2. JSP Expression: This is used to output the result of a Java expression directly
into the HTML response that is sent to the client's browser. It can be used to
print the value of a variable or the result of a method call. Syntax: <%= ... %>:
Example:
<%
message = "Good evening!";
%>
<!DOCTYPE html>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<h1><%= message %></h1>
<p>Welcome to our website. We hope you enjoy your visit.</p>
</body>
</html>
3. JSP Declaration: This is used to define global functions and variables that can
be accessed by other JSP elements in JSP page. Syntax: <%! ... %>
<%
// Handle form submission
if (request.getParameter("submit") != null) //request is jsp implicit object
{
‘process.jsp’ page
<!DOCTYPE html>
<html>
<head>
<title>Form Submission Result</title>
</head>
<body>
<h1>Form Submission Result</h1>
<%
// Retrieve form values
String name = request.getParameter("name");
String password = request.getParameter("password");
2. response: This object represents the HTTP response that will be sent back to
the client. It provides methods for setting response headers and writing
response content.
3. session: This object represents the user's HTTP session with the web
application. It provides a way to store and retrieve session attributes.
4. out: This object represents the output stream that is used to send content back
to the client.
5. config: This object provides access to the JSP page's configuration information,
such as the context path, servlet context, and initialization parameters.
These implicit objects can be accessed using standard Java syntax within a JSP page.
For example, to access the request object, we would use ‘request’ and to access a
parameter passed in the request, we would use ‘request.getParameter(“paramName”);
JSP Access Model
Object Scope