0% found this document useful (0 votes)
5 views124 pages

JDBCSERVLETJSP

Uploaded by

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

JDBCSERVLETJSP

Uploaded by

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

WAP to insert a record into the table with user entered data?

Own made
Video: 15
package com.jsp.jdbc;
import java.io.FileInputStream; Jdbcdata.properties
import java.io.IOException;
import java.sql.Connection; driver=com.mysql.cj.jdbc.Driver
import java.sql.DriverManager; url=jdbc:mysql://localhost:3306?user=root&password=root&useSSL=false
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;

public class InseringData {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
Connection connection = null;
PreparedStatement preparedstatement= null;

System.getProperty("jdbc");
try {
FileInputStream fileinputstream = new FileInputStream("lib/jdbcdata.properties");
Properties properties = new Properties();
properties.load(fileinputstream);

Class.forName(properties.getProperty("driver"));
connection=DriverManager.getConnection(properties.getProperty("url"));

String query = "insert into oejm2.employee values(?,?,?)";


preparedstatement=connection.prepareStatement(query);

System.out.println("Enter id,name,salary");
int id = scanner.nextInt();
String name = scanner.next();
double salary =scanner.nextDouble();

preparedstatement.setInt(1, id);
preparedstatement.setString(2,name);
preparedstatement.setDouble(3,salary);

preparedstatement.executeUpdate();

System.out.println("Data Inserted");

} catch (IOException | ClassNotFoundException | SQLException e) {

e.printStackTrace();
}

finally {

try {
if(preparedstatement!=null) preparedstatement.close();
if(connection!=null)connection.close();
scanner.close();
} catch (SQLException e) {

e.printStackTrace();
}
}

}
package com.jsp.jdbc;
WAP to insert multiple data entered by user?
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection; Jdbcdata.properties
import java.sql.DriverManager; driver=com.mysql.cj.jdbc.Driver
import java.sql.PreparedStatement; url=jdbc:mysql://localhost:3306?user=root&password=root&useSSL=false
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;

public class MultipleDataInsertion {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Connection connection = null;
PreparedStatement preparedstatement = null;
//int record = 0;

System.getProperty("jdbc");
try {
FileInputStream fileinputstream = new FileInputStream("lib/jdbcdata.properties");
Properties properties = new Properties();
properties.load(fileinputstream);

Class.forName(properties.getProperty("driver"));
connection = DriverManager.getConnection(properties.getProperty("url"));

String query = "insert into oejm2.employee values(?,?,?)";


preparedstatement = connection.prepareStatement(query);
do {
System.out.println("Enter id,name,salary");
int id = scanner.nextInt();
String name = scanner.next();
double salary = scanner.nextDouble();

preparedstatement.setInt(1, id);
preparedstatement.setString(2, name);
preparedstatement.setDouble(3, salary);

preparedstatement.executeUpdate();

System.out.println("Data Inserted");
System.out.println("Press 1 to add one more record or press any other number for exit:");
//record=scanner.nextInt();
} while (scanner.nextInt() == 1);//while(record==1);

} catch (IOException | ClassNotFoundException | SQLException e) {

e.printStackTrace();
}

finally {

try {
if (preparedstatement != null)
preparedstatement.close();
if (connection != null)
connection.close();
scanner.close();
} catch (SQLException e) {

e.printStackTrace();
}
}

}
Output:

Enter id,name,salary
3
ram
7000
Data Inserted
Press 1 to add one more record or press any other number for exit:
1
Enter id,name,salary
4
laxman
6000
Data Inserted
Press 1 to add one more record or press any other number for exit:
8
Video: 16

PreparedStatement:

 It is a platform to execute SQL queries


 PreparedStatement also an interface in java.sql package extends Statement interface
 We can create PreparedStatement platform by using prepareStatement()
 PreparedStatement supports PlaceHolder concept

prepareStatement():

It is a method of connection interface

Syntax: public PreparedStatement prepareStatement(String queries);

Interface Interface
Statement Connection

Methods:  createStatement:
return :Statement Object
 execute(String queries)
 executeUpdate(String queries)
 executeQuery(String queries)

extends

Interface
PreparedStatement

Methods:

 execute()
 executeUpdate()
 executeQuery()
 execute(String queries)
 executeUpdate(String queries)
 executeQuery(String queries)

Interface

Connection

 prepareStatement(String queries):
return: PreaparedStatement Object
PlaceHolder in PreparedStatemet:

 PlaceHolder is indicated by the symbol: ”?”


 It is representing the data at the time of query compilation
 Before executing the query data must be set for every PlaceHolder
 We can set the PlaceHolder value by using set***()
 Every PlaceHolder represent columns,each PlaceHolder must be set with proper type of value

Set***(): ***- means DataType

 It is a method of PreparedStatement.
 It is used for setting the PlaceHolder value.

Syntax: public void set***(int PlaceHolderindex, **** value)

Example:

 setInt(1,254)
 setString(2,”kdjadj”)
package com.jsp.jdbc;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;

public class InsertingByPrepared {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
Connection connection = null;
PreparedStatement preparedstatement = null;

System.getProperty("jdbc");
try {
FileInputStream fileinputstream = new FileInputStream("lib/jdbcdata.properties");
Properties properties = new Properties();
properties.load(fileinputstream);

Class.forName(properties.getProperty("driver"));
connection=DriverManager.getConnection(properties.getProperty("url"));

String query = "insert into oejm2.employee values(?,?,?)";


preparedstatement=connection.prepareStatement(query);

System.out.println("Enter id, name , salary"); Output:


preparedstatement.setInt(1,scanner.nextInt());
preparedstatement.setString(2,scanner.next() ); Enter id, name , salary
preparedstatement.setDouble(3, scanner.nextDouble()); 5
oram
preparedstatement.executeUpdate(); 67894
DataInserted
System.out.println("DataInserted");

} catch (IOException | ClassNotFoundException | SQLException e) {

e.printStackTrace();
}

Jdbcdata.properties
}

} driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306?user=root&password=root&useSSL=false
WAP to insert multiple record or data?
Benefit of PreaparedStatement:
package com.jsp.jdbc;
 Compilation will be 1 time and multiple time
import java.io.FileInputStream; execute for multiple data insertion
import java.io.IOException;
 It reduces compilation Time.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException; Jdbcdata.properties
import java.util.Properties;
import java.util.Scanner; driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306?user=root&password
public class MultipleInsertionbyPreparedStatement { =root&useSSL=false
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Connection connection = null;
PreparedStatement preparedstatement = null;

System.getProperty("jdbc");
try {
FileInputStream fileinputstream = new FileInputStream("lib/jdbcdata.properties");
Properties properties = new Properties();
properties.load(fileinputstream);

Class.forName(properties.getProperty("driver"));
connection = DriverManager.getConnection(properties.getProperty("url"));

String query = "insert into oejm2.employee values(?,?,?)";


preparedstatement = connection.prepareStatement(query);
do {
System.out.println("Enter id, name , salary");
preparedstatement.setInt(1, scanner.nextInt());
preparedstatement.setString(2, scanner.next());
preparedstatement.setDouble(3, scanner.nextDouble());

preparedstatement.executeUpdate();

System.out.println("DataInserted");
System.out.println("Enter 1 for inserting one more data: ");
} while (scanner.nextInt() == 1);

} catch (IOException | ClassNotFoundException | SQLException e) {

e.printStackTrace();
}

Output:
Enter id, name , salary
4
farahan
79000
DataInserted
Enter 1 for inserting one more data:
1
Enter id, name , salary
5
krish
777777
DataInserted
Enter 1 for inserting one more data:
10
package com.jsp.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class TCLCommand {

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
Connection cn = null;
PreparedStatement pst = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306?useSSL=false&user=root&password=root");
cn.setAutoCommit(false); // This will turn off AutoCommit

int r = 0;
String qu = "insert into jspiders.student values(?,?,?)";
pst = cn.prepareStatement(qu);

do {
System.out.println("Enter id ,name,marks"); Output:

int id = scn.nextInt(); Enter id ,name,marks


String na = scn.next(); 13
double ma = scn.nextDouble(); reeshika
89.5
pst.setInt(1, id); data inserted
pst.setString(2, na); You want to keep (1) or rollback(2)
pst.setDouble(3, ma); 2
Press 1 to insert one more data
pst.executeUpdate();// execution 1
System.out.println("data inserted"); Enter id ,name,marks
System.out.println("You want to keep (1) or rollback(2)"); 13
int op =scn.nextInt(); rohit
if(op==1) { 85.3
cn.commit(); data inserted
} You want to keep (1) or rollback(2)
else { 1
cn.rollback(); Press 1 to insert one more data
} 2
System.out.println("Press 1 to insert one more data");
r = scn.nextInt();

} while (r == 1);
} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();
}
finally {

try {
if(pst!=null) pst.close();
if(cn!=null) cn.close();
scn.close();
} catch (SQLException e) {

e.printStackTrace();
}
}

}
Video: 17

Create Project to which does insert, update, delete and display record:
1. Create Java Project : ctrl+N or right click –go to New ---- select Project
 Select Java Project
 Click to Next
 Project Name: CURDOPERATION
 select Finish
 select Don’t Create for Module name
 Select No for Open the Java Perspective?
2. Create lib folder: select the CURDOPERATION project: ctrl+N or right click---- go to New ----select Folder----select
CURDOPERATION -------Folder name: lib------Finish.
3. Copy the jar file: mysql-connector-j-8.0.32.jar
4. Paste to lib folder of CURD OPERATION
5. Select mysql-connector-j-8.0.32.jar ---------right click ------- go to Build Path------ select Add to Build Path
Or
Select mysql-connector-j-8.0.32.jar-------- right click------- go to Build Path------- configure Build Path------- select Class Path--
--Add jars...--------select mysql-connector-j-8.0.32.jar-----ok-----apply and close

 It will add to Referenced Libraries in the project


