Getting Started with Servlets and JSP using Tomcat

What is a Servlet?

  • A servlet is a server-side program which executes inside a Web server, such as Apache.
  • It Receives HTTP requests from the client and provides HTTP responses

The Servlet API

Servlet API is used to create servlets.

Servlets use classes and interfaces from two packages: javax.servlet and javax.servlet.http. The javax.servlet package contains classes to support generic, protocol-independent servlets.

These classes are extended by the classes in the javax.servlet.http package to add HTTP-specific functionality.

The top-level package name is javax instead of the familiar java, to indicate that the Servlet API is a standard extension.

Every servlet must implement the javax.servlet.Servlet interface. Most servlets implement it by extending one of two special classes: javax.servlet.GenericServlet or javax.servlet.http.HttpServlet.

What is Tomcat?

Tomcat is a Servlet Container.

  • Manages servlet loading/unloading
  • Works with the Web server (e.g. Apache) to direct requests to servlets and responses back to clients

How to Create and Run Servlets

1. Download and install Java SE 6 (including JRE)

You can download Java from the link below

http://www.java.com/en/download/index.jsp

Install it in your system

2. Download Tomcat

You can download Tomcat from the link below. The latest version of Tomcat is Tomcat 7.0

http://tomcat.apache.org/

Install Tomcat.

3. Configure the server

4. Test set up

The Tomcat Home Page gets displayed if it’s successfully installed

TomcatHomePage

TomcatHomePage

Tomcat Directory/File Structure

TomcatDirectoryStructure

Tomcat Directory Structure

This is the Tomcat Directory structure once it is installed in your system.

Tomcat Directories/Files Description

Directory Description
bin The binary executables and scripts
conf  Configuration files
lib JAR files that contain classes that are available to all Web applications
logs Log files
webapps Web applications
work  Temporary files and directories for Tomcat

Deploy a Web Application in Tomcat

  • The application should be under the C:\Tomcat 7.0\webapps directory
  • A root directory for the application can be created under the C:\Tomcat 7.0\webapps directory (e.g. C:\Tomcat 7.0\webapps\ContactApp)
  • The root directory contains sub-directories, the index file, HTML and JSP files for the application.
  • All directories and files relating to our applications should be under this directory
  • Applications that use servlets must have the WEB-INF and WEB-INF\classes directories inside their root directories
  • Put the Deployment descriptor for the application inside the WEB-INF directory.

Deployment Descriptor

  • Deployment descriptor is an XML file with the name web.xml
  • It should be in the WEB-INF directory

A Sample Deployment Descriptor

<web-app>
	<servlet>
		<!--Name for referring to it elsewhere in the DD -->
		<servlet-name>HelloServlet</servlet-name>
		<!-- Full name, including any package details-->
		<servlet-class>servlets.HelloWorldServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<!--Name of the servlet again -->
		<servlet-name>HelloServlet</servlet-name>
		<!--Client’s URL will have this -->
		<url-pattern>/HelloServlet</url-pattern>
	</servlet-mapping>

</web-app>

Tomcat: Important Directories for an application in webapps directory

Directory Description
doument root Contains sub-directories, the index file,  HTML and JSP files for the application.
\WEB-INF Contains a file named web.xml. It can be used to configure servlets and other components that make up the application.
\WEB-INF\classes Contains servlets and other Java classes that are not compressed into a JAR file. If Java packages are used, each package must be stored in a subdirectory that has the same name as the package.
\WEB-INF\lib Contains any JAR files that contain Java classes that are needed by this application, but not by other Web

Writing your First Servlet

Open any Text Editor and Type the Program below.

HelloWorldServlet.java


package servlets;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HelloWorldServlet extends HttpServlet
{
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
	{
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		out.println("<html>");
		out.println("<head><title>Hello World Servlet</title></head>");
		out.println("<body>");
		out.println("<h1>Hello World!!!</h1>");
		out.println("<p>Welcome to the world of Servlets and JSP!!!</p>");
		out.println("</body></html>");
	}
}

Compile it like any other Java Program using javac command. The class file should get generated successfully.

