0% found this document useful (0 votes)
44 views106 pages

J2EE

The document discusses J2EE, its components like JDBC, Servlet and JSP. It also discusses abstraction, abstract classes and interfaces. It then talks about parameters, arguments, methods and their characteristics. Finally, it covers design patterns, factory design pattern and how to create objects using factories.

Uploaded by

samdetect41
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views106 pages

J2EE

The document discusses J2EE, its components like JDBC, Servlet and JSP. It also discusses abstraction, abstract classes and interfaces. It then talks about parameters, arguments, methods and their characteristics. Finally, it covers design patterns, factory design pattern and how to create objects using factories.

Uploaded by

samdetect41
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 106

J2EE

1. J2EE stands for Java 2 Enterprise Edition where ‘2’ stands for version.

2. J2EE is used for the simplification of web application development.

3. Follo. Are the components of J2EE.

i) JDBC(Java Database Connectivity)

ii) Servlet

iii) JSP (Java Server Pages)

Abstraction

The process of hiding the implementation by providing the necessary functionality.

We can achieve abstraction with the help of

1. Interface
2. Abstract class

Abstract class

A class which is prefixed with abstract keyword.

Characteristics of abstract class

1. We cannot create object for abstract class.


2. Inside an abstract class we can have both concrete methods as well as abstract methods.
3. Inside an abstract class we can have a static variables, Non-static variable, blocks,
constructors, etc.
4.
5. Cannot create object because it will be incomplete.

Q. Can we override static methods? //No

Q. Can we make static methods abstract? //No

Q. Can we make a constructor private? //Yes

Q. Can we make a constructor final? //No


Interface

 It is a component in Java which is used to achieve 100% abstraction and multiple inheritance.
 It is a medium which is used to connect 2 applications (It is a medium of communication
between service provider and service user)

Note:

We cannot create an object for interface.

Members we can declare in an interface

1. Static final variable


2. Abstract method-(Non-static)
3. From JDK8 onwards inside an interface we can declare static and default methods.

Q. Define a method which can accept a no. and check whether it is Even or odd.

Import java.util.Scanner;

class EOO

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

int n=sc.nextInt();

boolean rs=isBoolean(n);

if(rs==true)

System.out.println(n+“ is Even”);

else

System.out.println(n+“ is Odd”);

static boolean isBoolean(int n)

int n;

if(n%2==0)

return true;

else

return false;

}}
Q. Define a method which can accept the reference of book and print its attributes.

class EBook

String title=”Binge”;

String author=”Stephen”;

double price=540.0;

Book(String title,String author,double price)

this.title=title;

this.author=author;

this.price=price;

}}

-class printDetails

public static void main(String[] args)

Book a = new Book(“J2EE”, “Philips”, 300);

Book b = new Book(“Framework”, “Stephen”, 450);

printDetails(a);

printDetails(b);

public static void printDetails(Book a)

System.out.println(“Title: ”+a.title);

System.out.println(“Author: ”+a.author);

System.out.println(“Price: ”+a.price);

}}

18/01/2023

Coupling

The dependency between two objects or two classes or two interfaces.


1. Tight Coupling
2. Loose Coupling

Tight Coupling

Change in the implementation affects the user then it is Tight Coupling.

Loose Coupling

Change in the implementation does not affect the user then it is Loose Coupling.

Method

It is a block of instruction which is used to perform a particular task.

Note:

-A method can accept the reference of an object.

Q.

class Laptop

int ram, storage;

String brand;

double price;

static void printDetails(int ram, int storage, String brand, double price)

this.ram=ram;

this.storage=storage;

this.brand=brand;

this.price=price;

}}

-class TestLaptop

static void main(String[] args)

Laptop l1=new Laptop(4,1,”HP”,50000);

Laptop l1=new Laptop(8,1,”Dell”,55000);

Laptop l1=new Laptop(8,1,”Mac”,60000);

printDetails(l1);
printDetails(l2);

printDetails(l3);

static void printDetails(Laptop laptop)

System.out.println(“Ram : ”+laptop.ram);

System.out.println(“Storage : ”+laptop.storage);

System.out.println(“Brand : ”+laptop.brand);

System.out.println(“Price : ”+laptop.price);

System.out.println(“-----------------------------------“);

}}

19/01/2023

Note:

-A method can return the reference of an object.

-Implementation class of Iterator is Itr.

Ex.

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

class Demo

public static void main(String[] args)

list<Integer> nums = new ArrayList<>();

iterator<Integer> I = nums.iterator();

-In the above example iterator() is a method which is implemented in ArrayList and it will create the
implementation object of java.util.Iterator and returns the reference.
-We cannot create the object of an interface so if we want to call the methods of an interface then
we must create the implementation object of an interface.

Ex.

interface Vehicle

@Override

void start();

System.out.println(“Bike has been Started”);

-class testVehicle

public static void main()String[] args)

Vehicle v = new Bike():

v.start();

20/01/23

Design Pattern

It is an optimised solution for different types of re-occurring designs.

We have 2 types of design patterns

1. Relational Design Pattern


2. Factory Design Pattern

Relational Design Pattern

It is used to write object creation logic.

Ex. Singleton Design Pattern

Factory Design Pattern

It is used to create different object of the same type.

Note: In factory design pattern we will have a Hesper method or factory method. Which will take
string as argument and produces the object and return the reference.
Parameter

Parameter is used to represent the type of argument or it is used to hold the argument.

Argument

It is the value passed for the method whenever we call it.

Ex. bike Vehicle Bike Object

Factory
Bike Car

For factory design pattern we need to write 3 types of logic

1. Implementation Logic
2. Object Creation Logic
3. Utilisation Logic

Implementation Logic: It is used to provide the implementation.

Object Creation Logic: It is used to create the object for implemented classes.

Utilisation Logic: This logic is written to access the functionality

Without Utilisation logic there is no use from other 2 types of logic

Ex. package org.jsp;

public interface Vehicle {

void Start();

-package org.jsp;

public class Bike implements Vehicle

@override

public void start()

System.our.println(“Bike has been Started”);

public class Car implements Vehicle

{
@override

public void start()

System.our.println(“Car has been Started”);

public class VehicleFactory

public vehicle getVehicle(String type)

if(type.equals(“Bike”))

return newBike();

else if(type.equals(“Car”))

return new Car();

else

System.out.println(type+“ Vehicle is not Available”);

return null;

-package org.jsp;

import java.util.Scanner;

public class TestVehicle

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

System.out.println(“Tell me what type of vehicle you want”);

String type = sc.nextInt();

VehicleFactory factory = new VehicleFactory();

Vehicle v = factory.getVehicle(type);

If(v!=null)
v.start();

}}

21/01/23

class VehicleFactory

public Vehicle getVehicle(String type)

return new Bike();

return new Car();

return null;

class Bike implements vehicle

void Start()

@override

System.out.println("Bike has been Started ");

JAR (Java Archieve)

It is a compressed file format which is similar to zip file format. It is used to compress different types
of files together.

Contents of a JAR

.java (Source Code) -> Optional

.class (ByteCode or Executable Code)

.xml

.properties (To store the config data in the form of key=value pairs. Where key should be unique.)
Config (It is used to store the configuration files).

Extensive Markup language (XML)

Used to config the resources with the help of customised tags or User defined tags.

Steps to create a JAR file

1. Click on file and select the export option.

2. Select Java and JAR file.

3. Now Select the project which you want to compress and click on browse.

4. Browse the directory where you want to export the JAR file.

5. Name the JAR file and click on save.

Need for a JAR file

To import the properties of a resource we need a JAR file. We can add JAR file into Java build path in
two ways

1. Externally - might affect project

2. Internally - won’t affect project

Steps to add a JAR file into he build path externally

1. Right click on your project and select properties.

2. Select Java Build Path and click on libraries tab.

3. Select the class Path and click on add external JAR and browse the directly where JAR file is
present.

4. Select the JAR file and click on open.

Steps to add a JAR file into he build path internally

1. Right click on your project and create a folder with the name lib.

2. Copy the JAR file and paste it in lib folder.

3. Add the JAR file into the Build Path.

-Steps to add the JAR file into Build Path

3.1 Right click on project and select properties option.

3.2 Select Java Build Path and click on libraries tab.

3.3 Click on AddJARS and browse the lib folder where the JAR file is present.

3.4 Select the JAR file and click on open.


Assignment

Design the Factory for the follo requirement

JDBC

 It is a specification provided in the form of abstraction API which is used to achieve loose
coupling between java application and the database server.

24/01/23

Creational design pattern

Factory design pattern

Class loading process

The process of loading a .class file into JVM memory. We can load a class into the JVM memory in
two ways.

1. By calling the member of a class like variable, constructor or method.


2. By using a method for name String fully qualified class farName (FrCN) which is a static
method present in java.lang class.