6. Select src folder of CURDOPERATION project: ctrl+N or right click---- go to New -----select Package------
Name: com.jspider.dml------Finish
7. Select com.jspider.dml-----right click--------- go to New------ Class------Name: DMLOperation------Finish
8. Go to HeidiSQL-----select Unnamed -------right click go to Create new------Database----Name: simpleproject-------ok-----
select simpleproject--------right click Create New ------Table--- employee-----id(Primary Key), name, salary

Insert query: insert into simpleproject.employee values(id,’name’,salary);

Update query: update simpleproject.employee set columnName=new value,columnName=new value…….. where condition;

Delete query: delete from simpleproject.employee where condition;


package com.jspider.dml;

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


Scanner scanner = new Scanner(System.in);
Connection connection;
PreparedStatement preparedstatement;
ResultSet resultset;

public DMLOperation() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306?useSSL=false", "root",
"root");

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();
}
}

public void insertRecord() {


try {
preparedstatement = connection.prepareStatement("insert into simpleproject.employee
values(?,?,?)");
do {
System.out.println("Enter employee : id , name,salary");

preparedstatement.setInt(1, scanner.nextInt());
preparedstatement.setString(2, scanner.next());
preparedstatement.setDouble(3, scanner.nextDouble());

preparedstatement.executeUpdate();
System.out.println("data inserted");
System.out.println("Enter 1: for one more data entery or other number for exit");
} while (scanner.nextInt() == 1);

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

public void updateRecord() {


System.out.println("Enter id of the employee who's record you want to update");
int id = scanner.nextInt();

System.out.println(
"Enter 1: id Updation" + "\r\n" + "Enter 2:name Updation" + "\r\n" + "Enter 3:salary
Updation");
int update = scanner.nextInt();
try {
if (update == 1) {

preparedstatement = connection.prepareStatement("update simpleproject.employee set id =?


where id =?");
System.out.println("Enter new Id:");
preparedstatement.setInt(1, scanner.nextInt());
preparedstatement.setInt(2, id);

} else if (update == 2) {

preparedstatement = connection
.prepareStatement("update simpleproject.employee set name =? where id =?");
System.out.println("Enter new name:");
preparedstatement.setString(1, scanner.next());
preparedstatement.setInt(2, id);

} else if (update == 3) {
preparedstatement = connection
.prepareStatement("update simpleproject.employee set salary =? where id =?");
System.out.println("Enter new salary:");
preparedstatement.setDouble(1, scanner.nextDouble());
preparedstatement.setInt(2, id);

}
preparedstatement.executeUpdate();
System.out.println("Record Updated");
} catch (SQLException e) {
e.printStackTrace();
}
}

public void deleteRecord() {

try {
preparedstatement = connection.prepareStatement("delete from simpleproject.employee where id =?");
System.out.println("Enter the id for delete");
preparedstatement.setInt(1, scanner.nextInt());

preparedstatement.executeUpdate();
System.out.println("Record deleted");

} catch (SQLException e) {

e.printStackTrace();
}

public void displayAll() {


try {
preparedstatement = connection.prepareStatement("select * from simpleproject.employee");
resultset = preparedstatement.executeQuery();
System.out.println("id" + "\t" + "name" + "\t" + "salary");
while (resultset.next()) {
System.out.println(resultset.getInt("id") + "\t" + resultset.getString("name") + "\t"
+ resultset.getDouble("salary"));
}
} catch (SQLException e) {

e.printStackTrace();
}

}
package com.jspider.dml;

import java.util.Scanner;

public class Test {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DMLOperation dmloperation = new DMLOperation();
do {
System.out.println("Enter 1 for insert data" + "\r\n" + "Enter 2 for update data" + "\r\n"
+ "Enter 3 for Delete Data");

int operation = scanner.nextInt();


dmloperation.displayAll();

if (operation == 1)
dmloperation.insertRecord();
else if (operation == 2)
dmloperation.updateRecord();
else if (operation == 3)
dmloperation.deleteRecord();
else
System.out.println("invalid option selected!!!!");

dmloperation.displayAll();

System.out.println("Enter 1 for repeat or Enter any number for exit:");


} while (scanner.nextInt() == 1);
}

}
Enter 1 for insert data
Enter 2 for update data
Enter 3 for Delete Data
1
id name salary
1 laxman 4500.0
2 raman 6200.0
3 kiran 7500.0
Enter employee : id , name,salary
4
prasant
4000
data inserted
Enter 1: for one more data entery or other number for exit
3
id name salary
1 laxman 4500.0
2 raman 6200.0
3 kiran 7500.0
4 prasant 4000.0
Enter 1 for repeat or Enter any number for exit:
1
Enter 1 for insert data
Enter 2 for update data
Enter 3 for Delete Data
2
id name salary
1 laxman 4500.0
2 raman 6200.0
3 kiran 7500.0
4 prasant 4000.0
Enter id of the employee who's record you want to update
2
Enter 1: id Updation
Enter 2:name Updation
Enter 3:salary Updation
2
Enter new name:
ram
Record Updated
id name salary
1 laxman 4500.0
2 ram 6200.0
3 kiran 7500.0
4 prasant 4000.0
Enter 1 for repeat or Enter any number for exit:
1
Enter 1 for insert data
Enter 2 for update data
Enter 3 for Delete Data
3
id name salary
1 laxman 4500.0
2 ram 6200.0
3 kiran 7500.0
4 prasant 4000.0
Enter the id for delete
4
Record deleted
id name salary
1 laxman 4500.0
2 ram 6200.0
3 kiran 7500.0
Enter 1 for repeat or Enter any number for exit:
10
Stored procedure: Video: 18

 It is a set of frequently executing precompiled queries stored in database.

How to create Stored Procedure:

Go to HeidiSQL---------- select jspiders----------student----------right click--------Create new-----select Stored procedure------


Name:selectingAll-------BEGIN SELECT * FROM jspiders.student; END

Statement

extends

PreparedStatement

extends

CallableStatement

CallableStatement :

 It is a platform to execute SQL queries.


 This is also interface present in java.sql package
 CallableStatement supports Stored procedure concept.
 CallableStatement extends PreparedStatement
 CallableStatement processing time is less compare to PreparedStatement

How to create CallableStatement platform?

prepareCall() method used to create CallableStatement platform.

prepareCall() :

 It is a method of Connection interface


Syntax: public CallableStatement prepareCall(String query)
package com.jsp.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StoredProcedureExample {


static Connection connection;
static CallableStatement callablestatement;
static ResultSet resultset;

public static void main(String[] args) {

try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306?useSSL=false","root", "root");

callablestatement=connection.prepareCall("call jspiders.selectingAll");
resultset=callablestatement.executeQuery();

System.out.println("sid"+"\t"+"sname"+"\t"+"marks");
while(resultset.next())

System.out.println(resultset.getInt("sid")+"\t"+resultset.getString("sname")+"\t"+resultset.getDouble("marks"));

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();
}

}
Output:
sid sname marks
1 anant 80.0
2 mark 50.0
3 priyank70.0
4 roshan 82.55
5 sunil 50.0
6 ganesh 99.5
7 jack 71.0
package com.jsp.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class InsertCallable {

static Connection connection;


static CallableStatement callablestatement;

public static void main(String[] args) {

try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306?useSSL=false","root", "root");

callablestatement=connection.prepareCall("call jspiders.insertRecord");
callablestatement.executeUpdate();

System.out.println("data inserted");

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();
}
This program is not recommended because
} query is tight coupling
Output: data inserted
}
package com.jsp.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Scanner;

public class InsertCallable {

static Connection connection;


static CallableStatement callablestatement;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
try {
Class.forName("com.mysql.cj.jdbc.Driver");

connection=DriverManager.getConnection("jdbc:mysql://localhost:3306?useSSL=false","root", "root");

callablestatement=connection.prepareCall("call jspiders.insertRecord(?,?,?,?,?)");
System.out.println("Enter id, name, marks, mobile,address ");
callablestatement.setInt(1, scanner.nextInt());
callablestatement.setString(2, scanner.next());
callablestatement.setDouble(3, scanner.nextDouble());
callablestatement.setLong(4, scanner.nextLong());
callablestatement.setString(5, scanner.next());
Output:
callablestatement.executeUpdate(); Enter id, name, marks, mobile,address
11
System.out.println("data inserted"); sita
58
} catch (ClassNotFoundException | SQLException e) { 8249633792
delhi
e.printStackTrace(); data inserted
}

}
WAP to fetch the data without using ResultSet? Video: 19
package com.jsp.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Scanner;

public class OutParameterExample {


static Connection connection;
static CallableStatement callablestatement;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306?useSSL=false", "root",
"root");

callablestatement = connection.prepareCall("call jspiders.fetching(?,?,?,?)");


System.out.println("Enter the id :");

callablestatement.setInt(1, scanner.nextInt());
callablestatement.registerOutParameter(2, Types.DECIMAL);
callablestatement.registerOutParameter(3, Types.VARCHAR);
callablestatement.registerOutParameter(4, Types.BIGINT);

callablestatement.executeQuery();

System.out.println(callablestatement.getDouble(2) + "\t" + callablestatement.getString(3) + "\t"


+ callablestatement.getLong(4));
Output:
} catch (ClassNotFoundException | SQLException e) {
Enter the id :
e.printStackTrace(); 10
} 97.87 gita 9824567985
}

}
Batch file : Java Prgm Video: 20
 It is a file contains set of queries which are going to execute at one shot. 10 queries add to
 Batch file will not visible for you it is like a virtual file which contains set of queries. batch file
 Batch file works only for DML queries.
 In case of multiple (DML) queries instead of executing the query we push the query into Batch file.
 Once every queries is pushed then we execute the batch file Database
addBatch():

 This method is used for pushing the query to batch file


 Syntax: public void addBatch(String query)-------Statement
 Syntax: public void addBatch()---------PreparedStatement

executeBatch():

 It is a method of Statement interface.


 This method used for executing batch file.
 Syntax: public int[] executeBatch()
PreparedStatement:

int[] : Each element of the array represent number of rows got effected by each query in the batch batch file. 10 queries ---1 time Compilation
and 10 time execution.
package com.jsp.jdbc;
import java.io.FileInputStream; Batch file:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
10 queries ---1 time compilation
import java.sql.PreparedStatement; and 1time execution.
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;
import java.util.Scanner;

public class BatchFileExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Connection connection = null;
PreparedStatement preparedstatement = null;

System.getProperty("jdbc");
try {
FileInputStream fileinputstream = new FileInputStream("lib/jdbcdata.properties");
Properties properties = new Properties();
properties.load(fileinputstream);

Class.forName(properties.getProperty("driver"));
connection = DriverManager.getConnection(properties.getProperty("url"));

String query = "insert into oejm2.employee values(?,?,?)";


preparedstatement = connection.prepareStatement(query);
do {
System.out.println("Enter id, name , salary");
preparedstatement.setInt(1, scanner.nextInt());
preparedstatement.setString(2, scanner.next());
preparedstatement.setDouble(3, scanner.nextDouble());

preparedstatement.addBatch(); This will add the number queries in Batch file


System.out.println("DataInserted");
System.out.println("Enter 1 for inserting one more data: ");
} while (scanner.nextInt() == 1);

int arr[]=preparedstatement.executeBatch();
System.out.println(Arrays.toString(arr)); This will execute all the queries present in Batch
System.out.println("check the database:");
file in single execution.

} catch (IOException | ClassNotFoundException | SQLException e) {

e.printStackTrace();
}
}
}
Output:

Enter id, name , salary


1
keran
5000
DataInserted
Enter 1 for inserting one more data:
1
Enter id, name , salary
2
ranveer
3000
DataInserted
Enter 1 for inserting one more data:
1
Enter id, name , salary
3
kriti
6000
DataInserted
Enter 1 for inserting one more data:
5
[1, 1, 1]
check the database: This represents Number of rows
affected by each queries.
DataBaseMetaData: (very rarely used) Video: 21
 It gives data about database
 By this DataBaseMetaData we can get information about database like database name, data base, data base version (major
and minor), Driver name, username, url etc....
 DataBaseMetaData is an interface present in java.sql package........
 We can create Object of DataBaseMetaData by using getMetaData()

getMataData():

 It is method of Connection interface


 Syntax: public DataBaseMetaData getMetaData()

package com.jsp.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DataBaseInformation {

public static void main(String[] args) {


Connection connection = null;
DatabaseMetaData databasemetadata = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306?useSSL=false", "root",
"root");
databasemetadata = connection.getMetaData();

System.out.println("DataBase Information:");
System.out.println("DataBase Name:" + databasemetadata.getDatabaseProductName());
System.out.println("DataBase version:Major-" + databasemetadata.getDriverMajorVersion() + "\t"
+ "DataBase version: Minor" + databasemetadata.getDriverMinorVersion());
System.out.println("URL=" + databasemetadata.getURL());
System.out.println("Driver Name=" + databasemetadata.getDriverName());
System.out.println("Driver Version Major=" + databasemetadata.getDriverMajorVersion() + "\t" +
"Minor="+ databasemetadata.getDriverMinorVersion());

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();
}
Output:
}
DataBase Information:
} DataBase Name:MySQL
DataBase version:Major-8 DataBase version: Minor0
URL=jdbc:mysql://localhost:3306?useSSL=false
Driver Name=MySQL Connector/J
Driver Version Major=8 Minor=0
ResultSetMetaData: (very rarely used)
video: 21
 It is used to get meta data on resultant table (not from database)
 It is an interface present in java.sql package
 We can create Object of ResultSetMetaData by getMetaData()
 It is used to get information like Table Name, number of columns, column names, column data types etc.

getMetaData():

 It is a method of ResultSet interface


 Syntax: public ResultSetMetaData getMetaData()

package com.jsp.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class ResultSetDataInformation {

public static void main(String[] args) {


Connection connection = null;
Statement statement = null;
ResultSet resultset = null;
ResultSetMetaData resultsetmetadata = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306?useSSL=false", "root",
"root");
statement = connection.createStatement();

resultset = statement.executeQuery("select id as employeeid,salary as monthlysalary from


oejm2.employee");

resultsetmetadata = resultset.getMetaData();

int columncount = resultsetmetadata.getColumnCount();


System.out.println("Resultant Table Information:");
System.out.println("Number columns:" + columncount);

System.out.println("ColumnNames"+"\t"+"datatypes"+"\t"+"aliasname");
for (int i = 1; i <= columncount; i++) {

System.out.println(resultsetmetadata.getColumnName(i)+"\t\t"+resultsetmetadata.getColumnTyp
eName(i)+"\t\t"+resultsetmetadata.getColumnLabel(i));
}

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();
}
} Output:
}
Resultant Table Information:
Number columns:2
ColumnNames datatypes aliasname
id INT employeeid
salary DECIMAL monthlysalary
Video=22

Server:
 It is a machine which accepts the user request, process the request and get back some response.
 Server also manages the resource present in server machine.
 There are 2 type of server:
1. Web server
2. Application server Server:
Client
Web server: It can only process web request that is http request. app
Application server: It act like web server as well as it can run big Browser app
Application like EJB (Enterprise Java Bean).
app

Video: 22_A.java_20.07.21_REC

How to install apache Tomcat? Video: 29:00 duration

Video: 23

Servlet :

 Servlet is a specification(rule) to develop web application


 Servlet is an API given in the form of JAR file
 API conatins two package:
1. Javax.servlet
2. Javax.servlet.http
 Servlet is a package present in ServletAPI
 Servlet is also an interface present in javax.servlet package
 Servlet is a server side java program
Interfaces of javax.servlet package:
 Servlet
 ServletRequest
 ServletResponse
 ServletContext
 ServletConfig
 RequestDispatcher
 Filter
 FilterChain Filter API
 FilterConfig
(Security purpose)

Classes of javax.servlet
 GenericServlet
 ServletException

Server
http request
container
Client
Browser
App1
Configuration file

web.xml

Every web application must contains only one (minimum


one or maximum one) web.xml
container may also called as:
 servlet container
 jsp container
 web container
 jee container
actually name of container is: CATALINA
How to create Web Project?

1. Ctrl+N or Right Click


2. New
3. Project
4. Search Web Folder
5. In Web Folder : Select Dynamic Web Poject
6. Next>
7. Project Name: Web apps , Dynamic web module version: 3.0
8. Finish

Here java program made

I have already selected server from and added to my


Servers or you can go to Tomcat folder then go to lib folder
search for sevlet-api.jar copy and paste to lib folder of your
project or follow video (23_A.java_21.07.21_REC) Or video
(25_A.java_23.07.21_REC) from 58:00:00 time

lib Folder: here only we place external library


file

How to generate web.xml files?

1. Select project i.e.: Webapps


2. Right click
3. Java EE tools
4. Generate Deployment Descriptor Stub
web.xml: here only we do configuration

How to create HTML file?

1. Select webapp folder


2. Right click
3. New
4. HTML file
5. File Name: example.html
6. Finish
package com.jsp.webapps;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFirstServlet 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 this is printed in console");
PrintWriter out = arg1.getWriter();
out.println("<html><body><h1>Hi good Morning</h1></body></html>");

example.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="hi"> click here </a>
</body>
</html>
web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd"
version="3.0">
<display-name>Webapps</display-name>
<welcome-file-list>
<welcome-file>example.html</welcome-file>
URN (Uniform resource name) or
</welcome-file-list> name of the servlet
<servlet>
<servlet-name>myfirst</servlet-name>
<servlet-class>com.jsp.webapps.MyFirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myfirst</servlet-name>
<url-pattern>/hi</url-pattern> Give qualified name:
</servlet-mapping>
1. Go to :class MyFirstServlet
</web-app>
2. click to MyFirstServlet
3. Copy Qualified Name
4. And paste it here

How to run the server of tomcat?

1. Go to Console then open the Servers


2. Start the server or ctrl+alt+R
3. It will show the server started
4. Open the Browser
5. Url=http://localhost/Webapps

OR

First time running then it is compulsory to follow


below steps:
1. Select the project: Webapps
2. Right click
3. Run as
4. Run on Server
5. Select:Tomcat v9.o Server at localhost
6. Finish
7. It will directly open the Open the Browser
Servlet interface:
Video:24
 It is a interface present in javax.servlet package
 It is a root interface of server side java program
 It contains some methods which are used for accepting the request and processing the request, processing the request, get
back some response.
Method of Servlet interface:
1. init()-------> it is used for initialization process. It is executed at the beginning.
Syntax: public void init(ServletConfig arg0) throws ServletException{}
2. service()-----> This is the main method of Servlet interface , this method accept the request, process the request by
the Business logic present in it, and get some response to client.

Syntax:public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException{}

3. destroy()----->This method executed just before removing the Servlet object(during undeployment of Servlet/ shut
down the server)
Syntax: public void destroy(){}
4. getServletInfo()-----> It is used to give information about the servlet
Syntax: public String getServletInfo(){}
5. getServletConfig()-------> It is used for getting the ServletConfig object
Syntax: public ServletConfig getServletConfig(){}
Note:
Servlet Life cycle (very important):
 In a server N number of
 It is the activity performed during the execution of Servlet application can be present.
 In an application we can have N
 Stages:
number of Servlet.
1. instantiation phase
2. initialization phase
3. service phase
4. Destroy phase
1. Instantiation phase: Here object of Servlet class is created by container.

Whenever Servlet receive first request then this phase will be executed once.

2. Initialization phase: Here in this phase initialization of servlet can be done.


Here init() is called right after the instantiation
init()/initialization phase is executed once in the life time of servlet.

3. Service phase: this phase is executed after the init() called .


In this phase service method will be called, in service method we place main business logic which
process the request and get response to client.
service() executed again and again for each time when it receive request.

4. Destroy phase: this phase executes when server will shutdown/undeployment of application done.
Here destroy() will be called just before removing servlet object.

Life Cycle Method :

init()

service() These three methods are life cycle of servlet.

destroy()
xml:
 It is a configuration file.
 By using this we can configure the application.
 Here we use some custom tags to configure the resource.
 All web application must has a one xml file name as web.xml