Deploying and Running your Servlet

  • Create a root directory for the application under the C:\Tomcat 7.0\webapps directory (e.g. C:\Tomcat 7.0\webapps\Servlet1)
  • Create a WEB-INF and WEB-INF\classes directories inside the Servlet1 Directory.
  • Make a directory called servlets inside WEB-INF\classes directory as our HelloWorld Servlet is inside this package.
  • Put the class file of the servlet inside WEB-INF\classes\servlets directory.
  • Write the Deployment Descriptor web.xml and put it under the WEB-INF directory.

Deployment Descriptor for Hello World Servlet


<web-app>

	<servlet>
		<servlet-name>HelloServlet</servlet-name>
		<servlet-class>servlets.HelloWorldServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>HelloServlet</servlet-name>
		<url-pattern>/HelloServlet</url-pattern>
	</servlet-mapping>

</web-app>

Running Hello World Servlet

  1. Start tomcat
  2. Open browser and type http://localhost:8080. The Home Page of Tomcat should open.
  3. Type http://localhost:8080/Servlet1/HelloServlet in the address bar of your browser.
  4. The Servlet should run and display the famous greetings in programming

Snapshot of the o/p

Hello World Servlet

Servlets are extremely powerful and can do a lots of work very easily as compared to CGI. They are good in performance and secure. :D

Web Based Contact Management System using JSP and MySQL-Part 3

Hi Friends 

Hope you are fine and Enjoying your Holidays. Here I am back with the Third part of this Mini Contact Management System using JSP and MySQL.

Here’s the Link for the First and Second Parts

Web Based Contact Management System Using JSP and MySQL Part 1

Web Based Contact Management System Using JSP and MySQL Part 2

In this Part we will see

  • Removing a Contact
  • Searching for an existing Contact

Contact_Delete.jsp

This jsp page is called when the user clicks on the Delete hyperlink below a Contact. It takes the Contact Id and Delete the Contact from the DB.

SQL DELETE Statement has been used  for removing the contact.

 


<%@page import="java.util.*"%>
<%@page import="java.sql.*"%>

<html>

<head><title>My Contacts</title></head>

<body>

<%@include file='Includes/db_connect.jsp'%>

<%! boolean success = false; %>
<%
	int contact_id = Integer.parseInt(request.getParameter("contact_id"));	
	
	String sql= "DELETE FROM contact_details WHERE contact_id = ?";
	
	PreparedStatement pstmt = con.prepareStatement(sql);
	pstmt.setInt(1, contact_id);
	
	int nRows = pstmt.executeUpdate();
	
	if(nRows==0){
		success = false;
	}
	
	else{
		success = true;	
	}
	
	pstmt.close();con.close();

%>
	
	
	<%
			if(success==true){
	%>
	
	<h2>Contact have been successfully deleted</h2>
	
	<%
		}//if end
		else{		
	%>
	
	<h2> Error -- Contact could not be deleted </h2>
	
	<%
		}//else end
		
	%>

<p align='center'>
<a href="ContactDetails.jsp">View Contacts</a>
</p>

</body>
</html>

Suppose we want to delete Jack Smith so click on the Delete link below that contact

After successful Deletion the message gets displayed

ContactSearchForm.html

This displays an HTML Form with a text box where the user needs to enter the Contact Name he wants to search.

<html>
<head>
<title>My Contacts</title>

</head>

<body>

<h1>Search for a Contact </h1>

<form action='ContactSearchResults.jsp' method='post'>

Enter contact name you want to search: <input type="text" name ="contact_name" /><br /><br />

<input type='Submit' value='Search'/>

</form>

</body>

</html>


Snapshot of Search Form


Enter a Contact Name you want to search

ContactSearchResults.jsp

This page is called as a response to ContactSearchForm.html .  It takes the Contact Name as Parameter and search the required contact from the DB. If found it displays the Contact Detail in Tabular Format.

<%@page import="java.util.*"%>
<%@page import="java.sql.*"%>

<html>

<head><title>My Contacts</title></head>

<body>
<%@include file='Includes/db_connect.jsp'%>
<p align='left'>
<a href="Contact_New.html">Add New Contact</a> | <a href="ContactSearchForm.jsp">Search Contact</a>
</p>

<table cellpadding='10' border='1' align='left'>

<tr>
<td colspan="3" align="center"><h2>Search Results</h2></td>
</tr>

