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

Multiplication Table in Java

This is a very basic program But for a beginner it is worth trying.

And it also makes us aware about the power of for loop which can repeat so many times within a second.

public class MulTable
{
	public static void main(String[] args)
	{
		int i;
		int num = 9;
		for(i=1; i<=10; i++)
		{
			System.out.println(num+ " * " +i+ " = "+num * i);
		}
	}
}

Snapshot of the o/p