web.xml:

 It is used to configuring the web applications


 Main root tag is: <web-app> </web-app>
<servlet>
Servlet Configuration: <servlet-name></servlet-name>
<servlet-class> fully qualified name of servlet class </servlet-class>
</servlet>

Servlet Mapping: It helps the container to pass the request to a particular servlet.
<servlet-mapping>
<servlet-name></servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>

Video: 25

GenericServlet:

 It is an abstract class present in javax.servlet package.


 This class implements Servlet interface and provide implementation for every method except service()
 It provide all type of request, it is not bound to any protocol.
Servlet( interface)

Request (object):
tellfortune Container

Client
implements

GenericServlet (abstract class)


Response
 Its override all the method
web.xml
except service() i.e. abstract
service()

extends

MyFirstServlet (developer class)

 It need to Override only


service()
PrintWriter:

 It is a class present in java.io package.


 PrintWriter is capable of writing content to response object.
 We can get the PrintWriter object by using a method getWriter()

getWriter():

 It is non-static method of ServletResponse interface.

Create: Dynamic Web Project --------Webapps2

Generate: web.xml file in lib folder

Create: html file i.e. Home.html


web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd"
version="3.0">

<welcome-file-list>
<welcome-file>Home.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>fortune</servlet-name>
<servlet-class>com.example.FortuneTeller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fortune</servlet-name>
<url-pattern>/tellfortune</url-pattern>
</servlet-mapping>
</web-app>

Home.html
If this both URL Pattern name is not same then
<!DOCTYPE html>
it will give: HTTP Status 404 –Not Found
<html>
<head> (Generally we say 404-Error)
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<a href="tellfortune">Click Here</a>

</body>
</html>
package com.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FortuneTeller extends GenericServlet {

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub

String[] arr = { "your day is going to be awesome", "you will become very famous in future",
"you will get job soon if you work hard", "you will get married soon" };
Random random = new Random();
int randomnumber=random.nextInt(arr.length-1);

//System.out.println(arr[randomnumber]);
This will print in the console

PrintWriter out = arg1.getWriter();


out.println("<html><body><h1>"+arr[randomnumber]+"</h1></body></html>");

Run the Server (Tomcat v9.0 Server at localhost)

Go to Browser: http://localhost:8080/Webapps2 ------- Enter or select Webapps2 ---right click---Run As---Run on Server
This will randomly generate to client
by go back to: Click Here

How to Change Web Browser Setting when you Run on Server?

Click the -----Window-----Web Browser-------then you can select browser i.e. Chrome

The above process need only one time for changing Browser
How to generate Random Number?

It is present in: java.util.Random

Random random = new Random();


int randomnumber=random.nextInt(6);
6 is the argument which generate limit
between 0 to 6

Video: 26

Request (Object):
url:
data:us=ram Container

Client

Response (Object)
Web.xml

getParameter():

 It is a method of ServletRequest interface used for extracting value from request object.
 Syntax: public String getParameter(String key){}
Updating the previous Program: Home.html, FortuneTeller.java

Home.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<style type="text/css">
input[type="submit"] {
margin-top: 10px;
}
</style>
</head>
<body>
<div>
<form action="tellfortune">
<div>
Name:<input type="text" name="us">
</div>
<div>
<input type="submit" value="get Fortune">
</div>
</form>
</div>

</body>
</html>

FortuneTeller.java

package com.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FortuneTeller extends GenericServlet {

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = arg0.getParameter("us");

String[] arr = { "your day is going to be awesome", "you will become very famous in future",
"you will get job soon if you work hard", "you will get married soon" };
Random random = new Random();
int randomnumber = random.nextInt(arr.length - 1);

// System.out.println(arr[randomnumber]);

PrintWriter out = arg1.getWriter();


out.println("<html>");
out.println("<body>"); Not Recommended but
out.println("<h1>Hi "+name+" your fortune is <br>"+arr[randomnumber]);
out.println("</h1>"); we can do
out.println("</body>");
out.println("</html>");
// OR
// out.println("<html>"
// + "<body>"
// + "<h1>Hi " + name + " your fortune is <br>" + arr[randomnumber]
// + "</h1>" Recommended
// + "</body>"
// + "</html>");

}
Create: Dynamic Web Project(Webapps3)
Video: 27
Create: web.xml

Create: home.html

Create: package (com.technical) and classes (ShowForm, ProcessData)

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Webapps3</display-name>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>form</servlet-name>
<servlet-class>com.technical.ShowForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>form</servlet-name>
<url-pattern>/showform</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>process</servlet-name>
<servlet-class>com.technical.ProcessData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>process</servlet-name>
<url-pattern>/pform</url-pattern>
</servlet-mapping>

</web-app>

Home.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome</title>
<style type="text/css">
img {
width: 400px;
height: 400px;
}
.side {
display: inline-block;
}
</style>
<title>Insert title here</title>
</head>
<body>
<div class="side">
<h1>Welcome to Technical Company</h1>
</div>
<div class="side"> Download the Image and copy the image
<a href="showform">Career</a> and paste on the webapp folder of the
</div> Project.
<div>
<img src="pexels-pixabay-269077.jpg">
</div>

</body>
</html>
ShowForm.java

package com.technical;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ShowForm extends GenericServlet {

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out =arg1.getWriter();
out.println("<html>\r\n"
+ " <head>\r\n"
+ " <style>\r\n"
+ "\r\n" //do by your self
+ " </style>\r\n"
+ " </head>\r\n"
+ " <body>\r\n"
+ " <div>\r\n"
+ " <form action='pform'>\r\n"
+ " <div>\r\n"
+ " Name:<input type=\"text\" name=\"us\">\r\n"
+ " </div>\r\n"
+ " <div>\r\n"
+ " Email:<input type=\"text\" name=\"em\"\r\n"
+ " </div>\r\n"
+ " <div>\r\n"
+ " <input type=\"submit\" value=\"register\"\r\n"
+ " </div>\r\n"
+ " </form>\r\n"
+ " </div>\r\n"
+ " </body>\r\n"
+ "\r\n" This html is made in Visual Studio
+ "</html>"); app copied and pasted here
// out.println("<html>"
// + "<head>" OR
// + "<style>"
// + "" In eclipse also you can make
// + "</style>"
// + "</head>"
// + "<body>"
// + "<div>"
// + "<form>"
// + "<div>"
// + "Name:<input type='text' name='us'>"
// + "</div>"
// + "<div>"
// + "Email:<input type='text' name='em'>"
// + "</div>"
// + "<div>"
// + "<input type='submit' value='register'>"
// + "</div>"
// + "</form>"
// + "</div>"
// + "</body>"
// + "</html>");
//
}
}
ProcessData.java

package com.technical;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ProcessData extends GenericServlet {

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=arg0.getParameter("us");
String email= arg0.getParameter("em");

PrintWriter out =arg1.getWriter();


out.println("<html><body><h1>HI "+ name+" your Registration suceessfull "
+ "you will receive job Details on your email:"+email
+ "</h1></body></html>");

}
Now: Run the Server
Overview of Project

Every kind of .jar file should be


pasted here that is in lib folder

Flow of the Project


RequestDispatcher:

 It is a interface of ServletAPI , it is present in javax.servlet package


 It is used for sending same request to next Resource (resource can be another servlet or a html page or a jsp page).

Container

Client servlet
LoginValidation
User: Database

Password:

Create Database in HeidiSQL: xyzcompany

Give table name as: logininfo

Create table column: username and password

Insert two data for checking: abc , abc123 and xyz ,xyz123
Create: Dynamic Web Project Name: RequestDispatcherExample

Create: web.xml

Create: login.html

Copy the mysql-connector-j-8.0.32.jar file and paste in lib folder

package com.rdexample;

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.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class LoginValidation extends GenericServlet {

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException
{
// TODO Auto-generated method stub
String user = arg0.getParameter("us");
String pass = arg0.getParameter("ps");
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
PrintWriter out = arg1.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root");
pst = cn.prepareStatement("select * from xyzcompany.logininfo where username=?");
pst.setString(1, user);

rs = pst.executeQuery();
if (rs.next()) {
String dpass = rs.getString("password");
if (pass.equals(dpass)) {
out.println("<html><body><h1>Welcome.....you successfully
login</h1></body></html>");
} else {
out.println("<html><body><h1>Check your password</h1></body></html>");
}
} else {
out.println("<html><body><h1>Check your username</h1></body></html>");
}

} catch (ClassNotFoundException | SQLException e) {


// TODO Auto-generated catch block
e.printStackTrace();
}

}
web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_4_0.xsd"
version="4.0">
<display-name>RequestDispatcherExample</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.rdexample.LoginValidation</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/log</url-pattern>
</servlet-mapping>
</web-app>

Login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<div>
<form action="log">
<div>
User Name:<input type="text" name="us">
</div>
<div>
Password:<input type="password" name="ps">
</div>
<div>
<input type="submit" value="log in">
</div>
</form>
</div>
</body>
</html>
Run the Server

If your username and password


matched with database in xyzcompany
then it will show this kind of output.

When your username is not matched with


database then it will show this kind of output.
When your username is matched with database but
password is not matched then it will show this kind of
output

RequestDispatcher:

 It is a interface of ServletAPI , it is present in javax.servlet package


 It is used to redirect (for sending same) the request to next Resource (resource can be another servlet or an html page or
a jsp page).
 We can get the object of RequestDispatcher by getRequestDispatcher()
 getRequestDispatcher(): It is a method of ServletRequest interface

RequestDispatcher contain 2 methods:


1. forward()
2. include()

forward():
request Container
na=

Client
First Second

Same Request will be send to


Second with the help of
RequestDispatcher: method
name forward()
Create Dynamic Web Project name: forwardExample

Create: web.xml

Create: NewFile.html

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>forwardExample</display-name>
<welcome-file-list>
<welcome-file>NewFile.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>fir</servlet-name>
<servlet-class>com.forwardExample.First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fir</servlet-name>
<url-pattern>/one</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sec</servlet-name>
<servlet-class>com.forwardExample.Second</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sec</servlet-name>
<url-pattern>/two</url-pattern>
</servlet-mapping>
</web-app>

NewFile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
<form action="one">
Name:<input type="text" name="na"><br> <input
type="submit">
</form>
</div>
</body>
</html>
First.java

package com.forwardExample;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class First extends GenericServlet {

@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=req.getParameter("na");
System.out.println("First servlet getting name="+name);
RequestDispatcher rd=req.getRequestDispatcher("two");
request and response has
rd.forward(req, resp);
been send to : class Second
PrintWriter out = resp.getWriter();
out.println("<html><body><h1>First servlet saying name="+name+"</h1></body></html>");
}

this will not print in client page bcz request and


response has been forwarded to Second servlet that is
Second.java so it is not need to write the programe

Second.java

package com.forwardExample;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Second extends GenericServlet {

@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=req.getParameter("na");
PrintWriter out=resp.getWriter();
out.println("<html><body><h1> This is Second Servlet response "+name+"</h1></body></html>");
}

} This will print in the client page