<tr>
	<th>Name</th>
	<th>Mobile</th>
	<th>Email</th>
</tr>
<%
	String contact_name = request.getParameter("contact_name");
	
	String sql = "SELECT * FROM contact_details WHERE name LIKE ?";
	
	PreparedStatement pstmt = con.prepareStatement(sql);
	pstmt.setString(1, contact_name);
	
	ResultSet rs = pstmt.executeQuery();
	
	while(rs.next())
	{
		String name = rs.getString("name");
		String mobile = rs.getString("mobile");
		String email = rs.getString("email");

%>

	<tr>
		<td><%=name%> </td>
		<td><%=mobile%></td>
		<td><%=email%></td>
	</tr>
	
<%
}


rs.close();
rs = null;
pstmt.close();
pstmt = null;
con.close();

%>
</table>
<br /><br /><br /><br /><br /><br />
<p align='left'>
<a href="ContactDetails.jsp">View Contacts</a>
</p>

</body>
</html>

Search Results

Web Based Contact Management System using JSP and MySQL-Part 2

Hi Friends

In the first part we have already seen how to display the Contacts from the Database and How to Add a New Contact.

Here’s the Link for the First Part

Web Based Contact Management System Using JSP and MySQL

In this part we will see

  • Updating an Existing Contact
We will describe the other files that made ContactApp here

Contact_Edit.jsp

This jsp File displays a Form with fields to edit an existing contact. On clicking the Edit link below the Contact in the Main Page this page opens with a form with existing Contact Data. The user can edit the data and click on Save Button. The Contact get updated in the db.

SQL SELECT Statement have been used to fetch the contact details and display in a form to edit it.


<%@page import="java.util.*"%>
<%@page import="java.sql.*"%>

<html>

<head><title>My Contacts</title></head>

<body>
<%@include file='Includes/db_connect.jsp'%>

<form action="Contact_Update.jsp"  name='NewContactForm' method="post">

<table class='login' cellpadding='10' align='center'>

<tr>
<td colspan="2" align="center"><h2>Edit Contact</h2></td>
</tr>

<%

	int contact_id = Integer.parseInt(request.getParameter("contact_id"));

	String sql= "SELECT * FROM contact_details WHERE contact_id = ?";

	PreparedStatement pstmt = con.prepareStatement(sql);
	pstmt.setInt(1, contact_id);

	ResultSet rs = pstmt.executeQuery();

	while(rs.next())
	{
		String name = rs.getString("name");
		String mobile = rs.getString("mobile");
		String email = rs.getString("email");
		int id = rs.getInt("contact_id");

  %>

	<tr>
	<td>Name: </td>
	<td><input type="text" name ="contact_name" value = "<%=name%>"size="40"> </td>
	</tr>

	<tr>
	<td>Mobile: </td>
	<td><input type="text" name ="mobile" value = "<%=mobile%>" size="40"></td>
	</tr>

	<tr>
	<td>Email: </td>
	<td><input type="text" name ="email" value = "<%=email%>" size="40"></td>
	</tr>

	<tr>
	<td colspan="2" align="center"><br/><br/>
	<input type = "hidden" name ="contact_id" value = "<%=contact_id%>"/>
	<input type="Submit" value ="Save">
	<input type="Reset" value ="Reset">
	</td>
	</tr>

	<%
	}//while

rs.close();
rs = null;
pstmt.close();
pstmt = null;
con.close();

%>

</table>

<p align='center'>
<a href="ContactDetails.jsp">View Contacts</a>
</p>

</body>
</html>

Snapshot of the o/p

Contact_Update.jsp

This jsp page takes the parameters from the Contact_Edit.jsp page which displays an HTML Form with fields containing data of an existing contact. When user make changes to the fields and submit the form, the form fields are sent to Contact_Update.jsp. This file then updates the contact details to the DB.
SQL UPDATE Statement has been used to do the updation.

<%@page import="java.util.*"%>
<%@page import="java.sql.*"%>

<html>

<head><title>My Contacts</title></head>

<body>

<%@include file='Includes/db_connect.jsp'%>

