02/01/2020

What is Java Servlet - Studywow | Servlet in Java

Studywow: Read what is Java Servlet and Life Cycle of Servlet. For more topics of java, click here!


Q.1. What is Java servlet?

Ans. Java servlets provide a component-based, platform-independent methods for building web-based applications. Servlets are Java programs that can be deployed on Java enabled web server to enhance and extend the functionality of the web server. It is a class that extend the capabilities of the servers and respond to the incoming request.

Q2. Define the functions of Servlet?

Ans. Servlets perform the following major functions:
(a) Read the explicit data sent by the clients (browsers). This include HTML from on a web page.
(b) Read the implicit HTTP request data sent by the clients (browsers), i.e. cookies, media types and compression schemes the browser understands and so forth.
(c) Process the data and generate the results.
(d) Send the explicit data (i.e. the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), excel, etc.
(e) Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g. HTML), setting cookies and caching parameters and other such tasks.

Q.3. How servlets are created in Java?


Ans. Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects. Generally, Servlets can be created in three ways:
(a) By implementing Servlet interface,
(b) By inheriting GenericServlet class,
(c) By inheriting HttpServlet class.

Q4. Give the life cycle of Java Servlet?

Ans. The servlet life cycle describes how the servlet container manages the servlet object. The following steps are followed by a servlet:
1. Loading ServletClass: A servlet class is loaded when first request for the servlet is received by the web container.
2. Creating Servlet Instance : The servlet instance is created by the web container when the servlet class is loaded.
3. Call to the init() Method: This method is called by container only once, when the servlet is created.
Syntax: public void init() throws ServletException {
........................
}

4. Call to service() Method: This method is called by the web container each time to handle requests from clients.
Syntax: public void service (ServletRequest request, Servlet Response
response) throws ServletException, IOException

5. Call to destroy Method : This method is used to clean resources and called before
removing the servlet instance.
Syntax: public void destroy ( ) {
//Finalisation code...
}

Q5. Describe the procedure and program of database connectivity using Java Servlet ?

Ans. To start with basic concept, let us create a simple table and create few records in that table as follows:

Create Table

To create the Employees table in TEST database, use the following steps:
Step 1: Open a Command Prompt and change to the installation directory as follows:
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>

Step 2: Login to database as follows
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>

Step 3: Create the table Employee in TEST database as follows:
mysql> use TEST;
mysql> create table Employees
{
id int not null,
age int not null,
first varchar (255),
last varchar (255)
};
Query OK, O rows affected (0.08 sec)
mysql>

Create Data Records

Finally you create few records in Employee table as follows:
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO Employees VALUES (101, 25, 'Mayank', 'Rana');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal').;
Query OK, 1 row affected (0.00 sec)
mysql>

Accessing a Database

Here is an example which shows how to access TEST database using Servlet.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Database Access extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// JDBC driver name and database URL
static final String JDBC DRIVER="com.mysql.jdbc.Driver";
static final String DB URL="jdbc:mysql://localhost/TEST";
// Database credentials
static final String USER = "root";
static final String PASS = "password";
// Set response content type
response.setContentType ("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public "-//W3c//dtd html 4.0 " + "transitional//en\">\n";
out.println (docType +"<html>\n" + "<head><title>" + title + "</title></head> \n" +
"<body bgcolor=\"#f0f0f0\">\n" + "<h1 align="center\">" + title + "</h1>\n");
try{
// Register JDBC driver
Class.forName ("com.mysql.jdbc.Driver");
// Open a connection
conn = DriverManager.getConnection (DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement ();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery (sql);
// Extract data from result set
while (rs.next()) {
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString ("last");
//Display values
out.println(", ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
//Handle errors for JDBC
e.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally{
//finally block used to close resources
try{
if (stmt !=null)
stmt.close();
} catch (SQLException se2) {
} // nothing we can do
try{
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} //end finally try
} //end try

Now let us compile above servlet and create following entries in web.xml
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern> / DatabaseAccess</url-pattern>
</servlet-mapping>

Now call this servlet using URL http://localhost: 8080/DatabaseAccess which would display following response:
Database Result 
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mayank, Last: Rana
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal




Join us on Facebook and Twitter  to get the latest study material. You can also ask us any questions.
Facebook = @ studywow
(click on it or search "studywow" on facebook)
Twitter = @ studywow
(click on it or search "studywow" on Twitter)
Email= studywow.com@gmail.com
Send us your query anytime!