Run the Server.


Overview of the Project

include():

Container

IncludeExample

Client

Name: First Second


submit

Request and Response will be sending from


the First Servlet class to Second Servlet class
by help of RequestDispatcher: mehod name:
include()
Create a Dynamic Web Project: includeExample

Create: web.xml

Create: NewFile.html

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>includeexample</display-name>
<welcome-file-list>
<welcome-file>NewFile.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>fir</servlet-name>
<servlet-class>com.includeexample.First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fir</servlet-name>
<url-pattern>/oneinclude</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sec</servlet-name>
<servlet-class>com.includeexample.Second</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sec</servlet-name>
<url-pattern>/twoinclude</url-pattern>
</servlet-mapping>
</web-app>

NewFile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
<form action="oneinclude">
Name:<input type="text" name="na"><br> <input
type="submit">
</form>
</div>
</body>
</html>
First.java

package com.includeexample;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class First extends GenericServlet {

@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException
{
// TODO Auto-generated method stub
String name=req.getParameter("na");
System.out.println("First servlet getting name="+name);
RequestDispatcher rd=req.getRequestDispatcher("twoinclude");
rd.include(req, resp);

PrintWriter out = resp.getWriter();


out.println("<html><body><h1>First servlet saying name="+name+"</h1></body></html>");
}

} include() return back from second servlet to first


servlet and execute the remaining part

Second.java

package com.includeexample;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Second extends GenericServlet {

@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException
{
// TODO Auto-generated method stub
String name=req.getParameter("na");
PrintWriter out=resp.getWriter();
out.println("<html><body><h1> This is Second Servlet response "+name+"</h1></body></html>");
}
}

Run the Server: Run As-- Run on server


Overview of Project

If this Kind of Error is giving then go to Video: 28_A.java_27.07.21_REC

At time: 1:02:54
forward():

 It is used to forward the request and response to the next Resource


 Once we done forward total control will go to next Resource
 Method signature: public void forward(ServletRequest agr0, ServletResponse arg1)

Include():

 It is used to pass the request and response object to next resource, once the next resource executed it include the
response of next resource in the current servlet.
 Method signature: public void include(ServletRequest agr0, ServletResponse arg1)

Another Project: RequestDispatcherExample( if this project already there then no need of Creating Database Table)

Create Database in HeidiSQL: xyzcompany

Give table name as: logininfo

Create table column: username and password

Insert two data for checking: abc , abc123 and xyz ,xyz123
Create: Dynamic Web Project Name: RequestDispatcherExample(if this project is already there then only update it)

Create: web.xml

Create: login.html, profile.html

Copy the mysql-connector-j-8.0.32.jar file and paste in lib folder

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_4_0.xsd"
version="4.0">
<display-name>RequestDispatcherExample</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.rdexample.LoginValidation</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/log</url-pattern>
</servlet-mapping>
</web-app>

login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<div>
<form action="log">
<div id='userError'></div>
<div>
User Name:<input type="text" name="us">
</div>
<div id='passError'></div>
<div>
Password:<input type="password" name="ps">
</div>
<div>
<input type="submit" value="log in">
</div>
</form>
</div>
</body>
</html>
LoginValidation.java

package com.rdexample;

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.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class LoginValidation extends GenericServlet {

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
String user = arg0.getParameter("us");
String pass = arg0.getParameter("ps");
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
PrintWriter out = arg1.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root");
pst = cn.prepareStatement("select * from xyzcompany.logininfo where username=?");
pst.setString(1, user);

rs = pst.executeQuery();
if (rs.next()) {
String dpass = rs.getString("password");
if (pass.equals(dpass)) {
RequestDispatcher rd = arg0.getRequestDispatcher("profile.html");
rd.forward(arg0, arg1);
} else {
RequestDispatcher rd = arg0.getRequestDispatcher("login.html");
rd.include(arg0, arg1);
out.println("<body><script> document.getElementById('passError').innerHTML='Check Password';"
+ "document.getElementById('passError').style.color='red'</script></body>;");
}
} else {
RequestDispatcher rd = arg0.getRequestDispatcher("login.html");
rd.include(arg0, arg1);
out.println("<body><script> document.getElementById('userError').innerHTML='Check UserId';"
+ "document.getElementById('userError').style.color='red'</script></body>;");
}

} catch (ClassNotFoundException | SQLException e) {


// TODO Auto-generated catch block
e.printStackTrace();
}

} This are written in javascript


}
language
profile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome to Profile page</h1>
<h2>you successfully logged in</h2>
<p>This is a html page</p>

</body>
</html>

Run the server:

If UserName and Password both are matching with


database then it will go to
If UserName is not matched with database then it
will show like this

If Password is not matched with Database then it will show


like this:
Overview of the Project: RequestDispatcherExample

Video: 29
ServletContext:

 It is a interface present in javax.servlet package


 ServletContext object is known as context object
 For every application in server a context Object is created by container.
 When we deploy(pushing) the application into the server then context object creation happen

Context Object can be used for:


 Configuring entire application
 Intercommunication of servlet
We can get the object of ServletContext by using a method:
getServletContext()

getServletContext ():
it is a method of GenericServlet
method Signature: public ServletContext getServletContext(){}
web.xml

Create data

In one web server there are nth no. of


Pushing data

application can be present

Context Object
App1 App2
driver=com.mysql
.cj.jdbc.Driver
Servlet1 Servlet2 Context Object

App3

Context Object

Another Project:

Update the project i.e: RequestDispatcherExample.

Or

Create Dynamic Web Project: RequestDispatcherExample

Create: web.xml

Create: login.html, profile.html, signup.html

Copy the mysql-connector-j-8.0.32.jar file and paste in lib folder

Create database in HeidiSQL ie: xyzcompany then create two Tables: 1. information:(column name : name, mobile, email, username )

2: logininfo: (column name:username,password)


web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_4_0.xsd"
version="4.0">
<display-name>RequestDispatcherExample</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.cj.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306?useSSL=false</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>root</param-value>
</context-param>

<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.rdexample.LoginValidation</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/log</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sign</servlet-name>
<servlet-class>com.rdexample.SignUpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sign</servlet-name>
<url-pattern>/signup</url-pattern>
</servlet-mapping>
</web-app>
login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<div>
<form action="log">
<div id='userError'></div>
<div>
User Name:<input type="text" name="us">
</div>
<div id='passError'></div>
<div>
Password:<input type="password" name="ps">
</div>
<div>
<input type="submit" value="log in">
</div>
<div><a href="signup.html">Sign up</a></div>
</form>
</div>
</body>
</html>