<%! boolean success = false; %>
<%
	String contact_name = request.getParameter("contact_name");
	String mobile = request.getParameter("mobile");
	String email = request.getParameter("email");	
	int contact_id = Integer.parseInt(request.getParameter("contact_id"));
	
	String sql= "UPDATE contact_details SET name = ?, mobile = ?, email= ? WHERE contact_id = ?";
	
	PreparedStatement pstmt = con.prepareStatement(sql);
	pstmt.setString(1, contact_name);
	pstmt.setString(2, mobile);
	pstmt.setString(3, email);
	pstmt.setInt(4, contact_id);
	
	int nRows = pstmt.executeUpdate();
	
	if(nRows==0){
		success = false;
	}
	
	else{
		success = true;	
	}
	
	pstmt.close();con.close();

%>
	
	
	<%
			if(success==true){
	%>
	
	<h2>Contact have been successfully updated</h2>
	
	<%
		}//if end
		else{		
	%>
	
	<h2> Error -- Contact could not be updated </h2>
	
	<%
		}//else end
		
	%>

<p align='center'>
<a href="ContactDetails.jsp">View Contacts</a>
</p>

</body>
</html>

Snapshot of the o/p

Snapshot of the Upadated Contacts-Check out Anna Adams Smith

As the post grew really large I will cover Deleting and Searching for a Contact in Part 3 of this Tutorial Series.
Keep Programming Keep Exploring. You can always find better ways to do the same thing.

Web Based Contact Management System Using JSP and MySQL Part 3

Web Based Contact Management System using JSP and MySQL Part 1

Hello people

Here I will show you a web based contact management system using JSP, JDBC and MySQL Database. This is a very simple application to make you clear your basics about building any Web Based Database Application using Java. This Web Application uses JSP and JDBC where a user can create and manage his Contacts online. It’s like an online Contact Book

For running this application you will need Tomcat and MySQL DatabaseYou can customize it to other web server like Glassfish and any other Database.

For using MySQL you need to download the JDBC Driver, you can get the driver from here.

http://www.mysql.com/products/connector/

Extract the JAR file and put it inside the lib directory in the Tomcat directory

This is the JAR FileName- mysql-connector-java-5.1.17-bin.jar

To download the Tomcat visit the below link

http://tomcat.apache.org/download-70.cgi

It is simple web based application where a user can manage his Contacts online.

It contains all the basic Functionalities like

  • Viewing all Contacts at once
  • Adding New Contact
  • Updating an Existing Contact
  • Removing a Contact
  • Searching for an existing Contact

Keep all the files for this application inside a directory called ContactApp (or whatever name you want to give to your application) and keep this inside the webapps directory of Tomcat.

The main purpose of this application is to understand How to use JDBC for creating a web based database application.

Understanding of Java language and JSP is important for this application.

For this application you need a Database Table. I am using MySQL Database that came with WAMP installation on Windows

In MySQL I created a database called contactdb. In that I created a table called contact_details.

You can see the structure of the Table in this screenshot

Now we will give a brief description about all the files that we need for this application

db_connect.jsp

We have separated the Database Connectivity part in another file called db_connect.jsp and included it in the files where we need to connect to the database.

This makes it easier to make any change to the code at a later stage and you don’t have to make a change in every file.

This file is in the Includes directory in ContactApp


<%
	String dbURL = "jdbc:mysql://localhost:3306/contactdb";
	String username = "Annna";
	String password = "MySecretPwd";
	Connection con = DriverManager.getConnection(dbURL, username, password);
%>

ContactDetails.jsp

This is the main page of this application. It shows how to fetch all the records from the data base table and display it on the web page.

SQL SELECT Statement has been used to fetch all the records from the Database Table.

This page displays all the contact details in Tabular Format. Below every contact there is a link for Editing and Deleting the Contact.


<%@page import="java.util.*"%>
<%@page import="java.sql.*"%>

<html>

<head><title>My Contacts</title></head>

<body>

<%@include file='Includes/db_connect.jsp'%>

<p align='left'>
<a href="Contact_New.html">Add New Contact</a> | <a href="ContactSearchForm.jsp">Search Contact</a>
</p>

<table cellpadding='10' border='1' align='left'>

<tr>
<td colspan="3" align="center"><h2>My Contacts</h2></td>
</tr>

