Unit7 Servlets and Java Server Page

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Web Container

In Java, a web container is a software component that provides the runtime


environment for web applications (web application contains servlets as controller, JSP as
view if developed using MVC pattern ). Web container may be built-in within web server or
sometimes it can be separate system. Web container is responsible for managing the
lifecycle of servlets of a web application that handles HTTP requests and responses,
and providing a number of other services such as security, transaction management
etc. When a request is made from the client to the web server, it passes the request to
web container, which finds the correct servlet and required resources to handle the
request, then use the resource to generate response and provide response to web
server. The container also provides a set of standard interfaces and classes that the
application can use to interact with the container and the underlying Java EE platform.
Some important works done by the web container are:
- Communication support between web server and servlets and JSPs.
- Lifecycle and resource management of servlet.
- Multithreading support
Some popular Java web containers include Apache Tomcat, Jetty etc.

Java Servlets (def. imp. For exam)


Servlets in Java are server-side components or java programs that that executes on
web server and handle incoming requests from web browsers or other clients and
generate dynamic responses based on the request. Servlets provide a way to handle
HTTP requests, process data, and generate HTML responses dynamically. Servlets can
interact with databases, run business logic, and communicate with other web services.
Essentially, servlets are a way to create web applications using Java.

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:

1. Loading and Instantiation:


In this stage, when a web server starts up or when a new request is received
from web browser or client, the servlet container loads the servlet class and
creates an instance of the servlet class for handling the request. The servlet
class instance is created only once in the servlet life cycle.

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.

5. Garbage collection by JVM:


Once the servlet is destroyed, garbage collector component of JVM will collect
the garbage’s.

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.

Writing servlets program


There are different ways to write a servlet program in Java. They are:
a. By Extending or inheriting the HttpServlet class
b. By extending or inheriting GenericServlet class
c. By implementing Servlet interface
Among them, Extending or inheriting the HttpServlet class is the most common way to
write a servlet program. You can create a Java class that extends the HttpServlet class
and override the doGet() or doPost() method to handle the HTTP GET or POST
requests.

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

Deploying servlet app process:


There are six steps to write the Servlet program (suppose here using apache tomcat
server). They are:
a. Install the Apache Tomcat server and configure it properly.
b. Then create the servlet program in your project. For this, create a new Java class
that extends the HttpServlet class. This class will be the servlet class that handles
the incoming HTTP requests. Override the doGet() and doPost() methods in the
servlet class. These methods will contain the logic to handle the incoming GET and
POST requests respectively.
c. Compile the servlet code using a Java compiler. The compiled servlet code should
be saved in a .class file.
d. 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.
e. Start the Tomcat server and deploy the WAR file on the Tomcat server.
f. Test the servlet by accessing it.

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.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException {

resp.setContentType("text/html"); //setting the content type


PrintWriter out = resp.getWriter(); //get the stream to write data

//writing html in the stream


out.println("<html>");
out.println("<head>");
out.println("<title>Hello World Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
out.close(); //closing the stream
}
}

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 {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Reading username and password from the HTML form


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

// Displaying the values of username and password


out.println("<html><body>");
out.println("<h2>Username: " + username + "</h2>");
out.println("<h2>Password: " + password + "</h2>");
out.println("</body></html>");
}
}

Processing forms using the Servlets


Processing forms using Servlets involves creating a Java Servlet that can handle HTTP
requests sent by HTML forms. Here's an overview of the steps involved in processing
forms using Servlets:

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.*;

public class LoginServlet extends HttpServlet {

private String validUsername = "user";


private String validPassword = "password";

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Get the username and password from the JSP form


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

// Validate the username and password


if (username.equals(validUsername) && password.equals(validPassword))
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>You are a valid user, Welcome!</h2>");
out.println("</body></html>");
} else {
response.sendError("Invalid username or password");
}
}
}

Database Access with Servlets:


Servlets do database access in same way as database connection access done by a
simple java application, as discussed in unit 4.
Handling Cookies in Servlets: (remember short overview only)
Handling Cookies in Servlets: (remember short overview only)

Q.Describe the process to deploy the servlet.


Solution:
Deploying a servlet involves several steps. Here's a general outline of the process:
a. Develop the servlet code: Write the servlet code using Java programming
language. The servlet code should be compliant with the Java Servlet API
specifications.

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: <%! ... %>

4. JSP Comments: This is used to show comment in JSP page.


Syntax: <% --... --%>:

5. JSP syntaxes for directives:


a. Page directive: The page directive is used to define page-level attributes
and import statements. It is placed at the beginning of a JSP page before any
other JSP elements.The syntax for the page directive is:
<%@ page attribute="value" %>
Here, "attribute" is the name of the attribute and "value" is its value.
Example: <%@ page language="java" %>
Example: <%@ import="java.util.*" %>

b. Include directive: The include directive is used to include the contents of an


external file into a JSP page. It is placed within a JSP page wherever the
content is to be included. The syntax for the include directive is:
<%@ include file="filename" %>
Example: <%@ include file="header.jsp" %>

Example: A simple JSP file to display "Tribhuwan University" five times

Example: JSP program that creates and process form.