Loading a class into JVM memory by calling a member of the class

-Test.java

class test

static {

System.out.println(“Test Class has been loaded”);

public static void main(String[] args)

-Demo.java

class Demo

static

{
System.out.println(“Demo class is loaded into JVM memory”);

public static void main(String[] args)

System.out.println(“Main Starts”);

test.name = “ABC”;

System.out.println(“Main Ends”);

Loading a class into JVM memory with the help of ForName.

ForName method throws a checked exception called as ClassNotFoundException, so we must either


handle or declare ClassNotFoundException.

-package.org.btm;

class Student

static {

System.out.println(“Student has been loaded into JVM memory”);

-package.org.jsp;

class ClassRoom

static {

System.out.println(“ClassRoom has been loaded into JVM memory”);

public static void main(String[] args) {

try {

Class.forName(“org.btm.Student”);

catch(ClassNotFoundException e) {
System.out.println(“Invalid Class Name”);

e.printStackTrace();

}}

25/01/23

URL (Uniform Resource Locator)

It is the exact path for a resource in the server.

Different parts of URL

1. Protocol
2. Domain Name / Host + Port Number
3. Resource

Protocol

Out of many we use 2 types of protocols

1) http (Hyper Text Transfer Protocol)


2) https (Hyper Text Transfer Protocol Secure)

Host

It is a platform to execute an application.

We have 2 types of Host

1) Local Host
2) Remote Host

Local Host

It is used to execute an application within a system.

Remote Host

If we use this we can execute the application in more than 1 system.

Port Number

It is a unique identification number to connect with a particular server.

The port number to connect with different database servers are as follows:

MySQL - 3306

Oracle - 1521

Standard way to write a JDBC URL

Protocol: SubProtocol: // localhost: portNumber / databaseName (Optional)

URL to connect with MySQL database server


jdbc: mysql: //localhost:3306/database

JDBC

It is a specification which has been given in the form of abstraction API which is used to achieve loose
coupling between java application and the database server.

JDBC Driver (or) Driver Software

 It is the implementation of JDBC.


 JDBC driver is given by database vendor.
 If we want to connect with a database server from java application then we need JDBC API
as well as JDBC driver.

Specifications of JDBC

1. Every JDBC Driver should have a Driver class which is implementing java.sql.Driver interface.

26/01/23

2. Every Driver class should have 1 static block mandatorily in it.


3. Every Driver class should be registered with JDBC API.

Steps to Create a JDBC application

1) Load and register driver.


Driver class provided by database vendor which is the part of JDBC.
2) Establish the connection between Java application and Database server.
3) Create a ‘Statement/Platform’.
4) Execute the query.
5) Process the result (Optional).
6) Close all the costly resources.

Costly resource

 Any resource which uses the system properties in the form of stream.
 All the costly resources must be closed once the task is completed.
 If we don’t close the costly resource then the efficiency of the application will decrease.

Note: All the interfaces of JDBC API are costly resources.

Steps to download MySQL connector

1. Open the browser.


2. Search Maven Repository.
3. Open mvnrepository.com.
4. Search MySQL connector Java.
5. My-sql connector java (2nd option).
6. Click on 8.0.28.
7. Download JAR file (size 2.4 MB).

27/01/23

Driver Interface
 It is an interface belong to JDBC API.
 It belongs to java.sql package.

Driver Class

 It is the implementation class provided by Database Vendor.


 This class is implementing java.sql.Driverinterface.

Driver Software/JDBC Driver

 It is the implementation of JDBC provided by Database Vendor.


 This will have the implantation for all the interfaces of JDBC API.

Load And Register The Driver (Driver class)

JDBC driver

We can load and register the driver in 2 ways

1. Manually
2. Using forName

Code to load and register the driver manually

import java.sql.DriverManager;

import java.sql.SQLException;

import com.mysql.cj.jdbc.Driver;

class LoadAndRegisterDemo

public static void main(String[] args)

