Database connection in Servlet

Purpose:

    How to connect your Servlet with Database?

Steps:
1) Create “MyServlet.java”, as servlet file (don’t know how to create a servlet file in Eclipse? Refer to our post: “ Servlet in Eclipse IDE“)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*; // for database purpose
 
public class MyServlet extends HttpServlet
{
	Connection con;
	Statement stmt;
	ResultSet rs;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		response.setContentType("text/html"); // informing the client that which format of data/response will be send
		PrintWriter out= response.getWriter(); 
		
		String name= request.getParameter("num");
		// will retrieve "NUM" field value entered by user using "getParameter()"
		// and store in STRING "name"
		
		try
		{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			con= DriverManager.getConnection("Jdbc:Odbc:dbs123");
			stmt= con.createStatement();
			
			rs=stmt.executeQuery("Select * from Student where s_name= '"+name+"' ");
			// Retrieving all columns from Database where "name" matches
			// Name of table is "Student"
			
			if(rs.next())
			{
				out.println("<h3> Name=</h3>" +rs.getString("s_name")); // Printing Name from Database
				out.println("<br> Address=" +rs.getString("address"));  // Printing Address from Database
			}
			else
			{
				out.println("<h3> ID is not exists</h3>"); // If no such ID found in Database
			}
		}
		catch(Exception e)
		{
			out.println(e);
		}
	}

}

2) Create “index.html”, as HTML file (you can refer: “How to add HTML file in your Servlet Program using Eclipse“)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="MyServlet" method="get">
Enter the ID of Student
<input type="text" name="num"><br> 

<input type="Submit" value="Submit">

</form>
</body>
</html>

3) Create “DBServlet” database file

Design View of database

4) Configure database in Administrative Tools from Control Panel
ODBC –> ADD –> Microsoft Access Driver (*.mdb,*.accdb)

Under “Data Source Name” enter: “dbs123” (as mentioned in Servlet file)
Click on “Select”
from “C” directory, choose appropriate database, i.e “DBServlet.accdb”
Click on “OK”

5) Press “CTRL”+ F11

OUTPUT

Advertisements

How to retrieve a form at Server end using Servlet

Purpose:

    How to retrieve data from various fields of a particular form at Server Side, specially when multiple field names are same

Steps:

1) Create “MyServlet.java”, as servlet file (don’t know how to create a servlet file in Eclipse? Refer to our post: “ Servlet in Eclipse IDE“)

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

public class MyServlet extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		response.setContentType("text/html"); // informing the client that which format of data/response will be send
		PrintWriter out= response.getWriter(); 
		
		String Values[] = request.getParameterValues("num"); 
		// will retrieve all field values entered by user using "getParameterValues()"
		// and store in STRING ARRAY
		
		out.println("<h3> The Values are </br>");
		
		for(int i=0; i<Values.length; i++)
		{
			out.println("<br>" +Values[i]); // print all field values entered by user in form
		}
	}

}

2) Create “index.html”, as HTML file (you can refer: “How to add HTML file in your Servlet Program using Eclipse“)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="MyServlet" method="get">
<input type="text" name="num"><br>  //Field 1 name is "num"
<input type="text" name="num"><br> //Field 2 name is "num"
<input type="text" name="num"><br> 
//Field 3 name is "num". 
//So all 3fields name are same, 
//Let's check whether we be able to retrieve & differentiate data entered by user in these fields.

<input type="Submit" value="Submit">

</form>
</body>
</html>

3) Press “CTRL+F11”

4) Output will be

Enter values in field and click on “Submit” button

HTML + Servlet Program using Eclipse

Purpose:

    How to add a HTML file into your Servlet using Eclipse?

Steps:
1) Create the following Servlet file in Eclipse (don’t know how to create a servlet in Eclipse? Refer to our post: “ Servlet in Eclipse IDE“)

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

