Home / java / First Servlet Program

First Servlet Program

How to write and execute your first Servlet Program in Eclipse Editor.

Create Dynamic Web Project: While creating the Dynamic web Project you have to choose 2.5 Dynamic web module version

DWA 2.5

Application Data Source :

package com.testsevlet;

import java.sql.Connection;
import org.apache.commons.dbcp2.BasicDataSource;

public class ApplicaionDataSource {

	static BasicDataSource data=null;
	static {
		data=new BasicDataSource(); 
	 public static Connection getConnection() throws Exception{
		return data.getConnection();

Servelt :

package com.testsevlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet{
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doPost(req, resp);
		PrintWriter pw = resp.getWriter();
		pw.write("Test Servlet");
		System.out.println("Control inside TestServlet");
			Connection conn  = ApplicaionDataSource.getConnection();		
			java.sql.PreparedStatement ps = conn.prepareStatement("select * from f_user");
			ResultSet rs = ps.executeQuery();
				pw.write("<br />");
		}catch(Exception e){

Run a Servlet Application with IDE Eclipse:

How to clean the Cache of Application before Run
1. Stop the Server
2. Clear Tomcat Work Directory: Right click on servlet you can see the option “Clear Tomcat Work Directory”
3: Clean: Right click on the Mouse you can see “Clean”
4. Project Clear: In IDE click on Project Menu you can see “Clean”.

Make a controller as Landing Page in web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

About Mohammad Fareed

Software Engineer @ Tekzenit.

Check Also

Object Creation in Java

1)How many ways are there to create an object? 1. How many ways to create …

Leave a Reply

Your email address will not be published. Required fields are marked *