try{

Driver d = new Driver();

DriverManager.registerDriver(d);

System.out.println(“Driver is loaded and registered”);

} catch (SQLException e) {

e.printStackTrace();

Output:
31/01/23

Note:

The above way of loading and registering the driver will result in tight coupling.

Step 1: Loading and registering the driver with the help of forName method.

Ex.

class TestLoadAndRegister

public static void main(String[] args)

try{

Class.forName(“com.mysql.cj.jdbc.Driver”);

System.out.println(“Driver is loaded and Registered”);

}catch (ClassNotFoundException e) {

System.out.println(“Invalid Driver Class Name”);

e.printStackTrace();

Output:

Step 2: Establish the connection between Java Application and database server.

1. Required Components: URL: jdbc: mysql//localhost:3306


2. User: root
3. Password: *************

01/02/23

java.sql.DriverManager

1. It is a helper class present in JDBC API.


2. DriverManager have 2 important static methods.
a. registerDriver(Driver)
b. getConnection()

getConnection

It is a helper method or factory method present in java.sql.DriverManager.


It is a static method which will create the implementation object of java.sql.Connection and returns
the reference.

So, the written type of getConnection is Connection.

This method is overloaded. Follo are the different types of getConnection() method.

1. getConnection(String url)

getConnection(String url, “ String user, String password, String password”

It is an interface present in JDBC API the implementation for connection is provided by vendors as a
part of JDBC Driver.

Note: All the costly resources must be closed in finally block by using if condition to avoid
NullPointerException.

Ex.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

class TestEstablishConnection

Public static void main(String[] args)

Connection con = null;

Try{

Class.forName(“com.sql.cj.jdbc.Driver”);

System.out.println(“Driver is loaded and Registered”);

con =DriverManager.getConnection(“jdbc:mysql://localhost:3306”,”root”,”password”);

System.out.println(“Connection has been Established”);

catch(ClassNotFoundException| SQLException e)

e.printStackTrace();

} finally

if(con!=null)
{

try {

con.close();

System.out.println(“Connection is closed”);

catch (SQLException e)

e.printStackTrace();

02/02/2023

Step 3: Create a statement or platform.

We need to create a platform to execute the sql queries.

We have different types of platforms available like java.sql.Statement, java.sql.PreparedStatement


and java.sql.CallableStatement.

Java.sql.connection is the factory for the statement()

CreateStatement()

It is a factory method or helper method present in java

This method will create the implement object of java.sql.Statement and returns the reference.

So the returntype of this method is Statement.

Ex.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class CreateStatement

{
public static void main(String[] args)

Connection con = null;

Statement st = null;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306","root",
"ankush.rana11");

System.out.println("Connection has been established");

st = con.createStatement();

System.out.println("Platform Created");

catch(ClassNotFoundException | SQLException e)

e.printStackTrace();

finally

if(con!=null)

try

con.close();

System.out.println("Connection is closed");

catch (SQLException e)

{
e.printStackTrace();

if(st!=null)

try

st.close();

System.out.println("Statement is closed");

catch (SQLException e)

e.printStackTrace();

3/02/23

Step 4: Execute the query

 We can execute the query by using

execute() , executeUpdate() , executeQuery()

 We can access these methods by using Statement or PreparedStatement or


CallableStatement interface.

execute():

 This method is used to execute any type of SQL query (Generic for all types of queries like
DDL, DML, DQL).
 The returntype of this method is boolean.
 It returns true if we execute DQL queries and returns false for if we execute other types of
query.
Method Declaration: public boolean execute(String query)

Syntax to call: st.execute(“Generic SQL queries”);

executeUpdate():

 This method is specific to execute only DML queries.


 The returntype of this method is int.
 It returns integer value based on the no. of rows affected due to a particular query.

Method Declaration: public int executeUpdate(String dmlquery)

Syntax to call: st.executeUpdate(“Specific DML queries”);

executeQuery():

 This method is specific to execute only DQL queries.


 The returntype of this method is ResultSet.
 This method returns the reference of resultSet.
 If we execute any query other than DQL it throws SQLException.

Method Declaration: public ResultSet executeQuery(String dqlquery)

Syntax to call: st.executeQuery(“Only DQL query”);

Code to create the user table with the help of Statement interface

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class CreateTable

public static void main(String[] args)

Connection con = null;

Statement st = null;

String query="create table user (id int not null, name varchar(45) null,
phone bigint(20) null, primary key(id))";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");


con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo","root",
"ankush.rana11");

System.out.println("Connection has been established");

st = con.createStatement();

System.out.println("Platform Created");

boolean res=st.execute(query);

System.out.println(res+" is the returned value");

catch(ClassNotFoundException | SQLException e)

e.printStackTrace();

finally

if(con!=null)

try

con.close();

System.out.println("Connection is closed");

catch (SQLException e)

e.printStackTrace();

if(st!=null)

try
{

st.close();

System.out.println("Statement is closed");

catch (SQLException e)

e.printStackTrace();

04/02/23

Code to insert a record into user table

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class UserInsertion

public static void main(String[] args)

Connection con = null;

Statement st = null;

String query="insert into user values(1,'balli',928465007)";

try {
Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo","root",
"ankush.rana11");

System.out.println("Connection has been established");

st = con.createStatement();

System.out.println("Platform Created");

int rs = st.executeUpdate(query);

System.out.println(rs+" no. of rows is affected and record is inserted");

catch(ClassNotFoundException | SQLException e)

e.printStackTrace();

finally

if(con!=null)

try

con.close();

System.out.println("Connection is closed");

catch (SQLException e)

e.printStackTrace();

if(st!=null)
{

try

st.close();

System.out.println("Statement is closed");

catch (SQLException e)

e.printStackTrace();

06/02/23

Code to update a record into user table

Query to update

Syntax: “Update user set name=’Name’, phone=Any where id = int”

Ex.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class UpdateUser

public static void main(String[] args)


{

Connection con = null;

Statement st = null;

String query="update user set name='Rocky',phone=123 where id=131";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo","root",
"ankush.rana11");

System.out.println("Connection has been established");

st = con.createStatement();

System.out.println("Platform Created");

int rs = st.executeUpdate(query);

System.out.println(rs+" no. of rows is affected and record is inserted");

catch(ClassNotFoundException | SQLException e)

e.printStackTrace();

finally

if(con!=null)

try

con.close();

System.out.println("Connection is closed");

}
catch (SQLException e)

e.printStackTrace();

if(st!=null)

try

st.close();

System.out.println("Statement is closed");

catch (SQLException e)

e.printStackTrace();

Code to delete a code from the user table using statement interface:

Syntax: delete from ‘table_name’ where id = ‘number’;

Ex.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class DeleteUser


{

public static void main(String[] args)

Connection con = null;

Statement st = null;

String query="delete from user where id=131";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo","root",
"ankush.rana11");

System.out.println("Connection has been established");

st = con.createStatement();

System.out.println("Platform Created");

int rs = st.executeUpdate(query);

System.out.println(rs+" no. of rows is deleted");

catch(ClassNotFoundException | SQLException e)

e.printStackTrace();

finally

if(con!=null)

try

con.close();
System.out.println("Connection is closed");

catch (SQLException e)

e.printStackTrace();

if(st!=null)

try

st.close();

System.out.println("Statement is closed");

catch (SQLException e)

e.printStackTrace();

Create a new Table:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;
import java.sql.Statement;

public class UpdatePercentTable

public static void main(String[] args)

Connection con = null;

Statement st = null;

String query="update percentage set name='Rocky',phone=123 where id=1";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo","root", "ankush.rana11");

System.out.println("Connection has been established");

st = con.createStatement();

System.out.println("Platform Created");

int rs = st.executeUpdate(query);

System.out.println(rs+" no. of rows is updated");

catch(ClassNotFoundException | SQLException e)

e.printStackTrace();

finally

if(con!=null)

try

con.close();
System.out.println("Connection is closed");

catch (SQLException e)

e.printStackTrace();

if(st!=null)

try

st.close();

System.out.println("Statement is closed");

catch (SQLException e)

e.printStackTrace();

07/02/23

What will happen if we execute DQL query

If we execute a DQL query we might get a result which is referred as Resultant data (or) processed
data, which is present in Cursor memory (or) Buffer memory.

We can fetch the Resultant data with the help of java.sql.ResultSet interface.

We can create the implementation object of ResultSet with the help of 2 methods:

1. getResultSet():
It is a helper method present in statement interface.
It will create the implementation object of java.sql.ResultSet and returns the reference.
So the returntype of this method is ResultSet.
2. executeQuery():
This method is specific to execute only DQL queries.
The returntype of this method is ResultSet.
This method returns the reference of resultSet.
If we execute any query other than DQL it throws SQLException.

java.sql.ResultSet:

 It is an interface present in JDBC API.


 The implementation is provided by database vendor as a part of JDBC Driver.
 We can fetch the data with the help of a method get***().
 get***() is overloaded.

We have 2 overloaded methods:

 get***(int column_Index)
 get***(String column_label)

next():

This method is used to check whether a record is present in the cursor memory or not.

Of the record is present it will return true else returns false.

Note:

 Column_name can also be called as column_label.


 Column_number can also be called as column_index.

08/02/23

If the datatype is long we will have the follo get method

1. getLong (int)
2. getLong (String) -> returntype = long

If the datatype is String

1. getString (int)
2. getString (String) -> returntype = String

If datatype is double

1. getDouble (int)
2. getString (String) -> returntype = String

Program to fetch the data from table

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.Statement;

public class FetchUser

public static void main(String[] args)

Connection con = null;

Statement st = null;

ResultSet rs = null;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo","root",
"ankush.rana11");

System.out.println("Connection has been established");

st = con.createStatement();

System.out.println("Platform Created");

rs = st.executeQuery("Select * from user");

while(rs.next())

System.out.println(rs.getInt("id")+" "+rs.getString(2)+" "+rs.getLong(3));

catch(ClassNotFoundException | SQLException e)

e.printStackTrace();

finally

if(con!=null)
{

try

con.close();

System.out.println("Connection is closed");

catch (SQLException e)

e.printStackTrace();

if(st!=null)

try

st.close();

System.out.println("Statement is closed");

catch (SQLException e)

e.printStackTrace();

if(rs!=null)

try

rs.close();

System.out.println("ResultSet Closed");
}

catch(SQLException e)

e.printStackTrace();

09/02/23

Code to insert multiple records using statement interface

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class InsertMultipleRecords

public static void main(String[] args)

Connection con = null;

Statement st = null;

String qry1="insert into user values(4,'Ding',999)";

String qry2="insert into user values(5,'Dong',888)";

String qry3="insert into user values(6,'Doom',777)";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");


con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo","root",
"ankush.rana11");

System.out.println("Connection has been established");

st = con.createStatement();

System.out.println("Platform Created");

st.executeUpdate(qry1);

st.executeUpdate(qry2);

st.executeUpdate(qry3);

System.out.println("Records Inserted Successfully");

catch(ClassNotFoundException | SQLException e)

e.printStackTrace();

finally

if(con!=null)

try

con.close();

System.out.println("Connection is closed");

catch (SQLException e)

e.printStackTrace();

if(st!=null)
{

try

st.close();

System.out.println("Statement is closed");

catch (SQLException e)

e.printStackTrace();

Note: When we insert multiple records using statement interface the query will be compiled multiple
times. This will decrease the efficiency.

Using preparedStatement we can write dynamic queries which can be compiled only once and can be
executed multiple times.

PlaceHolder

It is a parameter which is used to hold dynamic values during from the user during execution.

Placeholder is represented by a symbol ‘?’.

09/02/23

Rules to use a PlaceHolder

1. We should assign the values for the PlaceHolder before the execution of the query.
2. The number of values must be same as the number of PlaceHolders.
3. We can assign the value for PlaceHolder using a method set***(int index, ***value).

String inqry = “insert into user values(?, ?, ?)”;

String upqry = “update user set name=?, phone=? where id=?”;

String delqry = “delete from user where id=?”;


java.sql.PreparedStatement/pre-compiled Statement/Parameterized Statement

 It is an interface present in JDBC API.


 It is a sub-interface of java.sql.Statement interface.
 All the methods of Statement interface are inherited in PreparedStatement.
 Using PreparedStatement we can execute dynamic queries because it supports PlaceHolder.
 In PreparedStatement the query gets compiled during the creation of Statement, so it can
also be called as Pre-Compiled Statement.
 Using PreparedStatement interface we can compile the query once and execute that query
any number of times.

Code to insert multiple records using PreparedStatement Interface

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

public class InsertMultipleRecordsUsingPreparedStatement {

public static void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;

String qry = "insert into user values(?,?,?)";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

System.out.println("Connection has been established");

pst = con.prepareStatement(qry);

pst.setInt(1, 7);

pst.setString(2, "A");

pst.setLong(3, 99);

pst.executeUpdate();

pst.setInt(1, 8);
pst.setString(2, "B");

pst.setLong(3, 9999);

pst.executeUpdate();

pst.setInt(1, 9);

pst.setString(2, "c");

pst.setLong(3, 9999);

pst.executeUpdate();

System.out.println("Records Inserted Successfully");

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

}
}

11/02/23

Code to Insert a record using prepared statement (User)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.util.Scanner;

public class InsertUserInputPreparedStatement {

public static void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;

System.out.println("Enter the Id, name and Phone ");

Scanner sc = new Scanner(System.in);

int id = sc.nextInt();

String name = sc.next();

long phone = sc.nextLong();

String qry = "insert into user values(?,?,?)";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

System.out.println("Connection has been established");

pst = con.prepareStatement(qry);

pst.setInt(1, id);

pst.setString(2, name);
pst.setLong(3, phone);

pst.executeUpdate();

System.out.println("Records Inserted Successfully");

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

Code to Update a record using prepared statement (User)

import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.util.Scanner;

public class UpdateUserInputPreparedStatement {

public static <sys> void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;

String qry = "update user set name=?, phone=? where id=?";

Scanner sc = new Scanner(System.in);

System.out.println("Enter the Existing Id");

int id = sc.nextInt();

System.out.println("Enter the name and phone to Update");

String name = sc.next();

long phone = sc.nextLong();

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

System.out.println("Connection has been established");

pst = con.prepareStatement(qry);

pst.setInt(3, id);

pst.setString(1, name);

pst.setLong(2, phone);

pst.executeUpdate();

System.out.println("Records Inserted Successfully");

} catch (ClassNotFoundException | SQLException e) {


e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

Code to Delete a record using prepared statement (User)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.util.Scanner;
public class DeleteUserInputPreparedStatement {

public static void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;

System.out.println("Enter the Id ");

Scanner sc = new Scanner(System.in);

int id = sc.nextInt();

String qry = "delete from user where id=?";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

System.out.println("Connection has been established");

pst = con.prepareStatement(qry);

pst.setInt(1, id);

pst.executeUpdate();

System.out.println("Records Inserted Successfully");

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

}
if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

Code to Fetch a record using prepared statement (User)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Scanner;

public class FetchUserInputPreparedStatement {

public static void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;

ResultSet rs = null;

System.out.println("Enter the Id ");

Scanner sc = new Scanner(System.in);

String qry = "Select * from user where id=?";


int id = sc.nextInt();

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

System.out.println("Connection has been established");

pst=con.prepareStatement(qry);

pst.setInt(1, id);

rs=pst.executeQuery();

while(rs.next())

System.out.println(rs.getInt("id")+" "+rs.getString(2)+" "+rs.getLong(3));

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();
}

if (rs != null) {

try {

rs.close();

System.out.println("ResultSet is closed");

} catch (SQLException e) {

e.printStackTrace();

Code to Fetch a record using prepared statement (User) by name

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Scanner;

public class FetchUserInputPreparedStatementName {

public static void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;

ResultSet rs = null;

System.out.println("Enter the Name ");


Scanner sc = new Scanner(System.in);

String qry = "Select * from user where name=?";

String name = sc.next();

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

System.out.println("Connection has been established");

pst=con.prepareStatement(qry);

pst.setString(1, name);

rs=pst.executeQuery();

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString("name")+"
"+rs.getLong(3));

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");
} catch (SQLException e) {

e.printStackTrace();

if (rs != null) {

try {

rs.close();

System.out.println("ResultSet is closed");

} catch (SQLException e) {

e.printStackTrace();

Code to Fetch a record using prepared statement (User) by phone

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Scanner;

public class FetchUserInputPreparedStatementPhone {

public static void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;


ResultSet rs = null;

System.out.println("Enter the Name ");

Scanner sc = new Scanner(System.in);

String qry = "Select * from user where phone=?";

Long phone = sc.nextLong();

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

System.out.println("Connection has been established");

pst=con.prepareStatement(qry);

pst.setLong(1, phone);

rs=pst.executeQuery();

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getLong("phone"));

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {
pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

if (rs != null) {

try {

rs.close();

System.out.println("ResultSet is closed");

} catch (SQLException e) {

e.printStackTrace();

Code to Delete a record using prepared statement (User) by name

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.util.Scanner;

public class DeleteUserInputPreparedStatementName {

public static void main(String[] args) {

Connection con = null;


PreparedStatement pst = null;

System.out.println("Enter the name ");

Scanner sc = new Scanner(System.in);

String name = sc.next();

String qry = "delete from user where name=?";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

System.out.println("Connection has been established");

pst = con.prepareStatement(qry);

pst.setString(1, name);

pst.executeUpdate();

System.out.println("Records Inserted Successfully");

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();
System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

Code to Delete a record using prepared statement (User) by phone

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.util.Scanner;

public class DeleteUserInputPreparedStatementPhone {

public static void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;

System.out.println("Enter the Phone ");

Scanner sc = new Scanner(System.in);

long phone = sc.nextLong();

String qry = "delete from user where phone=?";

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");
System.out.println("Connection has been established");

pst = con.prepareStatement(qry);

pst.setLong(1, phone);

pst.executeUpdate();

System.out.println("Records Inserted Successfully");

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

Code to Fetch a record using prepared statement (User) by id and phone


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Scanner;

public class FetchUserInputPreparedStatementIDAPhone {

public static void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;

ResultSet rs = null;

System.out.println("Enter the Id and Phone ");

Scanner sc = new Scanner(System.in);

String qry = "Select * from user where id=? and phone=?";

int id = sc.nextInt();

long phone = sc.nextLong();

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("Driver is loaded and Registered");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

System.out.println("Connection has been established");

pst=con.prepareStatement(qry);

pst.setInt(1, id);

pst.setLong(2, phone);

rs=pst.executeQuery();

while(rs.next())

System.out.println(rs.getInt("id")+" "+rs.getString(2)+"
"+rs.getLong("phone"));
} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

if (rs != null) {

try {

rs.close();

System.out.println("ResultSet is closed");

} catch (SQLException e) {

e.printStackTrace();

}
}

14/02/23

Batch execution

 Each call to the database is considered as a costly operation.


 The more no. of DB calls will result in decrease in efficiency of the application.
 So, we can make a single DB call by collecting all the queries into one single batch.

Batch

 Batch is a collection of only DML queries.


 We can add more than one DML query into a single batch and make a single DB call.
 We can execute the batch with statement and also prepared statement.

Picture!!!!!!!

There are 2 methods associated with the batch

1. addBatch()
This method is used to add a DML query into the batch.
2. executeBatch()
It is used to execute all the DML queries present in the batch.
It return an integer array(int[]) where each element represent the number of rows affected
due to the specific query.
The number of elements present in int array(size) is same as the number of DML queries
present in Batch.

Code for Batch execution using Statement interface

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class BatchUsingStatement {

public static void main(String[] args) {

Connection con = null;

Statement st = null;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");
st=con.createStatement();

st.addBatch("delete from user where phone=9999");

st.addBatch("update user set name='A',phone=777 where id=2");

st.addBatch("insert into user values(11,'ABC',111)");

int[] r = st.executeBatch();

for(int i=0;i<r.length;i++)

System.out.println(r[i]+" rows are affected");

} catch (ClassNotFoundException | SQLException e)

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (st != null) {

try {

st.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

}
}

15/02/23

Note:

A batch with statement interface can contain all types of DML queries in it.

A batch with prepared statement can contain only one type of DML query.

So, a batch with statement is more efficient than batch with prepared Statement.

Code for Batch execution using prepared Statement

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.PreparedStatement;

public class BatchUsingPreparedStatement {

public static void main(String[] args) {

Connection con = null;

PreparedStatement pst = null;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

pst=con.prepareStatement("insert into user values(?,?,?)");

pst.setInt(1, 12);

pst.setString(2, "Rolex");

pst.setLong(3, 888);

pst.addBatch();

pst.setInt(1, 13);

pst.setString(2, "Adheera");
pst.setLong(3, 777);

pst.addBatch();

pst.setInt(1, 14);

pst.setString(2, "Rocky");

pst.setLong(3, 888);

pst.addBatch();

int[] r = pst.executeBatch();

for(int i=0;i<r.length;i++)

System.out.println(r[i]+" rows are affected");

} catch (ClassNotFoundException | SQLException e)

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("PreparedStatement is closed");

} catch (SQLException e) {

e.printStackTrace();
}

Code for Login validation of a person using preparedStatement interface(Query)

Select* from person where phone=? and password=?

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Scanner;

public class Login {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter your registered Phone no.: ");

long phone = sc.nextLong();

System.out.println("Enter your password");

String password = sc.next();

Connection con = null;

PreparedStatement pst = null;

ResultSet rs = null;

String qry = "select * from person where phone=? and password=?";

try {

Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_demo",
"root", "ankush.rana11");

pst=con.prepareStatement(qry);

pst.setLong(1, phone);

pst.setString(2, password);

rs=pst.executeQuery();

if(rs.next())

System.out.println("Login Successful");

System.out.println("ID"+rs.getInt(1));

System.out.println("name"+rs.getString(2));

System.out.println("phone"+rs.getLong(4));

System.out.println("age"+rs.getInt(3));

else

System.err.println("Invalid phone or password");

}catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {
pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

if (rs != null) {

try {

rs.close();

System.out.println("ResultSet is closed");

} catch (SQLException e) {

e.printStackTrace();

17/02/23

SERVLET

Server

Server is a Software which is used to manage all the resources along with which it will process the
client request and serve the client request (response).

Picture!!!

We have different types of servers:

1. Database Server
2. Application Server
3. Web Server

Database Server

- A server which is used to deal with the “data” is called as Database Server.
Ex. MangoDB, MySQLDB, Oracle DB, etc.

Application Server

- A server which is used to execute both enterprise application as well as web application is
called as Application Server.

Ex. JBoss, Oracle Web Logic, Apache Tomcat, etc.

Note: Apache Tomcat internally behaves as application server.

Web Server

- It is used to execute only web applications.

Ex. Apache Tomcat, Oracle GlassFish etc.

Web Application

- An application which runs on the browser (web) is called as Web Application.

We can have three types of logic in a web Application.

1. Presentation Logic
2. Business Logic
3. Persistent Logic

Presentation Logic

- It is used to display the content of an application.

Technologies Used:

- Servlet, Spring, etc…

Persistent Logic

- It is used to persist the data into persistent system (database).

Technologies Used:

- JDBC, Hibernate, Java Persistence API, etc…

18/02/23

JEE API

JEE API is a specification, which is used for the development of both Enterprise application as well as
web application, using which we can achieve Loose coupling between Application and server.

Picture!!!

Servlet
It is a server side Java Program which is used to execute all three types of logic such as :

1. Presentation Logic
2. Business Logic
3. Persistence Logic
EJB

 Enterprise Java Beans.


 It is a Invasive Framework.

Invasive

 A framework which allows the programmer to implement its interface and extend its classes
is called as Invasive Framework.
 Ex. EJB

Non-Invasive

 A framework which doesn’t allow the programmer to implement its interfaces and extends
its classes is called as Non-Invasive Framework.
 Ex. Spring, Hibernate, etc…

JPA (Java Persistence API)

 It is a specification to directly deal with the objects.

JSP (Java Server Page)

It is an API which is the extension of servlets used to develop web applications.

 JMA (Java Mail API)


 JMS (Java Message Service)
 JTA (Java Transaction API)

JEE Container

It is an engine which is used to manage JEE components such as EJB, JSP, Servlet, etc…

Picture!!!

Structure of JEE Application:

Picture!!!

Steps to download Apache Tomcat

1. Open your browser and search for Apache Tomcat.


2. Click on Apache Tomcat 9 download.
3. Download the zip file which is convenient for your system.
4. Extract the zip file to a specific Folder.

Steps to install or stat the Server:

1. Sett JAVA_HOME
Copy the path: c:/Program Files/Java/Jdk 19.0.1
Paste the Path: Right click on ‘This PC’/properties -> Advanced-system settings ->
Environment variable -> system variable -> new.
2. Set CATALINA-HOME
Copy the path: Upto Apache Tomcat
Paste the Path: Right click on ‘This PC’/properties -> Advanced-system settings ->
Environment variable -> system variable -> new.
3. Set path for Apache Tomcat
Copy the path: Apache Tomcat upto bin folder.
Paste the Path: Advanced System Settings -> Environment Variables -> system variable ->
path -> edit -> new -> Paste it.
21/02/23

Folder’s of Apache Tomcat Server

bin:

It is used to store the executable files, like start up and shutdown instruction for a server.

Lib:

This folder is used to store the executable jar files which can be used for some additional
functionality.

Conf:

It is used to store the configuration files, for a server.

Work:

It is used to store the translated Servlets (Conversion of JSP to Servlet)

Logs:

It is used to store the logs displayed on Server console.

Web-app:

It is used for the deployment of a web application.

Temp:

It is used to store the temporary files related to the server.

Note: By default the port number of Apache Tomcat is 8080.

Deployment:

The process of making all the resources available to the server is called as Deployment.

We have two types of deployment:

1. Manual Deployment
The process of making the resources available to the server manually to the web apps folder
is called as Manual Deployment.
2. Automated Deployment
The process of making the resources available to the server automatically with the help of
automated tools, such as: “ANT (Another Need Tool), Maven, JENKINS” is called as
automated Deployment.

Note:

 We can convert (compress) the project into a war file (Web Achieve) and we can deploy into
web apps folder.
 We can directly deploy on application into a web apps folder.
Note:

 We can deploy more than one application onto server, and if we are deploying more than
one application then the name of every application must be unique.
 Every Application should have one web.xml (deployment description) without which we will
get “404 Error” stating resources not found.
 The web.xml file will be parsed by JEE container so, if there is any error in web.xml we will
get parse Exception.

22/02/23

Web.xml

 It is a configuration file which is used to configure the configurable resources.


 Every application should mandatorily have only one web.xml, without which the application
fails to load and we get “404 Error”.
 Web.xml is passed by JEE container.
 The root tag of web.xml is <web-app>
 By default the version of web.xml is “1.0”, which is encoded with “UTF-8”.

Steps to add server into workspace:

 Open your workspace in eclipse.


 Search for Servers.
 Click on Servers.
 Click the link to create a new Server.
 Select Apache and select the version and click on next.
 Browser the directory, where Apache Tomcat is present, select folder and click on finish.

Welcome File or Landing File:

 It is used to configure the file which has to be display whenever we start the application.
 We need to configure welcome file in web.xml, using <welcome-file></welcome-file> which is
a sub tag of <welcome-file-list> </welcome-file-list>.
 We can configure more than one <welcome-file> and if we have more than one <welcome-
file> all the files will be loaded in sequential order.
 By default the <welcome-file> is index.html.
 If we don’t have the welcome file in the project, then we will get 404 Error.

Note:

By default the port number of Apache Tomcat server is 8080.

23/02/23

Servlet

Servlet is a server side java program, which is used to execute all the 3 types of logic, such as
presentation logic, Business Logic and Persistence Logic.

Servlet should have 3 important components

1. Servlet Name
2. Servlet class(Fully qualified Class name of Servlet)
3. URL Pattern.

Picture!!!

Servlet Hierarchy

Picture!!!

We can create a Servlet by implementing javax.Servlet.Servlet interface or by extending either


javax.Servlet.GenericServlet or by extending javax.Servlet.http.HttpServlet class.

All this classes and interfaces are present in Servlet-api.

Following are the important classes and interfaces of Servlet-api

In javax.Servlet package

Interfaces

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher

Class

1. Generic Servlet

In javax.Servlet.http

Interfaces

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession

Class

1. HttpServlet

24/02/23

javax.servlet.Servlet

 It is an interface present in servlet-api.


 It is the super most interface of Servlet Hierarchy.
 Servlet interface have 5 abstract methods in it.

Following are the abstract methods present in Servlet interface

1. init (ServletConfig)
2. destroy ()
3. service (ServletRequest, ServletResponse)
4. getServletInfo()  String
5. getServletConfig()  ServletConfig

Servlet-Mapping
The process of mapping a servlet with URL is called as Servlet-Mapping.

We can achieve Servlet-Mapping in 2 ways.

1. By using web.xml
2. By using Annotation

Code to create a Servlet by implementing javax.servlet.Servlet interface.

Java Code:

import java.io.IOException;

import javax.servlet.Servlet;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class FirstServlet implements Servlet{

@Override

public void destroy() {

// TODO Auto-generated method stub

@Override

public ServletConfig getServletConfig() {

// TODO Auto-generated method stub

return null;

@Override

public String getServletInfo() {

// TODO Auto-generated method stub

return null;

@Override
public void init(ServletConfig arg0) throws ServletException {

// TODO Auto-generated method stub

@Override

public void service(ServletRequest arg0, ServletResponse arg1) throws


ServletException, IOException {

// TODO Auto-generated method stub

System.out.println("Hi! I am your Buddy..... Farewell");

XML code:

<!-- naming the Servlet -->

<servlet>

<servlet-name>First</servlet-name>

<servlet-class>org.jsp.servletdemo.FirstServlet</servlet-class>

</servlet>

<!-- Mapping the Servlet -->

<servlet-mapping>

<servlet-name>First</servlet-name>

<url-pattern>/fs</url-pattern>

</servlet-mapping>

HTML code:

<body>

<h2><a href="fs">Click here to send the Request to your Servlet</a></h2>

</body>

25/02/23

Code to create a Servlet by extending Generic servlet class.

import java.io.IOException;
import javax.servlet.GenericServlet;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class MyServlet extends GenericServlet

public void service(ServletRequest req, ServletResponse resp) throws


ServletException, IOException

System.out.println("This is MyServlet...");

XML code:

<servlet>

<servlet-name>MyServlet</servlet-name>

<servlet-class>org.jsp.servletdemo.MyServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>MyServlet</servlet-name>

<url-pattern>/ms</url-pattern>

</servlet-mapping>

Html code:

<h2><a href="ms">Click here to send the request for MyServlet</a></h2>

javax.servlet.GenericServlet

 It is an abstract class present in Servlet-api.


 It is the sub-class of javax.servlet.Servlet interface.
 All the methods of servlet interface are present inside GenericServlet.
 Except service method all the methods of servlet interface are implemented in
GenericServlet.
 GenericServlet is independent of protocol.
 GenericServlet does not support session.

27/02/23

javax.servlet.http.HttpServlet

 It is an abstract class present in servlet-api.


 It is the sub-class of GenericServlet.
 All the methods of Servlet and GenericServlet are inherited in HttpServlet.
 HttpServlet is dependent on http-protocol so the name is given as HttpServlet.
 HttpServlet supports Session.

Note: HttpServlet doesn’t have any abstract method, all the inherited abstract methods are
implemented. Along with the inherited methods from the GenericServlet. HttpServlet also contains
do***(). Where * stands for type of request.

Following are the different types of HttpRequest:

1. Post
2. Put
3. Delete
4. Get
5. Patch
6. Head
7. Options
8. Trace

# Code to create a Servlet by extending HttpServlet(using doGet)

Java code:

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet{

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

System.out.println("This is your Second Servlet");

Xml code:

<servlet>
<servlet-name>Second</servlet-name>

<servlet-class>org.jsp.servletdemo.SecondServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Second</servlet-name>

<url-pattern>/ss</url-pattern>

</servlet-mapping>

Html code:

<h2><a href="ss">Click here to see Second Servlet</a></h2>

# Code to create a Servlet by extending HttpServlet(using doPost)

Java code:

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet{

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

System.out.println("This is your Second Servlet");

XML code:

<servlet>

<servlet-name>Second</servlet-name>

<servlet-class>org.jsp.servletdemo.SecondServlet</servlet-class>

</servlet>

<servlet-mapping>
<servlet-name>Second</servlet-name>

<url-pattern>/ss</url-pattern>

</servlet-mapping>

Html code:

<form action="ss" method="post">

<input type="submit" value="SecondServlet">

</form>

28/02/23

@WebServlet

 It is a class level annotation present in javax.servlet.Annotation package (Servlet-API).


 It is used to map a servlet with URL-pattern.

Form Data/ UI Data

 It is the data that has been sent to the server along with the request in the form of key
equals value pairs.
 We can fetch the form data with the help of getparameter (String) present in ServletRequest
Interface.

getparameter

 It is a non-static method present in ServletRequest Interface.


 This method will accept key as the parameter and return the value associated with the key in
the form of String.
 So the returntype of this method is String.

#Code to fetch the form data in the Servlet

Html code:

<form action="print" method="post">

Name<input type="text" name="nm"><br>

Phone<input type="tel" name="ph"><br>

State<input type="text" name="st"><br>

Country<input type="text" name="ct"><br>

<input type="submit" value="REGISTER">

</form>

Java code:
import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/print")

public class PrintDetails extends HttpServlet{

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException {

String name=req.getParameter("nm");

long phone=Long.parseLong(req.getParameter("ph"));

String state=req.getParameter("st");

String country=req.getParameter("ct");

System.out.println("Following are your Details");

System.out.println("Name: "+name);

System.out.println("Phone: "+phone);

System.out.println("State: "+state);

System.out.println("Country: "+country);

01/03/23

Java.io.Printwriter

 It is the sub-class of java.io.writer.


 It is used to write the data to the specified destination.

getWriter()

 This is a factory method or helper method present in ServletResponse interface.


 This method will return the reference of printWriter object.
 The returntype of getWriter is printWriter.
#Code to print the form data/display the form data in the browser using printWriter class

Form2.html code:

<form action="ps" method="post">

Name<input type="text" name="nm"><br>

Phone<input type="tel" name="ph"><br>

State<input type="text" name="st"><br>

Country<input type="text" name="ct"><br>

<input type="submit" value="REGISTER">

</form>

Java code:

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/ps")

public class PrintServlet extends HttpServlet{

@Override

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws


ServletException, IOException {

String name=req.getParameter("nm");

long phone=Long.parseLong(req.getParameter("ph"));

String state=req.getParameter("st");

String country=req.getParameter("ct");

PrintWriter writer = resp.getWriter();

writer.write("<html><body><h1>Your Details Are As Follows:</h1>");


writer.write("<h2>Name: "+name+"</h2>");

writer.write("<h2>Phone: "+phone+"</h2>");

writer.write("<h2>State: "+state+"</h2>");

writer.write("<h2>Country: "+country+"</h2></body></html>");

02/03/23

Enumeration

 It is an interface present in java.util package.


 It is used to hold a set of fixed data.

Methods of Enumeration:

hasMoreElements

 This method returns a boolean value, depends upon the presence of element in the
Enumeration.
 It returns true if any element present in the Enumeration otherwise it will return false.

nextElement

 This method returns the element present in the Enumeration.


 The returntype of this method depends upon the type of Enumeration.

getParameterNames

 This is a method present in ServletRequest Interface.


 This method will return all the keys present in the form of Enumeration<String>.
 So the returntype of this method is Enumeration<String>.

Ex.

Demo.java

import java.io.IOException;

import java.util.Enumeration;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/demo")

public class Demo extends HttpServlet{

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException {

Enumeration<String> keys = req.getParameterNames();

while(keys.hasMoreElements()) {

String key = keys.nextElement();

System.out.println(key+" --> "+req.getParameter(key));

Demo.html

<form action="demo" method="post">

Name<input type="text" name="nm"><br>

Age<input type="number" name="age"><br>

Phone<input type="text" name="ph"><br>

Email<input type="email" name="em"><br>

City<input type="text" name="ct"><br>

State<input type="text" name="st"><br>

Country<input type="text" name="cn"><br>

<input type="submit" value="REGISTER">

</form>

03/03/23

Servlet Life Cycle

 Servlet Life Cycle depicts the different phases of a servlet from instantiation upto destruction.

Following are the different phases in Servlet Life Cycle


1. Instantiation Phase
2. Initialisation Phase
3. Service Phase
4. Destruction Phase

Instantiation Phase

 In this phase JEE container will create the object for the servlet by calling public No-argument
constructor.
 Along with the servlet object servlet config object will be created which is used to initialise
the members of the Servlet.
 The scope of servlet config object is restricted to a particular servlet (For every Servlet object
one servlet config object will be created.)
 If this phase fails we will get Servlet Exception.
 This phase fails if JEE container is not able to find public No-argument constructor.

Initialisation Phase

 In this phase JEE container will call the init() of the servlet to initialise the members of the
servlet.
 Servlet Config object is used to initialise the members of the Servlet.
 If this phase fails we will get servlet Exception.

04/03/23

Service Phase

In this phase JEE container will call the service method to execute the logic.

JEE container will create the object for ServletRequest and ServletResponse to call the service
method.

Service method will execute for each client request.

By default service method is multiThreaded but we can make the servlet as single threaded in 2 ways

1. By making service method synchronized.


2. By implementing single threaded model interface.

Example for servlet LifeCycle

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/lh")
public class LifeCycleDemo extends HttpServlet{

static {

System.out.println("Class is loaded in JVM memory");

public LifeCycleDemo(){

System.out.println("This is the instantiation Phase");

@Override

public void init() throws ServletException {

System.out.println("The members are initialised");

@Override

protected synchronized void service(HttpServletRequest req,


HttpServletResponse resp) throws ServletException, IOException {

for(int i=0; i<=5; i++)

System.out.println("Executed "+i+" times "+Thread.currentThread());

try {

Thread.sleep(5000);

catch(InterruptedException e){

e.printStackTrace();

Destruction Phase

 In this phase JEE container will call the destroy method to close the resources.
 Destroy method will be called only once but in 2 situations
Case 1: If we close the application destroy method will be called to close all the costly
resources.
Case 2: If we redeploy the application, JEE container will call the destroy method to close all
the previously used resources.
 If this Phase fails, efficiency of the application will decrease.

Note:

1. The JEE container will create the servlet object only for the first client request.
2. Init method is executed only once for the first client request.
3. Service method will execute for every client request.
4. Destroy method will be called only once.

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/lh")

public class LifeCycleDemo extends HttpServlet{

static {

System.out.println("Class is loaded in JVM memory");

public LifeCycleDemo(){

System.out.println("This is the instantiation Phase");

@Override

public void init() throws ServletException {

System.out.println("The members are initialised");

@Override

protected void service(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException {
System.out.println("This is Service Phase");

@Override

public void destroy() {

System.out.println("All the resources are closed");

Load on Startup

 It is used to create the Servlet Object as soon as the application is started.


 Generally, the servlet object gets created after the first client request but if we use load on
Startup the servlet objects will be created as soon as the application starts.
 Because of Load on Startup the efficiency of application will increase.

06/03/23
 <load-on-startup> is a sub-tag of servlet tag.
 We should config. Load on startup with a positive integer value.
 The servlets will be loaded based on the positive integer value in ascending order of integer
value.
 If we have more than one servlet config with same integer value then sequential execution
takes place.
 If we config load on startup for a servlet with negative integer value then the servlet object
will be created after the first client request.

Note: If we use load on startup only service method will execute for the first client request.

#Code on Load on Startup using Annotation(web servlet)

Demo.java

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/demo", loadOnStartup = 11)

public class demo extends HttpServlet{


static {

System.out.println("Demo is loaded in JVM memory");

public demo(){

System.out.println("Demo object is created");

@Override

public void init() throws ServletException {

System.out.println("The members are initialised");

@Override

protected void service(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException {

System.out.println("This is Service Phase");

@Override

public void destroy() {

System.out.println("Demo object is destroyed");

Test.html

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class test extends HttpServlet{


static {

System.out.println("Test is loaded in JVM memory");

public test(){

System.out.println("Test object is created");

@Override

public void init() throws ServletException {

System.out.println("The members are initialised");

@Override

protected void service(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException {

System.out.println("This is Service Phase");

@Override

public void destroy() {

System.out.println("Test object is destroyed");

Web.xml

<welcome-file-list>

<welcome-file>home.html</welcome-file>

</welcome-file-list>

<servlet>

<servlet-name>test</servlet-name>

<servlet-class>org.jsp.test</servlet-class>

<load-on-startup>11</load-on-startup>
</servlet>

<servlet-mapping>

<servlet-name>test</servlet-name>

<url-pattern>/test</url-pattern>

</servlet-mapping>

07/03/23

Servlet Chaining

The process of transferring the control from a servlet to another resource such as jsp or html or
another servlet is called as Servlet Chaining.

We can achieve servlet chaining in two ways

1. javax.servlet.RequestDispatcher
2. Send Redirect(String)

javax.servlet.RequestDispatcher

 It is an interface present in Servlet-API.


 It is the interface which is used to transfer the control from one resource to another resource.

Following are the methods of RequestDispatcher interface

1. forward(ServletRequest, ServletResponse)

It is used to forward the request from one resource to another resource.

2. include(ServletRequest, ServletResponse)

It is used to include the request and response with another resource.

getRequestDispatcher(String path)

 It is an helper method or factory method present in ServletRequest interface.


 This method will create the implementation object of RequestDispatcher for the specified
resource and returns the reference.
 So the returntype of this method is RequestDispatcher.

#Code for Servlet Chaining using RequestDispatcher

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/login")

public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

String password = request.getParameter("ps");

Long phone = Long.parseLong(request.getParameter("ph"));

PrintWriter writer = response.getWriter();

RequestDispatcher dispatcher = null;

if(phone == 777111&&password == ("a12345"))

dispatcher = request.getRequestDispatcher("home.html");

dispatcher.forward(request, response);

}else

dispatcher = request.getRequestDispatcher("login.html");

writer.write("<html><body><h1>Invalid
Credentials<h1><body><html>");

dispatcher.include(request, response);

Html code:

<form action="login" method="post">

Phone No.<input type="tel" name="ph"><br>


Password<input type="password" name="ps"><br>

<input type="submit" value="login">

</form>

#Code to Register the data from the server using getRequest

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/reg")

public class RegisterServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

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

String Name = request.getParameter("nm");

int Age = Integer.parseInt(request.getParameter("age"));

long Phone = Long.parseLong(request.getParameter("ph"));

String Pass = request.getParameter("ps");

Connection con = null;

PreparedStatement pst = null;

String qry = "insert into user values(?,?,?,?,?)";

try {
Class.forName(UserUtility.DRIVER);

con =
DriverManager.getConnection(UserUtility.URL,UserUtility.USER,UserUtility.PA
SSWORD);

pst = con.prepareStatement(qry);

pst.setInt(1, id);

pst.setString(2, Name);

pst.setInt(3, Age);

pst.setLong(4, Phone);

pst.setString(5, Pass);

pst.executeUpdate();

PrintWriter writer = response.getWriter();

writer.write("<html><body><h1>User Saved Succesfully</h1></body></html>");

}catch(SQLException | ClassNotFoundException e) {

e.printStackTrace();

}finally {

if(con!=null)

try {

con.close();

} catch (SQLException e) {

e.printStackTrace();

if(pst!=null)

try {

pst.close();

} catch (SQLException e) {
e.printStackTrace();

Html code:

<form action="reg" method="post">

<h1>Registration Form</h1>

<p>Id: <input type="number" name="id"/></p>

<p>Name: <input type="text" name="nm"/></p>

<p>Age: <input type="number" name="age"/></p>

<p>Phone Number: <input type="tel" name="ph"/></p>

<p>Password: <input type="password" name="ps"/></p>

<p><input type="submit" value="Register"/></p>

</form>

09/03/23

#Code to Fetch the data from the server using getRequest

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

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

import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/fetch")

public class FetchUserServlet extends HttpServlet{

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,


IOException {

int id = Integer.parseInt(req.getParameter("id"));

Connection con = null;

PreparedStatement pst = null;

ResultSet rs = null;

String qry = "select * from user where id=?";

try {

Class.forName(UserUtility.DRIVER);

con =
DriverManager.getConnection(UserUtility.URL,UserUtility.USER,UserUtility.PASSWORD);

pst = con.prepareStatement(qry);

pst.setInt(1,id);

rs = pst.executeQuery();

PrintWriter writer = resp.getWriter();

if(rs.next()) {

writer.write("<html><body><h1>ID: "+rs.getInt(1)+"<br>");

writer.write("<h1>Name: "+rs.getString("name")+"</h1>");

writer.write("<h1>Age: "+rs.getInt("age")+"</h1>");

writer.write("<h1>Phone:
"+rs.getLong("phone")+"</h1></body></html>");

}else {

writer.write("<html><body><h1>Invalid ID</h1></body></html>");

catch (ClassNotFoundException | SQLException e) {


e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

if (rs != null) {

try {

rs.close();

System.out.println("ResultSet is closed");

} catch (SQLException e) {

e.printStackTrace();

}}

Html code:

<form action="fetch" method="get">

ID<input type="number" name="id"><br>


<input type="submit">

</form>

#Code to Delete the data from the server using getRequest

import java.io.IOException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/del")

public class DeleteUserServlet extends HttpServlet{

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,


IOException {

int id = Integer.parseInt(req.getParameter("id"));

Connection con = null;

PreparedStatement pst = null;

String qry = "delete from user where id=?";

try {

Class.forName(UserUtility.DRIVER);

con =
DriverManager.getConnection(UserUtility.URL,UserUtility.USER,UserUtility.PASSWORD);

pst = con.prepareStatement(qry);

pst.setInt(1,id);

pst.executeUpdate();
}

catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

}}

Html code:

<form action="del" method="post">

ID<input type = "number" name = "id"><br>

<input type="submit" name="DELETE">

</form>

#Code to Update the data from the server using getRequest

import java.io.IOException;

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

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/update")

public class UpdateUserServlet extends HttpServlet{

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException {

int id = Integer.parseInt(req.getParameter("id"));

String Name = req.getParameter("nm");

int Age = Integer.parseInt(req.getParameter("age"));

long Phone = Long.parseLong(req.getParameter("ph"));

String Pass = req.getParameter("ps");

Connection con = null;

PreparedStatement pst = null;

String qry = "update user set name=?, age=?, phone=?, pass=? where id=?";

PrintWriter writer = resp.getWriter();

writer.write("<html><body><h1>User Updated
Succesfully</h1></body></html>");

try {

Class.forName(UserUtility.DRIVER);

con =
DriverManager.getConnection(UserUtility.URL,UserUtility.USER,UserUtility.PA
SSWORD);
pst = con.prepareStatement(qry);

pst.setInt(5,id);

pst.setString(1, Name);

pst.setInt(2, Age);

pst.setLong(3, Phone);

pst.setString(4, Pass);

pst.executeUpdate();

catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

} catch (SQLException e) {

e.printStackTrace();

}
Html Code:

<form action="update" method="post">

ID:<input type = "number" name = "id"><br>

Name:<input type = "text" name = "nm"><br>

Age:<input type = "number" name = "age"><br>

Phone:<input type = "tel" name = "ph"><br>

Password:<input type = "password" name = "ps"><br>

<input type="submit" name="UPDATE">

</form>

#Code to Login the data from the server using getRequest

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/login")

public class LoginUserServlet extends HttpServlet{

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException {

long Phone = Long.parseLong(req.getParameter("ph"));


String Pass = req.getParameter("ps");

Connection con = null;

PreparedStatement pst = null;

ResultSet rs = null;

String qry = "select * from user where Phone=? and Pass=?";

try {

Class.forName(UserUtility.DRIVER);

con =
DriverManager.getConnection(UserUtility.URL,UserUtility.USER,UserUtility.PA
SSWORD);

pst = con.prepareStatement(qry);

pst.setLong(1, Phone);

pst.setString(2, Pass);

rs = pst.executeQuery();

PrintWriter writer = resp.getWriter();

if(rs.next()) {

writer.write("<html><body><h1>ID: "+rs.getInt(1)+"<br>");

writer.write("<h1>Name: "+rs.getString("name")+"</h1>");

writer.write("<h1>Age: "+rs.getInt("age")+"</h1>");

writer.write("<h1>Phone: "+rs.getLong("phone")+"</h1></body></html>");

}else {

writer.write("<html><body><h1>Invalid Credentials</h1></body></html>");

}catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();
System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {

pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

if (rs != null) {

try {

rs.close();

System.out.println("ResultSet is closed");

} catch (SQLException e) {

e.printStackTrace();

Html code:

<form action="login" method="post">

Phone:<input type="number" name="ph"><br>


Password:<input type="password" name="ps"><br>

<input type="submit" value="Login">

</form>

Home.HTML:

<body>

<a href = "RegistrationForm.html">Register</a><br>

<a href = "fetchUser.html">To Fetch User</a><br>

<a href = "DeleteUser.html">Delete User</a><br>

<a href = "UpdateUser.html">Update User</a><br>

<a href = "LoginUser.html">Login User</a>

</body>

10/03/23

JSP (Java Server Pages)

 JSP is an API which is used for the development of web applications.


 JSP is the extension of Servlet which will provide some advance functionality like Expression
language, JSTL (JSP Standard Tag Library) support using which we can simplify the web
application development.

Advantages of JSP

 It is an extension of servlet and provides some additional functionality.


 JSP is easy to maintain because the design part and the logical part are separated with the
help of predefined tags.
 JSP supports customised tags which are present in JSTL.
 If we do any modification for the Servlet then the Servlet need to be re-compiled and re-
deployed but if we use JSP there is no need to re-compile and re-deploy when we do a
modification.

Following are the different tags which are supported by JSP

1. Scriplet Tag (<% %>)


2. Expression Tag (<%= %>)
3. Declaration Tag (<%! %>

In every JSP we will have the Following objects

1. request -> HttpServletRequest


2. response -> HttpServletResponse
3. session -> HttpSession
4. out -> JspWriter
#Code to Fetch the data of user using JSP

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/fetchJ")

public class FetchUserServletUsingJSP extends HttpServlet{

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException {

int id = Integer.parseInt(req.getParameter("id"));

Connection con = null;

PreparedStatement pst = null;

ResultSet rs = null;

String qry = "select * from user where id=?";

try {

Class.forName(UserUtility.DRIVER);

con =
DriverManager.getConnection(UserUtility.URL,UserUtility.USER,UserUtility.PA
SSWORD);
pst = con.prepareStatement(qry);

pst.setInt(1,id);

rs = pst.executeQuery();

PrintWriter writer = resp.getWriter();

RequestDispatcher dispatcher = null;

if(rs.next()) {

dispatcher = req.getRequestDispatcher("print.jsp");

req.setAttribute("id", rs.getInt("id"));

req.setAttribute("Name", rs.getString("Name"));

req.setAttribute("Age", rs.getInt("Age"));

req.setAttribute("Phone", rs.getLong("Phone"));

dispatcher.forward(req, resp);

}else {

writer.write("<html><body><h1>Invalid ID</h1></body></html>");

catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

} finally {

if (con != null) {

try {

con.close();

System.out.println("Connection is closed");

} catch (SQLException e) {

e.printStackTrace();

if (pst != null) {

try {
pst.close();

System.out.println("Statement is closed");

} catch (SQLException e) {

e.printStackTrace();

if (rs != null) {

try {

rs.close();

System.out.println("ResultSet is closed");

} catch (SQLException e) {

e.printStackTrace();

}}

HTML code:

<form action="fetchJ" method="get">

ID<input type="number" name="id"><br>

<input type="submit">

</form>

JSP code:

<body>

<h1>Your Details are Displayed Below</h1>

<h1>ID:<%=request.getAttribute("id") %></h1><br>

<h1>Name:<%=request.getAttribute("Name") %></h1><br>
<h1>Age:<%=request.getAttribute("Age") %></h1><br>

<h1>Phone:<%=request.getAttribute("Phone") %></h1><br>

</body>

11/03/23

JSP Life Cycle

Step 1: Translation of JSP into Servlet.

Step 2: Compilation of translated Servlet.

Step 3: Instantiation of Translated Servlet Object.

Step 4: Initialisation of Translated Servlet Object by calling JSP_init().

Step 5: Execution of the logic by calling JSP_Service().

Step 6: Destruction of Translated Servlet by calling JSP_Destroy().

Print.jsp

<%! Public int getSum(int a, int b) {

Return a+b; }%>

<%int sum = getSum(10,20); %>

<h1> The sum is:<%= sum %>

Translated Servlet

Class printJSP_Servlet

Public int sum(int a , int b)

Return a+b;

Public void Service(HttpServletRequest req, HttpServletResponse resp)

Int sum = sum(10,20);

PrintWriter writer = resp.getWriter();

Writer.write(sum);

Session Tracking
Session Tracking is a technique in which we track the session of a user. Generally the application
should not ask the user to login for every request. Every request should not be considered as a new
request until the session is over.

We can achieve the session tracking by using following techniques

1. Cookies
2. HttpSession
3. HiddenFormFields

13/03/23

 It is an interface present in javax.servlet.Http Package.


 It is used to tract the session of a user.

Important methods of HttpSession.

1. setAttribute(String(value), Object(variable name)) -> returntype-void


It is used to add the data into session
2. getAttribute(String(attribute name)) -> returntype-java.lang.Object
This method returns the value associated with the attribute.
3. invalidate()
It is used to destroy the session.
Once we call invalidate method all the attributes associated with session will be destroyed.
Ex.

#Code to write the properties into jdbc.properties file

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Properties;

public class StoreProperties {

public static void main(String[] args) throws IOException {

Properties p = new Properties();

p.setProperty("jdbc.driver", "com.mysql.cj.jdbc.Driver");

p.setProperty("jdbc.user", "root");

p.setProperty("jdbc.url", "jdbc:mysql://localhost:3306/jdbc_demo");

p.setProperty("jdbc.password", "ankush.rana11");

FileOutputStream fout = new FileOutputStream("D:\\Docs\\J2EE\\


jdbc.properties");

p.store(fout, "Added JDBC Properties");

}
}

#Code to read the properties from properties file

import java.io.FileInputStream;

import java.io.IOException;

import java.util.Properties;

public class LoadProperties {

public static void main(String[] args) throws IOException {

FileInputStream fin = new FileInputStream("D:\\Docs\\J2EE\\


jdbc.properties");

Properties p = new Properties();

p.load(fin);

System.out.println(p.getProperty

("jdbc.driver"));

System.out.println(p.getProperty("jdbc.user"));

System.out.println(p.getProperty("jdbc.url"));

System.out.println(p.getProperty("jdbc.password"));

#Code to Establish the connection between java application and database server using
getConnection(String URL, Properties info).

Store Procedure

 Store procedure is a group of sql statements which contains a name and can be reused.

A store procedure can take 3 types of parameters

1. IN Parameter
2. Out Parameter
3. INOUT Parameter

Assignment Questions

What is a JDBC Driver?

What are the types of JDBC Driver?


Explain the types of Drivers.

Syntax to create a Stored Procedure

Create Procedure procedure_name(IN/ OUT/ INOUT parameter_name datatype)

BEGIN
/* SQL statements */

END

Java.sql.CallableStatement

 It is an interface present in JDBC api.


 The implementation of callable statement is provided by database vendor as a part of JDBC
Driver.
 It is used to call a stored procedure from the database.

prepareCall (String)

1. It is a factory method or helper method which is present in connection interface.


2. It will create the implementation object of java.sql.CallableStatement and returns the
reference.
3. The returntype of this method is callable Statement.

#Code to execute a callable statement and use stored procedure.

JDBC Driver

 JDBC Driver is the implementation of JDBC provided by database vendor to connect with
database.
 JDBC Driver is used to convert java calls into sql calls.
 It should be installed in client machine to connect with a specific database.

We have 4 types of JDBC Drivers

1. Type 1 Driver OR JDBC_ODBC Bridge Driver -> Open Database Connectivity


2. Type 2 Driver OR Native API Driver
3. Type 3 Driver OR Network Protocol Driver
4. Type 4 Driver OR Thin Driver

Note: We are using Type 4 Driver OR Thin Driver for database Connectivity.

You might also like