package com.rdexample;

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.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class LoginValidation extends GenericServlet {

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
String user = arg0.getParameter("us");
String pass = arg0.getParameter("ps");

ServletContext con = getServletContext();


String driver = con.getInitParameter("driver");
String url = con.getInitParameter("url");
String dbuser = con.getInitParameter("user");
String dbpass = con.getInitParameter("password");

Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
PrintWriter out = arg1.getWriter();
try {
Class.forName(driver);
cn = DriverManager.getConnection(url, dbuser, dbpass);
pst = cn.prepareStatement("select * from xyzcompany.logininfo where username=?");
pst.setString(1, user);

rs = pst.executeQuery();
if (rs.next()) {
String dpass = rs.getString("password");
if (pass.equals(dpass)) {
RequestDispatcher rd = arg0.getRequestDispatcher("profile.html");
rd.forward(arg0, arg1);
} else {
RequestDispatcher rd = arg0.getRequestDispatcher("login.html");
rd.include(arg0, arg1);
out.println("<body><script> document.getElementById('passError').innerHTML='Check
Password';"
+
"document.getElementById('passError').style.color='red'</script></body>;");
}
} else {
RequestDispatcher rd = arg0.getRequestDispatcher("login.html");
rd.include(arg0, arg1);
out.println("<body><script> document.getElementById('userError').innerHTML='Username not
present..Signup first to do login';"
+
"document.getElementById('userError').style.color='red'</script></body>;");
}

} catch (ClassNotFoundException | SQLException e) {


// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

profile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome to Profile page</h1>
<h2>you successfully logged in</h2>
<p>This is a html page</p>
</body>
</html>
signup.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
<form action="signup">
<div>
Name:<input type="text" name="na">
</div>
<div>
Mobile:<input type="text" name="mob">
</div>
<div>
Age:<input type="number" name="age">
</div>
<div>
Email:<input type="text" name="em">
</div>
<div>
UserName:<input type="text" name="us">
</div>
<div>
Password:<input type="text" name="ps">
</div>
<div>
<input type="submit" value="Sign Up">
</div>
<div>
<input type="reset" value="Reset">
</div>
</form>
</div>
</body>
</html>
package com.rdexample;

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.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SignUpServlet extends GenericServlet {

@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=req.getParameter("na");
String mobile=req.getParameter("mob");
//int age=Integer.parseInt(req.getParameter("age"));
String pass = req.getParameter("ps");
String user=req.getParameter("us");
String email=req.getParameter("em");

ServletContext con = getServletContext();


String driver = con.getInitParameter("driver");
String url = con.getInitParameter("url");
String dbuser = con.getInitParameter("user");
String dbpass = con.getInitParameter("password");

Connection cn = null;
PreparedStatement pst = null;

try {
Class.forName(driver);
cn=DriverManager.getConnection(url,dbuser,dbpass);
pst=cn.prepareStatement("insert into xyzcompany.information values(?,?,?,?)");

pst.setString(1, name);
pst.setString(2, mobile);
pst.setString(3, email);
pst.setString(4, user);

pst.executeUpdate();
pst=cn.prepareStatement("insert into xyzcompany.logininfo values(?,?)");
pst.setString(1, user);
pst.setString(2,pass);

pst.executeUpdate();

PrintWriter out = resp.getWriter();


out.println("<html><body><h3>Sucessfully Registered</h3></body></html>");

// RequestDispatcher rd=req.getRequestDispatcher("login.html");
// rd.include(req, resp);
// Or
req.getRequestDispatcher("login.html").include(req, resp);

} catch (ClassNotFoundException | SQLException e) {


// TODO Auto-generated catch block
e.printStackTrace();
}

}
Run the server:

This is login page:

If User Name is not matched with database

Singn Up page which data will stored in database


Successfully store the data in database

Data entered in Database


If User Name and Password are matched with database then:

If User Name is matched and password is not matched with


database
Overview of Project

Video: 30

New Project: intercommunication

Create Dynamic Web Project: intercommunication

Create web.xml One


Context Object:
Push data
Create NewFile.html info=Name
Name

Client
Form + Name

Two
lname

Name+lname
web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>intercommunication</display-name>
<welcome-file-list>
<welcome-file>NewFile.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.intercommunication.One</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/fir</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>second</servlet-name>
<servlet-class>com.intercommunication.Two</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/sec</url-pattern>
</servlet-mapping>
</web-app>

NewFile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="fir">

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


<br> <input type="submit">

</form>
</body>
</html>
One.java
package com.intercommunication;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class One extends GenericServlet{

@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=req.getParameter("na");

name=name.toUpperCase();

ServletContext con=getServletContext();
con.setAttribute("info",name );

PrintWriter out=resp.getWriter();
out.println("<html><body>your First name is "+name+""
+ "<form action='sec'>"
+ "Last Name:<input type='text' name='lname'><br><br>"
+ "<input type='submit'>"
+ "</form>"
+ "</body></html>");
}
}

Two.java
package com.intercommunication;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Two extends GenericServlet {

@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String lname = req.getParameter("lname");

lname = lname.toUpperCase();

ServletContext con=getServletContext();
String fname=(String) con.getAttribute("info");

String fullname = fname+" "+lname;

PrintWriter out = resp.getWriter();


out.println("<html><body>your Last name is " + lname
+ " Your full name is = " +fullname
+ "</body></html>");
}

}
ServletConfig:
 It is interface present in javax.servlet package
 SevletConfig object simply known as config object
 For every servlet in the application a config Object is created by Container, Container create config object when the
Servlet receive first request.
 We can get the object of config object by getServletConfig() present in the Servlet interface
 Method Signature: public ServletConfig getServletConfig(){}
 This method is used to configuring the Servlet

Context
Object
Servlet
Servlet
Config Config
Object Object

web.xml
Servlet

Config
Object

New Project:

Create Dynamic Web Project: ServletConfigExample

Create web.html

Create home.html

Download 3 laptop images in jpg format and copy those 3 images and paste it in webapp folder of the project
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>ServletConfigExample</display-name>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>laptop</servlet-name>
<servlet-class>com.ServletConfigExample.ShowLaptop</servlet-class>

<init-param>
<param-name>lap1img</param-name>
<param-value>laptop.jpg</param-value>
</init-param>
<init-param>
<param-name>lap1text</param-name>
<param-value>mi</param-value>
</init-param>

<init-param>
<param-name>lap2img</param-name>
<param-value>laptop02.jpg</param-value> Here we do changes of the images
</init-param> and value of the image if we want
<init-param>
<param-name>lap2text</param-name> to so it won’t require accessing
<param-value>dell</param-value> Servlet class
</init-param>

<init-param>
<param-name>lap3img</param-name>
<param-value>laptop03.jpg</param-value>
</init-param>
<init-param>
<param-name>lap3text</param-name>
<param-value>sony</param-value>
</init-param>

</servlet>
<servlet-mapping>
<servlet-name>laptop</servlet-name>
<url-pattern>/showlaptop</url-pattern>
</servlet-mapping>
</web-app>

home.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a>Mobile</a>
<a href="showlaptop">Laptop</a>
<a>Clothes</a>
</body>
</html>
package com.ServletConfigExample;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ShowLaptop extends GenericServlet {

@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletConfig config=getServletConfig();
String lap1img=config.getInitParameter("lap1img");
String lap1text=config.getInitParameter("lap1text");

String lap2img=config.getInitParameter("lap2img");
String lap2text=config.getInitParameter("lap2text");

String lap3img=config.getInitParameter("lap3img");
String lap3text=config.getInitParameter("lap3text");

PrintWriter out = resp.getWriter();


out.println("<html><head>"
+ "<style>"
+ "#tiles{"
+ "border:1px solid black;"
+ "background-color:yellow;"
+ "width:28%;"
+ "margin-left:2%;"
+ "}"
+ "img{"
+ "border: 1px solid black;"
+ "}"
+ ".side{"
+ "display: inline-block;"
+ "}"
+ "</style>"
+ "</head>"
+ "<body>"
+ "<div id='tiles' class='side'>"
+ "<div>"
+ "<img src='"+lap1img+"'>"
+ "</div>"
+ "<div>"
+ "<h4>"+lap1text+"</h4>"
+ "</div>"
+ "</div>"
+ "<div id='tiles' class='side'>"
+ "<div >"
+ "<img src='"+lap2img+"'>"
+ "</div>"
+ "<div>"
+ "<h4>"+lap2text+" </h4>"
+ "</div>"
+ "</div>"
+ "<div id='tiles' class='side'>"
+ "<div>"
+ "<img src='"+lap3img+"'>"
+ "</div>"
+ "<div>"
+ "<h4>"+lap3text+"</h4>"
+ "</div>"
+ "</div>"
+ "</body>"
+ "</html>"
);

}
Run the server:
Overview of the Project Video: 31

ServletApi: 1. Javax.servlet package 2. Javax.servlet.http package Servlet(interface)

Javax.servlet.http package:

interfaces:
1. HttpServletRequest
2. HttpServletResponse implements
3. HttpSession
4. HttpServletContext GenericServlet (abstract class)
5.etc
service(): one Overridden
method of Servlet interface
Classes:
HttpServlet
Cookie

HttpServlet:
extends
 It is an abstract class present in javax.servlet.http
 It extends GenericServlet
HttpServlet (abstract class)
 It is the bound with the HTTP protocol and provide many feature like cookies,
session There is no abstract method
Types of Http request:
Server
1. GET --> This request is made when we need some information like
Form/info view etc. To process GET type of request we use doGet()
GET type of request not suitable for large data or sensitive data
We can send small and non-sensitive data
 Every anchor tag(i.e. <a></a>) create GET request
 <form action=”pform”></form>: this form tag have default Default GET tag http or
https
But we can change into POST request also request
2. POST <form action=”pform” method=”post”></form>: Client
This request have POST request
 This type of request is made when we are sending the
Data to server
To process POST request we use doPost()
It is used for sending the large data and sensitive data

3. HEAD  It is like GET type of request , but it only used to send Header information,
 HEAD request can be processed by doHead()
4. PUT  It is used for uploading some updates in the resource
 To process PUT type of request we use doPut()
5. DELETE  we make this request when we want to delete any resource
 We process this request in doDelete()
6. TRACE  This request is used for testing the resource
We process this request in doTrace()
7. CONNECT
8. OPTIONS
9. PATCH

Project: Webapp3

home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome</title>
<style type="text/css">
img { This tag always makes a GET request
width: 400px;
height: 400px;
}
.side {
display: inline-block;
}
</style>
<title>Insert title here</title>
</head>
<body>
<div class="side">
<h1>Welcome to Technical Company</h1>
</div>
<div class="side">
<a href="showform">Career</a>
</div>
<div>
<img src="pexels-pixabay-269077.jpg">
</div>

</body>
</html>
This is GET request