<tr>
	<th>Name</th>
	<th>Mobile</th>
	<th>Email</th>
</tr>
<%

	String sql = "SELECT * FROM contact_details ORDER BY name";

	Statement stmt = con.createStatement();
	ResultSet rs = stmt.executeQuery(sql);

	while(rs.next())
	{
		String name = rs.getString("name");
		String mobile = rs.getString("mobile");
		String email = rs.getString("email");
		int id = rs.getInt("contact_id");

%>

	<tr>
		<td><%=name%> <br /><a href='Contact_Edit.jsp?contact_id=<%=id%>'>Edit</a> |

		<a href='Contact_Delete.jsp?contact_id=<%=id%>'>Delete</a>
		</td>
		<td><%=mobile%></td>
		<td><%=email%></td>
	</tr>

<%
}

rs.close();
rs = null;
stmt.close();
stmt = null;
con.close();

%>
</table>

</body>
</html>

Screenshot of this page is here

Adding New Contact-For this you need an HTML Form

Contact_New.html
This is a simple HTML Form that contains fields for a new contact.

<html>
<head>
<title>Add New Contact</title>
</head>

<body>

<form action="Contact_New.jsp"  name="NewContactForm" method="post">

<table class='login' cellpadding='10' align='left'>

<tr>
<td colspan="2" align="center"><h2>Add New Contact</h2></td>
</tr>

<tr>
<td>Name: </td>
<td><input type="text" name ="contact_name" size="40"> </td>
</tr>

<tr>
<td>Mobile: </td>
<td><input type="text" name ="mobile" size="40"></td>
</tr>

<tr>
<td>Email: </td>
<td><input type="text" name ="email" size="40"></td>
</tr>

<tr>
<td colspan="2" align="center"><br/><br/><input type="Submit" value ="Save">
<input type="Reset" value ="Reset"></td>
</tr>

</table>

</form>

</body>
</html>

Snapshot of the Form

Add a New Contact and Click on Save button

Contact_New.jsp
This jsp file takes the form data from Contact_New.html and stores it in the Database Table.
INSERT Functionality has been demonstrated in this file.
SQL INSERT Statement has been used to add the contact to db.


<%@page import="java.util.*"%>
<%@page import="java.sql.*"%>

<html>

<head><title>My Contacts</title></head>

<body>

<%@include file='Includes/db_connect.jsp'%>

<%! boolean success = false; %>
<%
	String contact_name = request.getParameter("contact_name");
	String mobile = request.getParameter("mobile");
	String email = request.getParameter("email");

	String sql= "INSERT INTO contact_details(name, mobile, email) VALUES(?, ?, ?)";

	PreparedStatement pstmt = con.prepareStatement(sql);
	pstmt.setString(1, contact_name);
	pstmt.setString(2, mobile);
	pstmt.setString(3, email);

	int nRows = pstmt.executeUpdate(); //returns the number of rows affected by the query

	if(nRows==0){
		success = false;
	}

	else{
		success = true;
	}

	pstmt.close();con.close();

%>

	<%
			if(success==true){
	%>

	<h2>Contact have been successfully added</h2>

	<%
		}//if end
		else{
	%>

	<h2> Error -- Contact could not be added </h2>

	<%
		}//else end

	%>

<p align='center'>
<a href="ContactDetails.jsp">View Contacts</a>
</p>

</body>
</html>

When the Contact gets added a screen is displayed with the message that the Contact has been added successfully
Snapshot of the o/p

Here is the List of Contacts with the New Contact

As this post grew very large we will continue with Updating, Deleting and Searching for a Contact in the next post.

Hope you enjoyed learning till now. Run this program. Make Changes to the source code and try other methods to do the same thing. Keep Programming because that’s the best you to learn this skill.

Check out the Part 2 of this Tutorial here
Web Based Contact Management System Using JSP and MySQL-Part2

Java Servlet – Key Points

Java Servlet

  • A servlet is a server-side program which executes inside a Web server, such as Apache.
  • It Receives HTTP requests from the client and provides HTTP responses
  • The javax.servleand javax.servlet.http packages provide interfaces and classes for writing servlets.
  • All servlets must implement the Servlet interface, which defines life-cycle methods.
  • When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. TheHttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.