public class MyServlet extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		response.setContentType("text/html"); // informing the client that which format of data/response will be send
		PrintWriter out= response.getWriter(); 
		
		//All data entered into a "TEXT" field of form, is stored as "STRING"
		//Hence if we enter "1" in a "TEXT" field of form, it will be stored as "ONE"
		//To convert it to "INT", we use a predefined function called= "parseInt()"
		int a1= Integer.parseInt(request.getParameter("n1")); 
		// using "getParameter()" to retrieve data entered by user in "n1" field
		int a2= Integer.parseInt(request.getParameter("n2")); 
		
		if (request.getParameter("r1")!=null) // checking if 1st radio button checked or not?
		{
			out.println("<h3> Addition= </h3>"+(a1+a2));
		}
		else if(request.getParameter("r2")!=null) // checking if 2nd radio button checked or not?
		{
			out.println("<h3> Subtraction= </h3>"+(a1-a2));
		}
		else if(request.getParameter("r3")!=null) //checking if 3rd radio button checked or not?
		{
			out.println("<h3> Multiply= </h3>"+(a1*a2));
		}
		else
		{
			out.println("<h3> Divide= </h3>"+(a1/a2));
		}		
	}

}

2) Next create a HTML File
Right click on “WebContent” folder –> New –> HTML File

Enter File Name: “index.html” and click on “FINISH” button

3) Now replace the existing “index.html” file code with this

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="MyServlet" method="get">
Enter 1st Number <input type="text" name="n1"><br>
Enter 2nd Number <input type="text" name="n2"><br>

<input type="radio" name="r1" value="Add">Add<br>
<input type="radio" name="r2" value="Subtract">Subtract<br>
<input type="radio" name="r3" value="Multiply">Multiply<br>
<input type="radio" name="r4" value="Divide">Divide<br>
<input type="Submit" value="Submit">

</form>
</body>
</html>

4) Now press “CTRL”+F11, you will get the following screen. Click on “FINISH BUTTON”, selecting WEB SERVER.

5) You will get output

6) Enter two numbers and perform any option like:

Eclipse IDE- Servlet Program

Steps:
You need to follow the following steps in order to create a Servlet in Eclipse:

  • Create a web project
  • Create a Servlet
  • Start Tomcat server and deploy project

Prerequisites:

  1. Eclipse IDE for Java EE Developers(download link)
  2. Apache Tomcat 6.0/7.0(download link , choose “32-bit/64-bit Windows Service Installer” to download from this link and install it by double click on the “.exe” file contained in archive)
  3. Once you are done with installation of Tomcat, remember not to run it at the same instance. As it will get conflicted later with Eclipse, when we deploy our project. Hence make sure that Apache services are stopped

Create a web project:
Select from the menu File –> New –> Dynamic Web Project.

Enter “FirstServlet” as your project name. Click on “NewRuntime” button and select “Apache Tomcat v6.0”.


Click “Next” button.

Click “Next” button.

Click on “Finish” button

Create a Servlet:
Select from the menu File –> New –> Servlet

Write “MyServlet” in the ‘Class Name’ field and then Click ‘Next’ button.

Now in case you want to specify deployment descriptor (web.xml), you can do this here and then Click ‘Next’ button.

Click on “Finish” button

Now you will get something like this

Now remove all that coding and replace it with

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

public class MyServlet extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		response.setContentType("text/html"); // informing the client that which format of data/response will be send
		PrintWriter out= response.getWriter(); 
		out.println("<hr>HELLO SERVLET</h3>"); // printing on the client

	}

}

Start Tomcat server and deploy project:
Right click on the project ‘FirstServlet’ and select from context menu ‘Run As’ –> ‘Run on Server’

Select the existing tomcat server
Click “Finish” button.
FirstServlet will get deployed.

OR
Press CTRL+F11, to run web application,

Click “Finish” button.
And you will see the output as

Command Line Arguments

Define: When a java program is launched from a terminal window, you can provide the program with either zero or more command-line-arguments.
Normally all values which user passes at the time of executing any java program, these values get stored in an array, “String args[]”.

Program:

public class CommandLineDemo
{
	public static void main(String args[])
	{
		System.out.println();
		for(int i=0; i<args.length; i++)
		{
			System.out.println("Value" +i+ "=" +args[i]);
		}
	}

}

Output:

Explanation: So here in above cmd snapshot

    javac CommandLineDemo.java 
// user has first compiled the java program

    java CommandLineDemo 1 2 3 
// then during execution, user passes 3 values as 1,2,3

Now here

for(int i=0; i<args.length; i++) 
// we are running "for loop" till the length of array, which is here 3 (as 3 values passed by user in CMD)
{ 	System.out.println("Value" +i+ "=" +args[i]); 
//Printing all 3 values of array, one by one
}

Thus the output is

Value 0=1
Value 1=2
Value 2=3

Java Introduction

Java History
1) Founder was James Gosling
2) Develop by Sun Microsystems in 1991
3) This language was initially called “Oak”, later renamed as “Java” in 1995

  • Basically, there was a need to create a platform-independent language that could be used to create software to be embedded in various consumer electronic devices, such as microwave, remote controls etc.
  • Now the trouble at that time with C, C++ was that they were designed to be compiled for a specific target.
  • Although it is possible to compile a C++ program, for just about any type of CPU, but to do so requires a full C++ compiler targeted for that CPU and which is expensive and time-consuming to create.

Versions of Java

  • JDK 1.0
  • JDK 1.1
  • J2SE 1.2
  • J2SE 1.3
  • J2SE 1.4
  • J2SE 5.0
  • Java SE 6
  • Java SE 7
  • Java SE 8
  • Java 9

Java programming language platforms

  1. Java FX
  2. Java ME (Java platform, Micro Edition)
  3. Java EE (Java Platform, Enterprise Edition)
  4. Java SE (Java Platform, Standard Edition)

Note: All Java platforms consists of a JVM (Java Virtual Machine) and an Application Programming Interface (API)

  • JVM: Is a program for a particular h/w and s/w platform, that runs Java technology applications
  • API: An API, in very simple terms, is the definition of what can be done programmatically with a particular application. So API here in Java is a collection of s/w components that you can use to create other s/w applications.

1) Java SE

  • When most people think of Java programing language, they think of the Java SE API.
  • Java SE API, defines everything from the basic types and objects of Java programming language to high-level classes that are used for networkingm security, database access, GUI development and XML parsing.

NOTE: Java SE comes in two types:-

  • JDK (Java Development Kit)- contains Java compiler, JDK allows you to compile and run Java from source code.
  • JRE (Java Runtime Environment)- JRE only allows the running of Java Bytecode, source that has already been compiled.

2) Java EE

  • Java EE platform is built on top of Java SE platform
  • It mainly allows development and running of web applications

3) Java ME

  • It provides an API & a small-footprint virtual machine for running Java programming language applications on small devices like mobile phones.
  • Java ME API is a subset of Java SE API, along with special class libraries useful for small device application development.

4) Java FX

  •  Java FX is a platform for creating rich internet applications using a light weight user-interface API.
  •  Java FX applications use hardware accelerated graphics

Difference between JDK, JRE and JVM

Java Development Kit
JDK contains tools needed to develop Java Program. These tools contain compiler (Javac.exe), Java application launcher (Java.exe), AppletViewer etc.

  • Java compiler converts Java code into Bytecode
  • Java application launcher opens a JRE, loads the class and invoke its main method

Java Runtime Environment

  • JRE contains JVM+ Java package classes (like util, math, lang, awt, swing etc)
  • Does not contains any development tools like compiler, debbuger etc.
  • For running java programs, JRE is used.

Java Virtual Machine

  • When a Java file compiles, its output is not an .EXE file, but a .CLASS file (which consists of Java Bytecodes, which only understandable by JVM)
  • So JVM act as an interpreter to convert ByteCode into Executable File

FUNDA: You need JDK, if all you want to write your own programs, and to compile them. For running java programs, JRE is sufficient.