package com.technical;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ShowForm extends GenericServlet {

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException
{
// TODO Auto-generated method stub
PrintWriter out =arg1.getWriter();
out.println("<html>\r\n"
+ " <head>\r\n"
+ " <style>\r\n"
+ "\r\n" //do by your self This tag is by default GET request
+ " </style>\r\n" but you can change into POST
+ " </head>\r\n" request.
+ " <body>\r\n"
+ " <div>\r\n"
+ " <form action='pform'>\r\n"
+ " <div>\r\n"
+ " Name:<input type=\"text\" name=\"us\">\r\n"
+ " </div>\r\n"
+ " <div>\r\n"
+ " Email:<input type=\"text\" name=\"em\"\r\n"
+ " </div>\r\n"
+ " <div>\r\n"
+ " <input type=\"submit\" value=\"register\"\r\n"
+ " </div>\r\n"
+ " </form>\r\n"
+ " </div>\r\n"
+ " </body>\r\n"
+ "\r\n"
+ "</html>");
This is GET request because of all sensitive data are visible
here and this is not recommended Data leak can be chances

package com.technical;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ShowForm extends GenericServlet {

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out =arg1.getWriter();
out.println("<html>\r\n"
+ " <head>\r\n"
+ " <style>\r\n"
+ "\r\n" //do by your self This is a POST request
+ " </style>\r\n"
+ " </head>\r\n"
+ " <body>\r\n"
+ " <div>\r\n"
+ " <form action='pform' method=’post’>\r\n"
+ " <div>\r\n"
+ " Name:<input type=\"text\" name=\"us\">\r\n"
+ " </div>\r\n"
+ " <div>\r\n"
+ " Email:<input type=\"text\" name=\"em\"\r\n"
+ " </div>\r\n"
+ " <div>\r\n"
+ " <input type=\"submit\" value=\"register\"\r\n"
+ " </div>\r\n"
+ " </form>\r\n"
+ " </div>\r\n"
+ " </body>\r\n"
+ "\r\n"
+ "</html>");

}
This is a POST request because Data is not
visible in request

New Project:

Create Project: HttpExample

Create web.xml

Create index.html

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>HttpExample</display-name>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>one</servlet-name>
<servlet-class>com.example.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>one</servlet-name>
<url-pattern>/submit</url-pattern>
</servlet-mapping>
</web-app>
index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1> Hi welcome Sir </h1>

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


Name:<input type="text" name="na"><br> This will execute doPost method
<br> <input type="submit">
</form>

<a href="submit"> Show Register form</a> This will execute doGet method
</body>
</html>

package com.example;

import java.io.IOException;
import java.io.PrintWriter;

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

public class Test extends HttpServlet {


PrintWriter out;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);

out = resp.getWriter();
out.println("<html><body><h1>This will show a form this is in doGet<h1></body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doPost(req, resp);

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

out=resp.getWriter();
out.println("<html><body><h1>"+name+" is executed in doPost<h1></body></html>");
}

}
Run the Server:

Submit: will execute


the overridden
Show: Register form will doPost method
execute the overridden
doGet method
Overview of the Project (HttpExample)

Video: 32

GET request POST request

 This type of request made when we need resource  This type of request is made when we are sending
(data/information/form/file) from the server resource to server
 This is not suitable for sending Large data  It take large amount of data
 This type of request not suitable for sending sensitive  Data will not be visible in URL section, so we can send
information as data is visible in URL section sensitive information

Http request:
Http request:
head: url
head: url+data
ip etc ip etc

Body: data
Body:

Note :::::> URL: having only limitation of 2048 character


Do an Update On: HttpExample project or Create New Dynamic Web Project

Create web.xml

Create index.xml

Create class: Test.java

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>HttpExample</display-name>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>one</servlet-name>
<servlet-class>com.example.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>one</servlet-name>
<url-pattern>/submit</url-pattern>
</servlet-mapping>
</web-app>

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hi welcome Sir</h1>

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


Name:<input type="text" name="na"><br>
<br> <input type="submit">
</form>

<a href="submit"> Show Register form</a>

</body>
</html>
package com.example;

import java.io.IOException;
import java.io.PrintWriter;

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

public class Test extends HttpServlet {


PrintWriter out;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);

out = resp.getWriter();
out.println("<html><body>This will show a form:<br><br>"
+ "<form>"
+ "Name:<input type ='text' name='na'> <br><br>"
+ "Mobile:<input type ='text' name='mob'><br><br>"
+ "<input type='submit'>"
+ "</form>"
+ "</body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doPost(req, resp);

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

out=resp.getWriter();
out.println("<html><body><h1>"+name+"<h1></body></html>");
}

}
Run the Server:
This output will come by clicking “submit”

This will execute because of POST request so


it will execute doPost request

This output will come by pressing: Show Register form

This will executed because GET request that why doGet


method will execute in Test.java
32_A.java_02.08.21_REC video Time: 27:30 about disadvantage of Context Object

SecondServlet FirstServlet
Client

Client

Context Object

OTP: 2567
Change OTP: 5784

Why context Object is not preferable for above situation because 1 st Client will make a request and it will give the otp number and at
same time 2nd Client will also make request and it will get the OTP number but for 1 st Client that OTP number will change because of
only one Context Object present for both client for that reson we should use Session Object for the above situation.

Session:  It is the time between client accessing the Webpage (web application) to the browser closing.

 Session is an object created for every user when they access the webapplication and session will deleted when browser will
close

HttpSession: It is an interface present in javax.servlet.http package

It is used to manipulate the session

We can get the object of session by getSession()


FirstServlet SecondServlet
getSession(): it is a method of HttpServletRequest Session
object

Client

Client
Session
Object
Create New Dynamic Web Project: sessionExample

Create: web.xml

Create: NewFile.html

Create Classes: FirstServlet.java, SecondFirst.java


web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>sessionExample</display-name>
<welcome-file-list>
<welcome-file>NewFile.html</welcome-file>
</welcome-file-list>
</web-app>

NewFile.htm

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="data" method="post">
Name:<input type="text" name="na"><br>
<br> Mobile:<input type="text" name="mob"><br>
<br> <input type="submit">
</form>
</body>
</html>
FirstServlet.java

package com.sessionExample;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

//import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(value="/data")
public class FirstServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
// TODO Auto-generated method stub
//super.doPost(req, resp);
String name=req.getParameter("na");
String mobile = req.getParameter("mob");

//ServletContext context = getServletContext(); // Creating Context object is not recommended


HttpSession session = req.getSession();

Random d = new Random();


String cap= ""+d.nextInt(9)+d.nextInt(9)+d.nextInt(9)+d.nextInt(9);
//context.setAttribute("originalCap", cap);
session.setAttribute("originalCap", cap);

PrintWriter out=resp.getWriter();
out.println("<html><body>"
+ "Please Enter following captcha: "+cap
+"<form action='captcha' method='post'>"
+"<input type='text' name='cap'>"
+ "<input type='submit'>"
+ "</form>"
+ "</body></html>");
}
}
SecondFirst.java

package com.sessionExample;

import java.io.IOException;
import java.io.PrintWriter;

//import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
This annotation will reduce line of
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; code in web.xml

@WebServlet(value="/captcha")
public class SecondServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
// TODO Auto-generated method stub
//super.doPost(req, resp);

//ServletContext context = getServletContext(); // Creating Context object is not recommended


because different client will get same context object that will create different Captcha code
HttpSession session = req.getSession();

//String originalCap=(String)context.getAttribute("originalCap");
String originalCap = (String) session.getAttribute("originalCap");
String userCap =req.getParameter("cap");

PrintWriter out = resp.getWriter();

if(userCap.equals(originalCap)) {
out.println("<html><body><h1> Captcha Correct</h1></body></html>");
}
else {
req.getRequestDispatcher("data").include(req,resp);
out.println("<html><body><h3> Captcha Wrong re-enter</h3></body></html>");
}

Overview of the Project


Run the server:

This page is opened by 1st client


in Google Chrome by
Httpsession
This page is opend by Edge browser:
means 2nd client for checking HttpSession
is working or not.

Edge Browser: 2nd Client


1st Client in GoogleChrome
2nd Client in Edge Browser

This means that two session object is created for 1st Client and 2nd
Client

This page will be seen for both Clients: if you enter Wrong
Captcha

Video: 32-2nd

setAttribute():
 It is a method of HttpSession, ServletContext and ServletRequest
 It is used to push a key and value pair to session Object
 Key is of String type and value is of Object type
 Method Signature: public void setAttribute(String key, Object value)
getAttribute():
 It is a method of HttpSession, ServletContext and ServletRequest
 It is used to read the value from key
 Method Signature: public Object getAttribute(String key)
What is a drawback of session object?
Ans. If there is lot of client is there then for every client having one session object. That session Object contains data for particular
Client and some data will be pushed to that session object that will create load to the server because of each client have each
session object so it will load the server
Or
For every client there is a session object created and it contains session scope data. Session object is stored in the server which may
Load the server so usally goes for Cookies.

Cookies:

Web server

Application1 Application2
Client
Request

Response

Attach
Pushing data
Cookie

Client browser only Cookie will store

Cookies:
 It is used to store the information at client side
 It is a class present in javax.servlet.http package
 We can create a cookie by creating object of Cookie class: Cookie c1 = new Cookie (key, value);
 We can add the Cookie to response by: resp.addCookie (CookieObject);

We can read the Cookies by using getCookie():


 public Cookie[] getCookies();
We can extract the value by getValue():
 getValue(): It is a method of Cookie class
This Kind of Error Explained in video: 32_A.java_03.08.21_REC and 33_A.java_04.08.21_REC

FirstServletCookies SecondServletCookies

Captcha+Cookie

Client
Cookie:
Attached Captcha Verfication:
Please enter the following
Yes
captcha:

NO

Name:

Mobile:
NewFile.html
web.xml
Create: Dynamic Web Project-- CookiesExamples

Create: web.xml

Create: NewFile.html

Create: FirstServletCookies.java and SecondServletCookies.java

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>CookiesExamples</display-name>
<welcome-file-list>
<welcome-file>NewFile.html</welcome-file>
</welcome-file-list>
</web-app>

NewFile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="formdata" method="post">
Name:<input type="text" name="na"><br> <br>
Mobile:<input type="text" name="mob"><br> <br>
<input type="submit">
</form>
</body>
</html>

Overview of the Project: CookiesExamples


FirstServletCookies.java
package com.cookiesexamole;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/formdata")
public class FirstServletCookies extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// super.doPost(req, resp);
String name = req.getParameter("na");
String mobile = req.getParameter("mob");

String r = (String) req.getAttribute("result");

Random d = new Random();


String cap = "" + d.nextInt(9) + d.nextInt(9) + d.nextInt(9) + d.nextInt(9);

Cookie c1 = new Cookie("originalcap", cap); // Creating Cookie Object


resp.addCookie(c1); // this cookie will attach to response Object

PrintWriter out = resp.getWriter();


out.println("<html><body>");

if (r != null && r.equals("failed")) { // or if(r!=null){


out.println("<h3> Wrong Captcha </h3>"); // out.println("<h3> Wrong Captcha </h3>");
} //}
out.println("Please Enter following captcha: " + cap
+ "<form action='captchaverfiy' method='post'>"
+ "<input type='text' name='cap'>"
+ "<input type='submit'>"
+ "</form>"
+ "</body></html>");
}
}
SecondServletCookies.java
package com.cookiesexamole;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/captchaverfiy")
public class SecondServletCookies extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// super.doPost(req, resp);

Cookie arr[] = req.getCookies(); // 1 object of cookies

String originalCap = arr[0].getValue();

String userCap = req.getParameter("cap");

PrintWriter out = resp.getWriter();