How forms can be created and processed using JSP? Make it clear with your own
assumptions. (5) [2076]
Solution:
Assuming that we want to create a registration form that allows users to enter their
username, and password. When the user submits the form, page will process the form
by validating the input data and display a message indicating whether the registration
was successful or not. Specify the method attribute as "POST" and we will not use
action attribute here since form data is not being passed to other page, otherwise the
action attribute will have value as: the URL of the JSP file that will process the form
data.
<%@ page language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<form method="POST">
<label>Username:</label>
<input type="text" name="username"><br>
<label>Password:</label>
<input type="password" name="password"><br>
<button type="submit" name="submit" value="submit">Submit</button>
</form>

<%
// Handle form submission
if (request.getParameter("submit") != null) //request is jsp implicit object
{

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


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

// Validate input data


boolean isValid = true;
String errorMessage = "";
if (Uname == null || Uname.trim().isEmpty()) {
isValid = false;
errorMessage = "Please enter your Username.";
}
else if (password == null || password.trim().isEmpty()) {
isValid = false;
errorMessage = "Please enter your password.";
}

// Display registration result


if (isValid) {
out.println("<p>Registration Succeed! Welcome user to new
page!!</p>");
}
else {
out.println("<p>Registration failed. + errorMessage + "</p>");
}
}
%>
</body>
</html>

Example: passing data from one JSP page to another


Write a program to a JSP web form to take inputs from user and submit it to second
JSP file which will validate and simply print the values of form submission. (5)[2075]
Solution:
Here's an example of a JSP program that takes inputs from the user, submits them to
a second JSP file, and then validates and prints the form submission:
‘form.jsp’ page:
<!DOCTYPE html>
<html>
<head>
<title>Form Submission</title>
</head>
<body>
<h1>Form Submission</h1>
<form action="process.jsp" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

‘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");

// Validate input data


boolean isValid = true;
String errorMessage = "";
if (name == null || name.trim().isEmpty()) {
isValid = false;
errorMessage = "Please enter your name.";
} else if (password == null || password.trim().isEmpty()) {
isValid = false;
errorMessage = "Please enter your password.";
}

// Display form submission result


if (isValid) {
out.println("<p>Thank you for registering! "</p>");
out.println("<p>Your Name is: " + name + "</p>");
out.println("<p>Your password is: " + password + "</p>");
} else {
out.println("<p> submission failed. " + errorMessage + "</p>");
}
%>
</body>
</html>

JSP implicit objects


In JavaServer Pages (JSP), implicit objects are a set of predefined objects that are
automatically available in every JSP page, without the need to declare or initialize them
explicitly. These objects provide important information and functionality that can be
used by JSP developers to simplify their code and perform common tasks.

The following are some of JSP implicit objects:


1. request: This object represents the client's HTTP request that triggered the
current JSP page. It provides access to request specific information such as
parameters, headers, session attributes etc.

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

Processing Forms in JSP


Database Access using JSP
(same as other normal java application accessing the database as discussed in unit 4)
To access the database from JSP page, we need to have the following steps done:
1. Configure JDBC driver or load JDBC driver
2. Establish a database connection
3. Execute a SQL query
4. Process the result set
5. Close the connection
Example:
<%@ page import="java.sql.*" %> <--importing the java.sql package-->
<html>
<head>
<title>Database Access Example in JSP</title>
</head>
<body>
<%
// Define database connection parameters
String dbUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";

//Load the JDBC driver


Class.forName("com.mysql.jdbc.Driver");
// Connect to the database
Connection conn = DriverManager.getConnection(dbUrl, username,
password);
// Execute a query
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// Process the query results
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
int age = rs.getInt("age");
out.println("<p>ID: " + id + "</p>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>Age: " + age + "</p>");
}
rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
This program uses the JDBC driver for MySQL to connect to a local MySQL database
(assumed to be running on port 3306) and retrieve all records from a table named
mytable. The retrieved data is then output to the JSP page using the implicit out
object.

Introduction to Java Frameworks(cheat)


Servlet Vs JSP (V.imp)
Old questions
(only one 5 marks questions asked in majority of question set. So, one 5 marks
question coming is chance).
i. What is servlet? Discuss its life cycle (5)[2072] [2076]
ii. What is JSP? Discuss with suitable example. (5)[2073]
iii. Write a Java program using servlet to display "Tribhuvan University". (5) [2074]
iv. Describe the process to deploy the servlet. Write a program to a JSP web form
to take input of a student and submit it to second JSP file which may simply
print the values of form submission. [4+6] [2075]
v. How forms can be created and processed using JSP? Make it clear with your own
assumptions. [5][2076]
vi. Define servlet. Discuss life cycle of servlet. Differentiate servlet with JSP. Write a
simple JSP file to display 'IOST' 20 times.[10][2077]
vii. How do you handle HTTP request (GET) using servlet?[5]
viii. Write short notes on:
• Servlet API
ix. Explain life-cycle of servlet in detail. Create a simple servlet that reads and
displays data from HTML form. Assume form with two fields username and
password.(5+5) [2078]
x. What is servlet? Write a simple JSP file to display "Tribhuwan University" five
times. (2+3) [2078]
xi. Write a simple JSP program to display “Tribhuvan University” 10 times.(5)
[2078]
xii. What are different ways of writing servlet programs? Write a sample Servlet
program using any one way. (1 + 4) [model question]
xiii. Discuss various scopes of JSP objects briefly. Create a HTML file with principal,
time and rate. Then create a JSP file that reads values from the HTML form,
calculates simple interest and displays it. (4 + 6) [model question]
xiv. Explain the significance of cookies and sessions with suitable example? [5]
[2075]

You might also like