if (userCap.equals(originalCap)) {
out.println("<html><body><h1> Captcha Correct</h1></body></html>");
} else {
req.setAttribute("result","failed");
req.getRequestDispatcher("formdata").forward(req, resp);
/* include(req, resp) method is not working properly (in video:33_A.java_04.08.21_REC)*/
}
}
}
What is Session Management? Ans. It is combination of HttpSession and Cookies

HttpSession: session object stores in server if lot of client using then it will load the Server

Cookies: Cookies Object stores in client browser so if client disable the Cookies in his Browser then web page will not work properly
previous Project (CookiesExample) you can do that.

In GoogleChrome : Privacy and Security : Cookies you change it


JSP (Java Server Page)
ServletAPI (i.e servlet jar file)
JSP (Java Server Page): package:
 Javax.servlet
 It is a improved version of servlet  Javax.servlet.http
 It is a combination of java program and html program (in one page )  Javax.servlet.jsp
 It is present in package : javax.servlet.jsp and javax.servlet.jsp.tagext  Javax.servlet.jsp.tagext
JSP life Cycle:

 translation
 compilation
 Instantiation Java Separate .class
 Initialization
 Service
 Destroy html separate html

How to write a java code in .jsp file?

Ans. By using tags we write java codes:


1. scriptlet tag (<% java code %>)
2. expression tag(<%= java code %>
3. declaration tag(<%! field or method declaration %> )

There are 9 implicit(predefined) objects are there How to create .jsp file in Dynamic Web Project?
in .jsp file:
Ans. Select webapp------right click-----New------select------JSP File----
Object Types FileName: FirstJsp.jsp--------Finish

1. request---------------HttpServletRequest
2. response-------------HttpServletResponse
3. out-------------------JspWriter
4. config----------------ServletConfig
5. application----------ServletContext
6. session--------------HttpSession
7. pageContext-------PageContext
8. page-----------------Object
9. exception-----------Throwable
Create: Dynamic Web Project---FirstJsp
Create: web.xml
Create: NewFile.html
Create: FirstJsp.jsp (How to create:--select-------webapp----New----select: JSP File----FileName: FirstJsp.jsp-----Finish)

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>FirstJsp</display-name>
<welcome-file-list>
<welcome-file>NewFile.html</welcome-file>
</welcome-file-list>
</web-app>

NewFile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FirstJsp.jsp">
Name:<input type="text" name="na"><br>
<br> <input type="submit">
</form>
</body>
</html>

FirstJsp.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% scriptlet tag
String name = request.getParameter("na");
out.println(name);
%>
<% for(int i=1;i<=5;i++) {%>
<h1>hi from jsp page <%=name %></h1>
<p> This is repeated---</p>
<%} %>
expression tag
</body>
</html>

Run the Server:


JSP tags: Video: 34

There are 3 types of tags in which we can write java coding:

1. Scriptlet tag
2. Expression tag
3. Decleration tag

Scriptlet Tag: It is written as <% %>

 Scriptlet tag content are written into the service method

Expression Tag: it is written as <%= %>

 It is used to print java content to the HTML page

Decleration tag: it is written as <%! >

 It is used for declaring any methods and static and non-static variable
 Content of Declaration tag are written outside of every method.

FirstJsp.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("na"); Scriptlet Tag
out.println(name);
%>
<% for(int i=1;i<=5;i++) {%> Expression Tag
<h1>hi from jsp page <%=name %></h1>
<p> This is repeated---</p>
<%} %>

<%!

public void m1(){


It creates anonymous class or Virtual
System.out.println("hi"); Declaration Tag
} class:

Jspservice method
%>
</body> Jspservice () {
</html>
<% java code %>
}
FirstJsp.jsp
Jsp init method
Java code
Jsp destroy ()
Html Outside method inside the virtual class:
<%! Java code %>
Directives:
Directives are written as: <%@ %>
It is used for giving or adding more information to JSP
There are 3 directives:
1. page directive
2. include directive
3. taglib directive

page directive: It is written as: <%@page >


It is used for giving information to current jsp page
Attribute of page directive::
language: this attribute tells about the language which is used and which is translated late
value of this attribute is always java (language=”java”)

contentType: This attribute decide what type of response need to be given


contentType=”text/html” but you can change to other type but by default is “text/html”

pageEncoding: this says about the character set include in current page

import: it is used to import library files

errorPage: this defines the destination page to which we need to redirect if any error occurs in the current page

isErrorPage: this is used to indicate the current page is handling the error
isErrorPage=”true”

extend: by this attribute we can extends any class


extends=”com.example.Abc”

Create Dynamic Web Project: FirstJsp


Create: web.xml
Create: NewFile.html
Create: writing.jsp, handlingpage.jsp
Create table on database on HeidiSQL: in---oejm2-----create----hello table---create column name as: name
web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>FirstJsp</display-name>
<welcome-file-list>
<welcome-file>NewFile.html</welcome-file>
</welcome-file-list>
</web-app>

NewFile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="writing.jsp">
Name:<input type="text" name="na"><br>
<br> <input type="submit">
</form>
</body>
</html>

writing.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" import="java.sql.*"%>
<%@ page errorPage="handlingpage.jsp"%>
For Exception handling we use
<!DOCTYPE html>
<html> errorPage=”handlingpage.jsp”
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("na");
Connection cn = null;
PreparedStatement pst = null;

Class.forName("com.mysql.cj.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root");
pst = cn.prepareStatement("insert into oejm2.hello values(?)");
pst.setString(1, name);

pst.executeUpdate();
%>
<h3>Data Written into database</h3>
</body>
</html>
handlingpage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" isErrorPage="true" %>
<!DOCTYPE html> This indicate the page is
<html> handling error
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>oops something went wrong please visit later <%= exception %></h1>
</body> This will give detail about
</html> Exception occurred.

Run the Server:


Overview of the Project (FirstJsp)
Include Directive: It is used to include any jsp or html page to the current page
It is written as: <%@ include file=”” %>

Taglib directive: It is used for including 3rd party jsp tags(spring)


It is written as: <%@taglib prefix=”hi” url=”” %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" import="java.sql.*"%>
<%@ page errorPage="handlingpage.jsp"%>
<%@taglib prefix="hi" url="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head> Taglib directive
<body>

<hi:form> Here all taglib directives(3rd party) is


added(first we have to add all jar file to lib
</form>
folder)
<%
String name = request.getParameter("na");
Connection cn = null;
PreparedStatement pst = null;

Class.forName("com.mysql.cj.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root");
pst = cn.prepareStatement("insert into oejm2.hello values(?)");
pst.setString(1, name);

pst.executeUpdate();
%>
<h3>Data Written into database</h3>
<%@ include file="NewFile.html" %> Include directive
</body>
</html>
Implicit Objects:
Video: 35
In jsp there are predefined words which represent the objects

1. request----------------------- HttpServletRequest
2. response----------------------HttpServletResponse
3. session------------------------HttpSession
4. exception --------------------Throwable
5. out-----------------------------PrintWriter(JspWriter)
6. config--------------------------ServletConfig
7. application--------------------ServletContext
8. page---------------------------Object
9. pageContext-----------------PageContext

Filter

Client Servlet

Filter: These are executed before the servlet and after the servlet
By filter we can do validation, encoding, decoding etc
Filter is an interface present in javax.servlet
 They are Plugable so we can add filter any time or remove then any time without affect the Servlet
 We can put n number of Filter

Filter Chain: it is an interface present in javax.servlet.package


 It is used to pass control from filter to next resource.

Create Dyanamic Web Project: Filter

FilterOne FilterSecond

Servlet
Client

This Filter order depend in


web.xml order they placed
Create: web.xml

Create: NewFile.html

Create: Example.java, FilterOne.java, FilterSecond.java

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>Filter</display-name>
<welcome-file-list>
<welcome-file>NewFile.html</welcome-file>
</welcome-file-list>

<filter>
<filter-name>validation</filter-name>
<filter-class>com.filter.FilterOne</filter-class>
</filter> This order only Filter will executs i.e
<filter-mapping>
<filter-name>validation</filter-name> Filterone then it goes FilterSecond
<url-pattern>/abc</url-pattern>
</filter-mapping>
<filter>
<filter-name>secvalidation</filter-name>
<filter-class>com.filter.FilterSecond</filter-class>
</filter>
<filter-mapping>
<filter-name>secvalidation</filter-name>
<url-pattern>/abc</url-pattern>
</filter-mapping>
</web-app>

NewFile.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="abc" method="post">
Enter Name(5-10 character):<input type="text" name="na"><br>
<br> Enter Mobile Number:<input type="text" name="mobile"><br>
<br>
<input type="submit">
</form>
</body>
</html>
FilterOne.java

package com.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FilterOne implements Filter {

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain ch)
throws IOException, ServletException {
// TODO Auto-generated method stub
String mobile=req.getParameter("mobile");
PrintWriter out = resp.getWriter();
if(mobile.length()==10) {
ch.doFilter(req, resp);
}
else {
out.println("<html><body> This is Filterone response"
+ " Mobile number is not valid"
+ "<a href='NewFile.html'> Home</a>"
+ "</body></html>");
}

FilterSecond.java
package com.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FilterSecond implements Filter {

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain ch)
throws IOException, ServletException {
// TODO Auto-generated method stub
String na = req.getParameter("na");
PrintWriter out = resp.getWriter();
if (na.length() <= 10 && na.length() >= 5) {
ch.doFilter(req, resp);
} else {
out.println("<html><body> This is FilterSecond response......"
+ " name is not valid"
+ "<a href='NewFile.html'> Home</a>"
+ "</body></html>");
}
}
}
ExampleServlet.java

package com.filter;

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( value="/abc")
public class ExampleServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
// TODO Auto-generated method stub
//super.doPost(req, resp);
String mobile = req.getParameter("mobile");
PrintWriter out = resp.getWriter();

out.println("<html><body><h3>"+mobile+"</h3></body></html>");
}
}
Run the Server:

If Name and mobile number length is


correct then:
If mobile Number length is not correct and
Name is correct

Or

If both Name and Mobile Number is not


correct

You might also like