Adv Java Nit
Adv Java Nit
RAGHU
ADVANCED JAVA
by
Mr. RAGHU
1|Page
Adv. Java by Mr. RAGHU
Web Applications:-
It is a collection of web pages, running in web server, can be accessed by web-browser
by using request and response process.
Web Applications are 2 types
1.>Static Web Application.
2.>Dynamic Web Application.
=>Advance Java, ASP.net, PHP are used to Develop Dynamic web Application.
=>To Develop Web Applications using Advance Java concepts used are:
Servlets, JSP (Java Server Pages) and JDBC (Java DataBase Connectivity).
It can also use concept like HTML, SQL.
-----------------------------------------------------------------------------------------------------------------
=>User should operate client machine which has one software installed i.e. web
browser (ex. Firefox, Chrome, …..)
=>By using web browser user can make request, which will be passed through network.
Request will be given to provider which has one software installed ie.web server (ex:
Apache Tomcat, ApacheHttp, IIS, Glassfish, Jetty…..).
=>In web server request will be taken by Servlet and it will process it.
If Servlets needs data or wants to store data in DB, it uses JDBC.
=>JDBC makes communication link between any java Application and Database.
=>Servlet will dispatch data to JSP (Java Server Pages) for final output.
=>This is given as response back to client machine. (ex: Response: Inbox Page, Login
Page, Login Fail Page etc……)
JDBC API:-
JDBC stands for java database connectivity. It is an API (Application Programming
Interface) giver by Sun Microsystems to perform “CURD” operations with Database
using Java.
C=Create (Create Database/Tables/Rows…)
3|Page
Adv. Java by Mr. RAGHU
------------------------------------------------------------------------------------------------------------------
JDBC Architecture:-
Driver:-It is a pre-defined class (in simple java software) which creates a communication
link between JDBC & Database.
=>Without Driver no JDBC concept works.
=>For Every Database Driver Software (class) is required.
=>DriverManager is a class which takes care of Driver, like
->Is this correct driver or not?
->Is this working or not?
->Is this loaded or not?
4|Page
Adv. Java by Mr. RAGHU
2>Javax.Sql (Extended)
=>Few classes and interfaces in above packages are given as connection, Statement,
PreparedStatement, ResultSet, DatabaseMetadata, RowSet etc.
=> To work with JDBC, our output should be converted to SQL which can be
understandable by Database.
Metadata:-
=>It provides information of Data (Data about Data) consider below table for data and
metadata.
-------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
Ex:- Data is 10 its Metadata is
Type:- Number
Column – eid
Is Primary key – yes
Accept null = no
Is unique = yes
5|Page
Adv. Java by Mr. RAGHU
Database Table:-
=>Create table <tablename> (eid number, ename varchar2 (20), esal number(5,2));
6|Page
Adv. Java by Mr. RAGHU
desc <tablename>;
=>alter table <tablename> dropcolumn columnname;
=>alter table <tablename> addcolumn datatype;
=>alter table <tablename> modifycolumn datatype;
Rename Table and column Names:-
=>alter table <tablename> rename to <newtablename>
alter table <tablename>renamecolumn <oldcolumnname>to newcolumnname.
DML queries:-
=>insert into <tablename> values (?, ?, ?);
=>update <tablename>set columnname= value (?)
=>truncate table <tablename>;
=>dalete from <tablename> where eid=1;
Edit Buffer:-
ed/edit with /.
JDBC Testing Setup Application:-Write one java application after installing software’s,
like JDK, Eclipse, Oracle/MySQL Databases.
Step 1:-Load Driver class using below statement
Class.forName(driverClass);
Step 2:-Creating connection between Java Application and Database using below
statement.
7|Page
Adv. Java by Mr. RAGHU
Connection con=DriverManager.getConnection(url,username,password);
Folder System:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
8|Page
Adv. Java by Mr. RAGHU
Folder System:-
9|Page
Adv. Java by Mr. RAGHU
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
//jdbc code
//load DriverClass
Class.forName(driverclass);
//2.create Statement connection
Connectioncon=DriverManager.getConnection(url,username,password;
//3.create Statement
Statement st=con.createStatement();
//4.Execute Statement
//5.Get Result
int count=st.executeUpdate(sql);
//6.Print result
System.out.println("Inserted:"+count);
//7.close connection
con.close();
}
}
10 | P a g e
Adv. Java by Mr. RAGHU
Output:--
Before Running this Goto Oracle command line and create below Queries.
#1.open SQL cmd prompt
Window=>oracleDatabase=>Run SQl commandline
#2.login to Oracle
=>conn system/manager
#3.create table for student
=>create table student (sid number, sname varchar2(20), sfee number(5,2));
#4.Type select Query to check result
=>select * from student;
NOTE:-If table is not created or created and deleted (now not available) then if we run
above application.
Output is : Exception
Java.sql.SQL Exception : Table () or view does not exist.
#1.open Eclipse/STS software and change to java mode
Windows=>Perspective=>Open Perspective=>other=>choose java option
#2.create new Java Project
#3.Add ojdbc jar for Oracle DB support
Right click on project=>Build path=>configure build path=>Library path=>click on Add
External Jars=>choose Ojdbc jar
#4.Creta a class under src folder
Right click on src folder=>new =>class=>Enter Details
Package : com.app
Name : JdbcUpdateTest=>Finish
Folder System:-
11 | P a g e
Adv. Java by Mr. RAGHU
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
//jdbc code
Class.forName(driverclass);
Connection con=DriverManager.getConnection(url, username, password);
Statement st=con.createStatement();
int count=st.executeUpdate(sql);
System.out.println("Updated:"+count);
con.close();
}
}
12 | P a g e
Adv. Java by Mr. RAGHU
Output:--
Exceptions in JDBC:-
13 | P a g e
Adv. Java by Mr. RAGHU
Folder System:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
}
Output:-
15 | P a g e
Adv. Java by Mr. RAGHU
eid 3
g>ResultSet creates default pointer with position to zero(0th) row also called as before
to FirstRow.
(###@)To change pointer position use rs.next();
Folder System:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JdbcSelectTest
{
public static void main(String[] args) throws Exception
{
//jdbc properties
String driverclass="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:xe";
String username="system";
String password="manager";
String sql="select * from employee1";
//jdbc code
Class.forName(driverclass);
16 | P a g e
Adv. Java by Mr. RAGHU
-------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
DATABASE SETUP:-
1)Open SQL CommandLine and connect
=>conn system/manager
2)Create emptab
=>create table emptab(eid number,ename varchar(25),esal number(10,3));
17 | P a g e
Adv. Java by Mr. RAGHU
3)Insert data
insert into emptab values(1,’ab’,2.5);
insert into emptab values(2,’abc’,3.5);
insert into emptab values(3,’abcd’,4.5);
4)Finally save data
commit(press Enter)
DRIVERS IN JDBC:-
A driver is a class which implements an interface”java.sql.Driver” given by sun
micro systems(Oracle corp.) which is part of JDK.
Ex: class MyLink implements java.sql.Driver {
…………..
}
=>Here MyLink can be called as Driver class(or) Driver software(or)Driver
=>Driver class is handled by DriverManager which is part of JDBC API.With out no JDBC
program works.
Generic Architecture of JDBC Driver:-
-------------------------------------------------------------------------------------------------------------------
18 | P a g e
Adv. Java by Mr. RAGHU
-------------------------------------------------------------------------------------------------------------------
=>ODBC stands for “Object Data Base Connectivity”. This is software used by platforms
(Operating system=OS) for Database connections.
=>This is very old process to link with database
For this sun Micro system has given class named as JdbcOdbcdriver(sun.jdbc.odbc
package).
=>It will convert JDBC calls to ODBC calls and communicate with DB.
JDK8 onwards it is not supported.
Advantages:-
i>It supports almost major databases.
Disadvantages:-
i>In OS, we should install ODBC drivers (Client machine-OS).
ii>It is machine (OS) Dependent.
iii>It works very slow compared with other types.
iv>JDK 8 onwards it is not supported.
Coding Steps:-
#1. Download JDK7 or lesser version and install
#2. Create DSN (DataSourceName)
DSN means a name given to Database,to identify DB by ODBC(by os)
Mycomputer➔c:driver➔eindows folder➔system32
Ex:- c:\windows\system32 (or) c:\windows\system64
Click on option “odbcad32.exe”
Click on system DSN➔click Add
Choose oracle11G or oracleXE(one)
Next➔provide details like
DataSource Name : oraclemydsn
Description : none(optional)
TNS ServiceName : ORCL/XE
19 | P a g e
Adv. Java by Mr. RAGHU
userId : system(username)
click on ok
driver class name is : sun.jdbc.odbc.JdbcOdbcDriver
url is >jdbc:odbc : <dsnName>
Folder System:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
20 | P a g e
Adv. Java by Mr. RAGHU
Type-2 Driver NATIVE API DRIVER:-Native is a keyword in java. It is used to link java
language with c-language (non-java) code.
Native can be provided to method also called as “native methods”.
A method which declared in java (non-java) is known as native method.
Example to native method is hashcode() from java.lang.object class.
=>This is type-2 Driver in java which uses both java and c-language concept (native
keyword).
=>Oracle has provided this type-2 driver implementation name as “OCI” (oracle Call
Interface (or) Open Call Interface).
=>OCI is process of connecting DB using C-Language(Memory Operation using Pointers)
This OCI is also called as OCI8 I Oracle 10g/11g version(here 8 means OCI version
number).
CODING STEPS:-
Oracle10G➔ojdbc14.jar
Location of Jar: C:\oracleexe\app\oracle\product\10.2.dserver\jdbc\lib
Oracle11G➔ojdbc6.jar
Location of jar: D:\app\nareshit\product\11.2.0\dbhome-1\jdbc\lib
URL Syntax:
Jdbc:oracle:oci:@<SID> (or)
21 | P a g e
Adv. Java by Mr. RAGHU
Jdbc:oracle:oci8:@<SID>
SID=Service Identifier of Database
SQL Query to find SID name in DB
Select * from global_name; oracle11g➔ORCL
Folder System:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
22 | P a g e
Adv. Java by Mr. RAGHU
Advantages:-
=>It is faster than Type-1 driver
Disadvantages:-
=>DB vendor(database people) has to implement this using native library and install in
client machine.
=>It is not available for all DBs(Given mainly for oracle DB).
=>It will not support Applets.
-------------------------------------------------------------------------------------------------------------------
=>IDS server is an open source server given by Ids solution to handle Type-3 driver in
JDBC.
IDS stands for➔Internet Database access Server
23 | P a g e
Adv. Java by Mr. RAGHU
LINK : http://www.idssoftware.com/download.html
=>Download & install.
=>It supports only oracle XE 10G not 11G DB, using only Type-1
Checking IDS server status:-
➔Windows key + R➔Enter ”services.msc”
➔Search for IDS server➔right click and run/start
Open below location to find Jar
C:\IDSServer\classes
JAR name is: jdk13drv.jar(add this to build path in Eclipse)
Driver class: ids.sql.IDSDriver
URL:jdbc:ids://<IPADDRESS>:12:/conn?dsn=<DSN>
=>To create DSN follow Type-1 driver steps
(IDS support Type-1 Driver)
Folder System:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
24 | P a g e
Adv. Java by Mr. RAGHU
System.out.println("done");
}}
Output:-
Advantages:-
=>One driver used to connect with any Database.
=>No database related libraries required [(ojdbc.6)/ojdbc.7/14]
Disadvantages:-
=>It is very slow compared with all other drivers. We must install extra works as
middleware server (IDS Server)
=>It needs network support.
=>Middleware server should have implemented Type-1/2/4 driver already
25 | P a g e
Adv. Java by Mr. RAGHU
(observe………(PORT=1521)
3)finding IP Address
➔open cmd prompt➔ipconfig(or)use localhost
IPV4 Address…….:192.168.3.112
url = jdbc:oracle:thin:@localhost:1521:xe;
Folder System:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
public class JdbcType4Ex {
public static void main(String[] args) throws Exception {
//jdbc properties-oracle DB
String driverclass="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:xe";
String username="system";
String password="manager";
//jdbc code
Class.forName(driverclass);
Connection con = DriverManager.getConnection(url,username,password);
System.out.println("done");
}}
Output:-
26 | P a g e
Adv. Java by Mr. RAGHU
Advantages:-
It is pure java driver, no other dependencies
It is fastest driver compared with all.
Supports for almost all high level databases
Disadvantages:-
For every database need Jar to get connect with DB.
Db to DB Driver class changes
Username=root;
Password=root;
Folder Structure:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
28 | P a g e
Adv. Java by Mr. RAGHU
MYSQL Commands:-
1)see all databases
2)connect to one DB
mysql>use test;
3)see all tables
mysql>showtables;
4)create table
mysql>create table student(sid int, sname varchar(25), sfee(double);
5)insert row
mysql>insert into student(1,’a’, 3.3);
6)save data
mysql>commit
Few other ways (write such code that will call static block)
Ex1: new OracleDriver();
Ex2: Driver d=new OracleDriver();
Ex3: Sysout(OracleDriver.BUILD-DATE);
➔In new JDBC API(4.x)It supports auto-loading of driver class i.e. without even step#1
in JDBC program works.
Ex : use jar ojdbc6.jar for oracle.
29 | P a g e
Adv. Java by Mr. RAGHU
JdbcProperties:-
Driverclass = org.postgresql.Driver
URL= jdbc:postgresql://<IP ADDRESS>:<PORT>/<DB>
Username= postgres password = admin
Step#>1 Go to postgreSQL
Start/windows button➔AllPrograms
postgreSQL➔click on PSQL
Step#2>create database and switch to it
➔Create database nareshit
➔\c nareshit
Step#3>create table
Create table student (sid int, sname char(30),sfee (float));
Step#4>insert one row
Insert into student values (1,’a’, 3.3);
Folder Structure:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
30 | P a g e
Adv. Java by Mr. RAGHU
Class.forName(driver);
Connection con = DriverManager.getConnection(url,username,password);
System.out.println("done");
}
}
Output:-
Ex (Valid Example):-
a>Insert into student values (?, ?, ?)
31 | P a g e
Adv. Java by Mr. RAGHU
Invalid ex:-
a>insert into ? values (1, ‘a’, 3.9)
b>update ? set ? = 10, ?=3.3 where ? = 55;
c>delete from ? where sid = 55;
d>select ?, ?, ? from ? where sid =55;
=>Every question mark symbol written in SQL query will be identified using one Number
(position Number) start from one (1),(1,2,3…..)
Ex:-
a>insert into student values(?, ?, ?);
b>update student set sname =?, sfee = ? where sid !=?
c>select sid from student where sid > ? or sfee < > ?
=>< > means it is not equals to (:=) in DB.
Syntax:-
=>Overview of prepared statement code.
1>Load drivers
2>Create connection (con)
String sql = “……..?, ?, ?”;
PreparedStatement ptmt con.prepareStatement(sql);
//Call set method to provide data
psmt.set<DataType> (int index, <DataType> value);
//execute update query..
//get and print result
//close connection
Insert Operation:-
Step#1:- Create student (sid, sname, sfee) table in DataBase.
Step#2:-Write below class in Eclipse
32 | P a g e
Adv. Java by Mr. RAGHU
Folder structure:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
33 | P a g e
Adv. Java by Mr. RAGHU
}
Output:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
35 | P a g e
Adv. Java by Mr. RAGHU
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
36 | P a g e
Adv. Java by Mr. RAGHU
int option=sc.nextInt();
switch (option) {
case 1:
sql+="where sid=?";
System.out.println("enter student Id:");
int stdId=sc.nextInt();
pstmt=con.prepareStatement(sql);
pstmt.setInt(1, stdId);
break;
case 2:
sql+="where sname=?";
System.out.println("Enter student Name:");
String stdName=sc.next();
pstmt=con.prepareStatement(sql);
pstmt.setString(1, stdName);
break;
case 3:
sql+="where sfee=?";
System.out.println("Enter student fee:");
Double stdFee=sc.nextDouble();
pstmt=con.prepareStatement(sql);
pstmt.setDouble(1, stdFee);
break;
default:
pstmt=con.prepareStatement(sql);
System.out.println("you choosen all row delete:");
break;
}
int count=pstmt.executeUpdate();
if(count==0)
System.out.println("sorry!!Details not Found");
else
37 | P a g e
Adv. Java by Mr. RAGHU
System.out.println("Data removed");
con.close();
}
}
Output:-
-------------------------------------------------------------------------------------------------------------------
Step#1 create a database table shown as below
38 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:-
Code:-
package com.app;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class StoreImage {
public static void main(String[] args) throws Exception {
//jdbc properties
String driverclass="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:xe";
String username="system";
String password="manager";
String sql="insert into imagetab values (?,?,?)";
//jdbc code
39 | P a g e
Adv. Java by Mr. RAGHU
Class.forName(driverclass);
Connection con = DriverManager.getConnection(url,username,password);
//1.load image into file object(RAM)
File f=new File("F:\\VENKY\\1.jpg");
//2.read data from file object
FileInputStream fis=new FileInputStream(f);
//3.create pstmt object
PreparedStatement pstmt=con.prepareStatement(sql);
//4.set basic data
pstmt.setInt(1,100);
pstmt.setString(2, "aa.jpg");
//5.set image data into BLOB
pstmt.setBinaryStream(3, fis,(int)f.length());
//6.execute pstmt
int count=pstmt.executeUpdate();
//7.print result
System.out.println("Inserted:"+count);
con.close();
}}
Output:-
40 | P a g e
Adv. Java by Mr. RAGHU
COMMON THINGS:-
=>Both are Interfaces.
=>Both are from java.sql package.
=>Both are used to represent SQL queries.
=>PreparedStatement extends Statement.
Folder Structure:-
Code:-
package com.app;
import java.io.FileOutputStream;
41 | P a g e
Adv. Java by Mr. RAGHU
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
con.close();
}}
Output:-
Oracle Function:-
Functions are used to execute set of SQL queries at a time in an order to do a final work.
➔Every function contains
Function name
Inputs to function
One output
Return type
Function body
SYNTAX:-
Create or replace function<name>(inputs)
Return<datatype>
IS/AS var datatype;
BEGIN
SQL1, SQL2…..;
return var;
END;
=>A function is used to execute a task.
JDBC CALLABLE STATEMENT - ORACLE FUNCTION CALL:-
Callable Statement:--
=> This is used to call functions or Procedures in JDBC.
(**only for call not for creating).
=>In general statement and Prepared Statements works on tables where as Callable
Statements works on functions and Procedures.
43 | P a g e
Adv. Java by Mr. RAGHU
Ans:-Function returns value (return type is applicable) but Procedure never returns
value(no return type). We can get date using OUT parameter in Procedure if required.
Code:-
package com.app;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
public class TestFunction {
public static void main(String[] args) throws Exception {
String driverClass="oracle.jdbc.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system"; String password="manager";
String sql="{?=call GETEMPNAME(?)}";
44 | P a g e
Adv. Java by Mr. RAGHU
Class.forName(driverClass);
Connection con=DriverManager.getConnection(url, user, password);
CallableStatement cstmt=con.prepareCall(sql);
cstmt.registerOutParameter(1, Types.VARCHAR);
cstmt.setInt(2, 10);
cstmt.execute();
String empName=cstmt.getString(1);
System.out.println(empName);
con.close();
}
}
ROWSET STEPS:-
STEP#1 create Rowset object using its implementation class
Ex: JdbcRowSet rs=new OracleJdbcRowSet();
Folder Structure:-
45 | P a g e
Adv. Java by Mr. RAGHU
Code:-
package com.app;
import javax.sql.rowset.JdbcRowSet;
import oracle.jdbc.rowset.OracleJDBCRowSet;
46 | P a g e
Adv. Java by Mr. RAGHU
System.out.println(rs.getInt(1)+","+rs.getString(2)+","+rs.getDouble(3));
System.out.println("MOVE ONE ROW BACK");
rs.relative(-1);
System.out.println(rs.getInt(1)+","+rs.getString(2)+","+rs.getDouble(3));
System.out.println("GO TO FIRST ROW");
rs.first();
System.out.println(rs.getInt(1)+","+rs.getString(2)+","+rs.getDouble(3));
System.out.println("GO TO LAST ROW");
rs.last();
System.out.println(rs.getInt(1)+","+rs.getString(2)+","+rs.getDouble(3));
rs.close();
}
}
Output:-
Note:-
isBeforeFirst() and isAfterLast() return true/false if cursor in that position or not.
rs.next(); is used to move cursor to next row(forward) in same way rs.presvious(); is
used to move cursor back.
rs.absolute(position); is used to go to exact row number if exist.
47 | P a g e
Adv. Java by Mr. RAGHU
CachedRowSet (I):-
CachedRowSet will execute command (SQL) and copies data into temporary memory
“catch” and remove the connection. i.e. Dis-Connected Mode, where as JdbcRowSet will
not close connection until our program ends i.e, Connected Mode.
Note:-
1) Implementation class for CachedRowSet is: OracleCachedRowset (c).
2)CachedRowSet also supports all methods like JdbcRowSet methods.
Ex: next(),previous(),absolute(),first(),last() etc.
48 | P a g e
Adv. Java by Mr. RAGHU
WebRowSet (I):-
It is a SerializedRowSet works in disconnected mode.
➔It supports all concepts supported by CachedRowSet and also this data can be sent
over network, file, and stream in global (XML) format.
Code:- WebRowSet rs=new OracleWebRowSet();
……..
rs.writexml(System.out);
➔WebRowSet converts data into global format like XML(tag based) so we can send to
another application, even developed in other language(internally used web Services
supports)
-------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
Folder Structure:-
Code:-
package com.app;
import javax.sql.rowset.WebRowSet;
import oracle.jdbc.rowset.OracleWebRowSet;
49 | P a g e
Adv. Java by Mr. RAGHU
50 | P a g e
Adv. Java by Mr. RAGHU
JoinRowSet:-
=>It can integrate multiple RowSets Data into one final RowSet based on one column
link.
RowSet#1+RowSet#2………..= JoinRowSet
=>It will support all concepts supported by WebRowSet also and joining of multiple
RowSet into one final RowSet
Simple Code:-
CachedRowSet rs1=…….
CachedRowSet rs2=…….
JoinRowSet jsr=new OracleJoinRowSet();
Jsr.addRowSet(rs1, ”columnName1”);
Jsr.addRowSet(rs2,”columnName2”);
=>This RowSet internally executes one Boolean condition which returns either true or
false after comparing with Data Base table Row.
51 | P a g e
Adv. Java by Mr. RAGHU
Evaluate(RowSet rs):- It can have conditions over any/all column(s) [any name/any
index]
Evaluate (Object value, int Column):- To have condition over Column Index based (like
condition on: 1st column or 2nd column…) use this method.
Evaluate (Object value, String columnName):- this method used to write condition based
on columnName.
Step#2:- Create FilteredRowSet object and set properties, execute
Step#3:- Link predicate object to RowSet
RowSetListener (Interface):-
Listener:-Listener is a concept which executes a task (method) automatically when it’s
related method is called. i.e., also called as“on every execution (Task#1 done) call
automatically Listener method (Task#2 should also be done)”.
=>RowSetListener is a interface given in a package: javax.sql, which has 3 methods
rowSetChanged(), rowChanged() and cursorMoved().
Here we want to transfer money from Ajay account to Vijay account then two Sql
queries required.
SQL#1 : To Deduct money from account #1 update account
set bal = bal-300 where aid = 101;
SQL#2 : To Credit money to account #2 update account
set bal = bal+300 where aid = 102;
If SQL#1 is executed and SQL#2 is not executed then consistency between data will not
be maintained. So here execute SQL#1 and SQL#2 both “commit” else “rollback” both.
Example:-
Step#1 Disable auto-commit in JDBC
By default Auto Commit is true.
Step#2 write codes in try-catch block
Step#3 At the end of try-catch block write commit() method or some where
Step#4 In catch block write rollback method
Format:
Connection con=………..
con.setAutoCommit(false);
try {
……….Statements&execute…….
con.commit();
53 | P a g e
Adv. Java by Mr. RAGHU
}
catch(SQLException se) {
con.rollback();
Sysout(“Problem:”+se);
}
con.close();
Folder Structure:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
54 | P a g e
Adv. Java by Mr. RAGHU
con.setAutoCommit(false);
Statement st=con.createStatement();
try { //2.execute code in try catch block
st.executeUpdate("insert into emptab2 values(21,'WER',12.2)");
//3.call commit()-if all are ok
con.commit();
System.out.println("inserted");
} catch ( SQLException se) {
//4.if exception-rollback()
con.rollback();
System.out.println("problem:"+se);
}
con.close();
}
}
Output:-
BatchProcessing:-
=>This concept is used to execute multiple SQLs at a time, instead of sending them one
by one. It saves only execution time by reducing network calls between Java Application
and Database.
-----------------------------------------------------------------------------------------------------------------
55 | P a g e
Adv. Java by Mr. RAGHU
-----------------------------------------------------------------------------------------------------------------
Step#1 Disable auto-commit
Step#2 create statement object
Step#3 use addBatch(SQL) to add multiple SQL queries to statement.
Step#4 call executeBatch():int[ ].Here Array indicates no.of.rows effected counts in
order.
Step#5 commit/rollback
FolderSystem:-
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
56 | P a g e
Adv. Java by Mr. RAGHU
con.setAutoCommit(false);
Statement st=con.createStatement();
try { //3.use method addBatch(SQL)
st.addBatch("insert into emptab2 values(21,'WER',12.2)");
st.addBatch("insert into emptab2 values(22,'BNML',22.2)");
st.addBatch("insert into emptab2 values(23,'AASD',32.2)");
int[] count=st.executeBatch();
System.out.println(count[0]);
System.out.println(count[1]);
System.out.println(count[2]);
//4.no exception then call commit()
con.commit();
System.out.println("inserted...");
}
catch (SQLException se)
{
con.rollback();
System.out.println("problem:"+se);
}
con.close();
}
}
Output:-
JdbcUpdateUsing ExceptionHandling:-
Folder System:--
57 | P a g e
Adv. Java by Mr. RAGHU
Code:-
package com.app;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
58 | P a g e
Adv. Java by Mr. RAGHU
EMAIL : javabyraghu@gmail.com
FB: https://www.facebook.com/groups/thejavatemple/
59 | P a g e
Adv. Java by Mr. RAGHU
SERVLETS
Web Application:-- It is a collection of web pages (Resources) used to provide service to
end user.
Ex:-- web applications:-www.bookmyshow, www.paytm.com, redbus, bigbasket, icici, net
banking, espncricinfo, youtubes, gmai, facebook, timeindia newspaper, twitter, amazon.
=>web application provides better services, saves time and faster service.
60 | P a g e
Adv. Java by Mr. RAGHU
-------------------------------------------------------------------------------------------------------------------
Web Server:-- A System (Computer) which holds web Applications hosted (web sites) and
provides to web clients (web browser).
Web client:-- A System (Computer) which is used to read/access web application is using
httpRequest (URL) and gets HttpResponse (Resource).
Web Server:-- A System installed on computer to host web sites is known as web servers.
Ex:-- Apache Tomcat, Apache Http, IIS etc..
Web Client:-- A System has web browser Software is called as Web Client.
Ex:--Mobile phone has Google chrome, hap top, desktop etc…
End User:-- A Person who operates client to make request and gets response.
=>web programmer (Web Designer):- A Person who creates static/dynamic web pages.
Web hosting:-- Placing a web application inside web server and starts service.
---------------------------------------------------------------------------------------------------------------
Servlets:-- These are used to develop Dynamic web application also supported static web
applications.
=>This is an API called as Servlet API [having classes and Interface] provided by sun Micro
system.
=>This API is provided in 2 Package
a>javax.Servlet [Package]
b>javax.Servlet.http [Package]
=>Servlet API is provided with basic Interface and Abstract classes along with relations
and package.
62 | P a g e
Adv. Java by Mr. RAGHU
---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
=>By using above API we can create one class that provide Dynamic Web page as output.
---------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
Example:--
1>using Servlet Interface:--
class MyServlet implements Servlet
{
}
2>Using Generic Servlet:--
class MyServlet extends GenericServlet
{
}
3>Using HttpServlet abstract class:--
class MyServlet extends HttpServlet
{
}
63 | P a g e
Adv. Java by Mr. RAGHU
---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
Types of Server:--
---------------------------------------------------------------------------------------------------------------
64 | P a g e
Adv. Java by Mr. RAGHU
1>Web Server:-- In java, web Servers are use to run Servlets/JSP based web
applications(web sites).
=>It supports to run both static and dynamic web application.
2>Application Server:-- In java, App servers are used to run EJBS [Enterprise Java Bean].
App servers also supports servlets/JSP based application.
3>Database Servers:-- These are used to store and read data from External services. It
supports CURD operations. An External source can be end user, Java App, .net App, or
Angular) etc…
Server Components:--
Web Server Components:--
----------------------------------------------------------------------------------------------------------------
65 | P a g e
Adv. Java by Mr. RAGHU
---------------------------------------------------------------------------------------------------------------
=>Here web Server is main program which contains web Container works as Sub rogram.
a>Web Container creates and holds Servlet class objects.
b>To create objects and call methods and to known their status containers uses
Handlers [Task Executions].
c>To work on Servlet classes “Servlet Handler” is provided and named as “Container”.
d>To work on JSP [Java Server Pages] “JSP Handler” is provided and named as Jasper.
e>These are also called as Cotelina Engine and Jasper Engine.
---------------------------------------------------------------------------------------------------------------
=>EJB are used to develop applications once and used to many times.
=>To create objects to EJBs and to holds those, EJB container is used.
---------------------------------------------------------------------------------------------------------------
Folder System for web applications:--
=>Every web application developed in java must follow folder System rules given by Sun
MicroSystem.
=>It should have two main files
a>Servlet class.
66 | P a g e
Adv. Java by Mr. RAGHU
---------------------------------------------------------------------------------------------------------------
Setup for Servlets:--
--->JDK 32/64 bit [8/9/10]
--->Tomcat 32/64 [7/8/9]
--->Eclipse Java EE (Photon] 32/64 bit
Step#1:-- Download Tomcat 7 and install it
Step#2:--Open Eclipse/STS and configure Apache Tomcat Server
-->window=>perspective=>open perspective=>other=>choose java EE=>Finish
=>Click on server tab=>right click =>new => server => choose Apache Tomcat [any
version] =>next => browse => choose Tomcat installation location.
Ex: c:/Program Files/Apache Software foundation/tomcat 9.0
=>next => finish
67 | P a g e
Adv. Java by Mr. RAGHU
Step#4:-- Copy servlet.api.jar from Tomcat installation folder to project lib folder.
Copy from: c:/Program Files/Apache software Foundation/Tomcat 9.0/lib
Paste in: Project => lib folder under [WEB-INF]
Folder Structure:--
68 | P a g e
Adv. Java by Mr. RAGHU
Code:--
Step#1:-- Create one class to generate Dynamic web page
---->right click on src folder => new => class => Enter package and name
Ex:-- package com.app
Name : MyFirstServlet
=>finish
package com.app.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
web.xml:--
69 | P a g e
Adv. Java by Mr. RAGHU
Those are:--
1>Servlet class 2>web.xml ***
1>Servlet class:-- It is a class which will be written and compiled by programmer.
=>Above example class, wrote in below steps,
a>Write one public class.
b>extends with GenericServlet abstract class.
c>provide public service() method, with ServletRequest and ServletResponse.
d>service method must throw 2 Exceptions.
Those are : ServletException, IOException
e>To display data at UI page(web page) use PrintWriter object (Do not use
System.out.println), get this object using code: response.getWriter();
f>To print data on web page code is out.println(….);
70 | P a g e
Adv. Java by Mr. RAGHU
<servlet>
<servlet-name> </servlet-name>
<servlet-class> </serrvlet-class>
</servlet>
=>meaning of above code is, web container creates object using above class and name.
Ex:--
<servlet>
<servlet-name>one</servlet-name>
<servlet-class>com.app.MyPage</serrvlet-class>
</servlet>
Example:--
71 | P a g e
Adv. Java by Mr. RAGHU
<servlet-mapping>
<servlet-name>one</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
=>Now end user should enter URL ends with /welcome.
Example:-- http://localhost:8080/FirstApp/welcome in browser
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
72 | P a g e
Adv. Java by Mr. RAGHU
---------------------------------------------------------------------------------------------------------------
Sending Data using URL request:--
a>Query Parameters:--
=>Here Parameters means input data to any method. [Here service() method]
=>Query Parameters means sending data along with Query (URL) to service() method.
Format will be
URL?Key=Value&Key=Value…
Ex:-- http://localhost:8080/App/welcome?sid=10&sname=AA&sfee=3.2
----------------------------------------------------------------------------------------------------------------
73 | P a g e
Adv. Java by Mr. RAGHU
----------------------------------------------------------------------------------------------------------------
Folder Structure:--
int id = Integer.parseInt(sid);
String sname = req.getParameter("sname");
String fee = req.getParameter("sfee");
//output data
PrintWriter out =res.getWriter();
out.println("Id is : "+id);
out.println("/");
out.println("Name is : "+sname);
out.println("Fee is : "+fee);
} }
=>Run on server Enter URL like:
http://localhost:3030/ServletFirstApp/welcome?sid=10&sname=Uday&sfee=34.78
web.xml Code:--
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>ServletFirstApp</display-name>
<servlet>
<servlet-name>two</servlet-name>
<servlet-class>com.app.MyDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>two</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
=>For checkbox, it can have multiple values. So, to read checkbox values use code:
request.getParameterValues(“key”) return String[] (String array).
=>If we print String[] un-readable output is provided, so convert to List type and print
using code:
Arrays.asList(arrayData) returns List.
=>Arrays is from java.util package and asList() is a static method.
=>On server startup to show one default page, without entering URL part, use
<welcome-file> concept. Server only calls this page.
---------------------------------------------------------------------------------------------------------------
Folder System:--
---------------------------------------------------------------------------------------------------------------
Code:-- 1>Register.html:--
=>Right click on WebContent folder => new HTML File => Enter name => Finish’
<!DOCTYPE html>
<html><head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head><body>
76 | P a g e
Adv. Java by Mr. RAGHU
2>Servlet code:--
package com.app.servlet;
public class FormReaderServlet extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)throws ServletException,
IOException
{
//read form input
77 | P a g e
Adv. Java by Mr. RAGHU
out.print("<td>EMAIL</td><td>"+email+"</td>");
out.print("</tr><tr>");
out.print("<td>COURSE</td><td>"+course+"</td>");
out.print("</tr><tr>");
out.print("<td>GENDER</td><td>"+gender+"</td>");
out.print("</tr><tr>");
out.print("<td>ADDRESS</td><td>"+addr+"</td>");
out.print("</tr><tr>");
out.print("<td>LANGS</td><td>"+languages+"</td>");
out.print("</tr></table></body></html>");
}
}
=>Run on server Enter URL like: http://localhost:3030/ServletFormEx/
78 | P a g e
Adv. Java by Mr. RAGHU
3>web.xml file:--
<?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" id="WebApp_ID" version="3.1">
<display-name>ServletFormEx</display-name>
<servlet>
<servlet-name>FormReader</servlet-name>
<servlet-class>com.app.servlet.FormReaderServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormReader</servlet-name>
<url-pattern>/insert</url-pattern>
</servlet-mapping>
<!-- To Show full Url Direct in Address bar after execution of project -->
<welcome-file-list>
<welcome-file>Register.html</welcome-file>
</welcome-file-list>
</web-app>
Output:--
79 | P a g e
Adv. Java by Mr. RAGHU
---------------------------------------------------------------------------------------------------------------
Working with Life cycle methods:--
Servlet API has provided 3 abstract methods in javax.servlet Servlet (I) Interface. Those
are simple called as init(), service() and destroy() known as life cycle methods.
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
80 | P a g e
Adv. Java by Mr. RAGHU
Q>What is the Lazy loading (or) when servlet object is created in server?
Ans>On First request made by web client, web server creates objects to servlet class and
calls init() method at same time. This is also called as Lazy loading. So, First request will
always slow (takes time to create object and call init() then service() method). 2nd
Request onwards only service() will be called.
Folder Structure:--
Code:--
1>Servlet class:--
package com.app.servlet;
import java.io.IOException;
import javax.servlet.GenericServlet;
81 | P a g e
Adv. Java by Mr. RAGHU
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
2>web.xml code:--
<?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" id="WebApp_ID" version="3.0">
<display-name>ServletRedirectEx</display-name>
<servlet>
<servlet-name>lifecycle</servlet-name>
<servlet-class>com.app.servlet.LifeCycleServlet</servlet-class>
<load-on-startup>10</load-on-startup>
82 | P a g e
Adv. Java by Mr. RAGHU
</servlet>
<servlet-mapping>
<servlet-name>lifecycle</servlet-name>
<url-pattern>/cycle</url-pattern>
</servlet-mapping>
</web-app>
Config Context
1>Ratio is n:n 1>Ratio is 1 : n
2>When servlet obj is created, then 2>Created on server startup
83 | P a g e
Adv. Java by Mr. RAGHU
config is created
3>If servlet is destroyed then config also 3>destroyed when server is
destroyed stopped.
NOTE:--
=>Both are temporary Memories.
=>Both holds data in key =value format.
=>By default key, value is string types.
=>By using ServletConfig we can get ServletContext memory link (because for all config
only one context).
=>But using ServletContext we cannot get ServletConfig memory (there are multiple
config memories exist).
=>Config memory exist if servlet object is exist, context memory exist even server has
zero servlet objects.
----------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
ServletConfig:--
=>It is a memory holds data in key=value format, It is used to pass input data to init-
method mainly.
=>in web.xml file under <servlet> tag write code like,
<init-param>
<param-name>mydata</param-name>
<param-value>Hello</param-value>
84 | P a g e
Adv. Java by Mr. RAGHU
</init-param>
=>Then server created objects with data like.
Folder Structure:--
Code:--
#1>Servlet class:--
package com.app.servlet;
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
85 | P a g e
Adv. Java by Mr. RAGHU
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class LifeCycleServlet extends GenericServlet
{
public void init(ServletConfig config)throws ServletException
{
String val =config.getInitParameter("Mydata");
System.out.println("From init method call : " +val);
}
public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException
{
System.out.println("From service method");
}
}
=>Run on server Enter URL like: http://localhost:8080/ServletEx/cycle
2>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" id="WebApp_ID" version="3.1">
<display-name>ServletConfigInit</display-name>
<servlet>
<servlet-name>Life</servlet-name>
<servlet-class>com.app.servlet.LifeCycleServlet</servlet-class>
<init-param>
<param-name>mydata</param-name>
<param-value>Hello</param-value>
</init-param>
</servlet>
86 | P a g e
Adv. Java by Mr. RAGHU
<servlet-mapping>
<servlet-name>Life</servlet-name>
<url-pattern>/cycle</url-pattern>
</servlet-mapping>
</web-app>
Folder Structure:--
87 | P a g e
Adv. Java by Mr. RAGHU
Example code:--
1>Servlet code:--
package com.app.servlet;
public class LifeCyleServlet extends GenericServlet
{
public void init(ServletConfig config)throws ServletException {
//Way#1 to read Context param
ServletContext sc =config.getServletContext();
String val = sc.getInitParameter("mydata");
System.out.println("from init"+val);
}
public void service(ServletRequest req, ServletResponse res)throws ServletException,
IOException
{
//way#2 to read Context param
ServletContext sc = req.getServletContext();
String val =sc.getInitParameter("mydata");
System.out.println("from service :" +val);
}
}
=>Run on server Enter URL like: http://localhost:2018/ServletInitParam/cycle
2>Web.xml:--
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>ServletFirstAppOfQueryParam</display-name>
<context-param>
<param-name>mydata</param-name>
<param-value>Hello Data</param-value>
88 | P a g e
Adv. Java by Mr. RAGHU
</context-param>
<servlet>
<servlet-name>Life</servlet-name>
<servlet-class>com.app.servlet. LifeCyleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Life</servlet-name>
<url-pattern>/cycle</url-pattern>
</servlet-mapping>
</web-app>
89 | P a g e
Adv. Java by Mr. RAGHU
Protocals:--Set of rules (guidelines) prepared and followed between two systems for task
execution.
Few Examples are:--
1>TCP/IP ==>Transmission Control Protocol / Internet Protocol
2>ARP ==>Address Resolution Protocal)
3>DHCP ==>Dynamic Host Configuration Protocal
4>FTP ==>File Transfer Protocal
5>HTTP ==>Hyper Text Transfer Protocal
6>ICMP ==>Internal Group Management Protocal
7>IGMP ==>Internate Group Management
8>IMAP4 ==>Internet MessageAccess Protocal version 4
9>NTP ==>Network Time Protocal
10>POP3 ==>Post office protocol version 3
11>RTP ==>Real-time Transfer Protocal
12>SMTP ==Simple Mail Transfer Protocal
13>TFTP ==>Trivial File Transfer Protocal
14>UDT ==>User Datagramprotocal
---------------------------------------------------------------------------------------------------------------
HttpServlet:--
=>GenericServlet (Abstract class) provided in javax.servlet is protocol independent i.e.
works for any type of protocol implement i.e. works for any type of protocol.
Ex:-- HTTP, FTP, SMTP….
=>But in real-time mostly used Protocol is HTTP (and HTTPS), to handle this protocol
specially with all its features Specially with all its features Sun Microsystem has provided
HttpServlet (Abstract class) in package javax.servlet.http.
=>Here GenericServlet is having only one abstract mthod “service()” and HttpServlet is
having zero abstract methods.
=>HttpServlet extends GenericServlet internally.
---------------------------------------------------------------------------------------------------------------
90 | P a g e
Adv. Java by Mr. RAGHU
Q>Why HttpServlet (or any other) is declared as abstract even it is not having abstract
methods?
Ans>HttpServlet has all method with no Customer specific logic, all method having
simple/default logic which provide no service. So, it is not recomanded to create object
this, finally declared as abstract.
=>GenericServlet (Abstract class) is having one abstract method, also called as life cycle
method.
service(ServletRequest, ServletResponse) throws ServletException, IOException [Life
Cycle method]
=>HttpServlet(Abstract class) is having zero abstract methods. Also service() method with
http
Parameters are given as:
Service(HttpServletRequest, HttpServletResponse) throws ServletException, IOException
--->[No Lify cycle method]
=>For every task one doXXX() method is used. For example every doXXX method is
compared with basic operations, then
1>doGet()==>Get the data from Server.
91 | P a g e
Adv. Java by Mr. RAGHU
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
Folder Structure:--
92 | P a g e
Adv. Java by Mr. RAGHU
Example Code:--
1>Create Servlet class under src folder [Which re-direct application after some time
(sec)]
package com.app.servlet;
public class EmployeeServelet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
PrintWriter out = res.getWriter();
res.addHeader(“Refresh”, “12; http://www.google.com/”);
out.print(new java.util.Date());
}
}
=>Run on server Enter URL like: http://localhost:3030/HttpServletMethods/message
2>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" id="WebApp_ID" version="3.0">
<display-name>HttpServletMethods</display-name>
<servlet>
<servlet-name>Sample</servlet-name>
<servlet-class>com.app.servlet.EmployeeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Life</servlet-name>
<url-pattern>/message</url-pattern>
</servlet-mapping>
<!-- To Show full Url Direct in Address bar after execution of project -->
</web-app>
93 | P a g e
Adv. Java by Mr. RAGHU
URL format:--
Protocal:--//IP:PORT/ContextPath/ServletUrlPattern
URI: -- /ContextPath/ServletUrlPattern
=>URL is used to identify one unique location of a resource (file/data).
(Uniform Resource Locator)
=>URI is a combination of ProjectName (ContextPath) and other part of URL patterns of
servlets.
=>IP : Unique number given to one system (Computer) in a network.
PORT:-- A unique number given to every service(software) in a System, assigned by OS,
Starts from zero (0) upto 65535.
=>Reserved port numbers are: 0 - 1024.
Example:--
Ex:-- http://17.86.19.18:8090/employee/show?sid=10
Here http ==>Protocal
8090 ==>port number
Employee==>ContextPath (ProjectName)
?sid=10==>Query String
=>These details, we can get in HttpServlet using “HttpServletRequest” (I).
94 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
Code:--
1>Servlet class:--
package com.app.servlet;
out.println(“URL is = “ +url.toString());
95 | P a g e
Adv. Java by Mr. RAGHU
out.println(“URI is = “ +uri);
2>Web.xml:--
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RequestInfoServlet8</display-name>
<servlet>
<servlet-name>Reg</servlet-name>
<servlet-class>com.app.servlet.ReqInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Reg</servlet-name>
<url-pattern>/message</url-pattern>
</servlet-mapping>
</web-app>
ContentType:-- Here Content means data this option is used to provide “What type of
data is provided by a servlet as a Response”.
=>In simple “Response has what data?” Text Data?, Image Data?, PDF Data?, Excel Data?,
Audio Data?, etc…
=>Every Response should better have Content Type. It follows format: “type/subtype”
Folder Structure:--
1>Servlet class:--
package com.app.servlet;
97 | P a g e
Adv. Java by Mr. RAGHU
2.>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" id="WebApp_ID" version="3.0">
<display-name>ServletContentType</display-name>
<servlet>
<servlet-name>DataServlet</servlet-name>
<servlet-class>com.app.servlet.DataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/content</url-pattern>
</servlet-mapping>
</web-app>
98 | P a g e
Adv. Java by Mr. RAGHU
Code:--
1>Servlet class:--
package com.app.servlet;
public class PdfDataServlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("application/pdf");
res.addHeader("Content-Disposition","attachment;filename=mydata.pdf");
try {
//1. Create one Document
Document doc = new Document();
//2. Get Writer over Doc
PdfWriter.getInstance(doc, res.getOutputStream());
//3. Open Doc
doc.open();
//4. Write data
doc.add(new Paragraph("Hello Pdf"));
99 | P a g e
Adv. Java by Mr. RAGHU
2>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" id="WebApp_ID" version="3.0">
<display-name>ContentTypePDF</display-name>
<servlet>
<servlet-name>DataServlet</servlet-name>
<servlet-class>com.app.servlet.PdfDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/pdf</url-pattern>
100 | P a g e
Adv. Java by Mr. RAGHU
</servlet-mapping>
</web-app>
--------------------------------------------------------------------------------------------------------------
=>Apache POI is a 3Rd party API used to generate Excel Output using “HSSF API” classes
are given as:
=> jars download Links:
http://www-eu.apache.org/dist/poi/release/bin/poi-bin-4.0.0-20180907.zip
101 | P a g e
Adv. Java by Mr. RAGHU
=>After downloading Apache POI .zip extract to one folder that looks like below (copy all
11 jars from here to Project lib folder).
Folder Structure:--
Code:--
1>Servlet class:--
package com.app.servlet;
//ctrl+shift+O(Imports)
public class ExcelDataServlet extends HttpServlet
{
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
102 | P a g e
Adv. Java by Mr. RAGHU
res.setContentType("application/vnd.ms-excel");
res.addHeader("Content-Disposition","attachement:filename=students.xls");
try { //1. Create WorkBook
HSSFWorkbook book = new HSSFWorkbook();
//2.Create Sheet in workbook
HSSFSheet sheet = book.createSheet("My STUDENTS DATA");
//3.Create Rows in sheet
HSSFRow row0=sheet.createRow(0);
//4.Create Cells and add data
//>> 1st row with data
row0.createCell(0).setCellValue("S1.No.");
row0.createCell(1).setCellValue("Name");
row0.createCell(2).setCellValue("Marks");
HSSFRow row2=sheet.createRow(1);
row2.createCell(0).setCellValue("102");
row2.createCell(1).setCellValue("Ramu");
row2.createCell(2).setCellValue("95.36");
}
}
}
=>Run on server Enter URL like: http://localhost:3030/ContentTypeExcel/excel
2.>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" id="WebApp_ID" version="3.0">
<display-name>ContentTypeExcel</display-name>
<servlet>
<servlet-name>Sample</servlet-name>
<servlet-class>com.app.servlet.ExcelDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Sample</servlet-name>
<url-pattern>/excel</url-pattern>
</servlet-mapping>
</web-app>
Servlet Redirect:--
=>When ever request is made by browser it will goto one servlet here this servlet only
provides response.
=>Instead of this if we want to execute another servlet or another application service
then we should re direct from our servlet to another servlet or another application by
using bellow code
response.sendRedirect(“/url”);
NOTE:--
104 | P a g e
Adv. Java by Mr. RAGHU
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
S1 = Servlet #1 in App#1
S2 = Servlet #2 in App#1
S3 = Servlet #3 in App#2
S4 = Servlet #4 in App#3
xyz = non Java (not a servlet) in App#4
105 | P a g e
Adv. Java by Mr. RAGHU
---------------------------------------------------------------------------------------------------------------
Folder Structure:--
Code:--
1>Under WebContent create one HTML, file
<Html><body>
<h1>Search Engine Page</h1>
<body>
<h1>Search Engine Page</h1>
<form action="redirect" method="get">
<pre>
Search Here:
106 | P a g e
Adv. Java by Mr. RAGHU
}
//goto URL (Search engine
res.sendRedirect(url);
}}
=>Run on server Enter URL like: http://localhost:3030/Redirect
2>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"
id="WebApp_ID" version="3.0">
<display-name>ServletRedirectEx9</display-name>
<servlet>
<servlet-name>search</servlet-name>
<servlet-class>com.app.servlet.SearchEngineServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>search</servlet-name>
<url-pattern>/redirect</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>search.html</welcome-file>
</welcome-file-list>
</web-app>
Types of Dispatching:--
108 | P a g e
Adv. Java by Mr. RAGHU
a>forward:-- If request made to Servlet#1 then it can send to Servlet#2 and Servlet#2
finally gives response.
=>servlet#2 can read servlet#1 request data
=>It is one directional (forward) only not backward.
b>include:-- Current servlet can goto another servlet, execute that and get response
back to our servlet.
=>Bi-Directional possible. It should also carry Data from one servlet to another servlet.
---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
Code is:--
RequestDispatcher dispatcher = request.getReuestDispatcher(“/url”);
dispatcher.forward(request, response); Or dispatcher.include(request, response);
109 | P a g e
Adv. Java by Mr. RAGHU
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
Folder Structure:--
110 | P a g e
Adv. Java by Mr. RAGHU
Code:--
1>EmpRegister.html:--
<!DOCTYPE html>
<html><head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="calculate" method="post">
Enter Name : <input type="text" placeholder="ename" name="ename" /><br>
Enter BASIC Salary : <input type="text" placeholder="basic" name="basic"/><br>
<input type="submit" value="get info" />
</form></body></html>
2>Servlet code:--
a>EmpHraServlet:--
package com.app.servlet;
import java.io.IOException;
111 | P a g e
Adv. Java by Mr. RAGHU
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
{
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, ArithmeticException,IOException
{
//1. read basic, name data
String ename=req.getParameter("ename");
String str =req.getParameter("basic");
System.out.println(ename);
System.out.println(str);
//2.Parse data
double basic = Double.parseDouble(str);
//Calculate TA
double ta =basic*8/100;
//4.Read HRA Servlet data
Object ob =req.getAttribute("hra");
package com.app.servlet;
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;
<servlet>
<servlet-name>Service2</servlet-name>
<servlet-class>com.app.servlet.EmpFinalServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Service2</servlet-name>
<url-pattern>/final</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Service3</servlet-name>
<servlet-class>com.app.servlet.HeaderServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Service3</servlet-name>
<url-pattern>/header</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Service4</servlet-name>
115 | P a g e
Adv. Java by Mr. RAGHU
<servlet-class>com.app.servlet.FooterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Service4</servlet-name>
<url-pattern>/footer</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Register.html</welcome-file>
</welcome-file-list>
</web-app>
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
Example:-
----------------------------------------------------------------------------------------------------------------
HTTP Response Format:--
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
117 | P a g e
Adv. Java by Mr. RAGHU
----------------------------------------------------------------------------------------------------------------
Examples codes for Http Servlets methods:--
Folder Structure:--
1.>servlect class:--
package com.app.servlet;
public class MyServletEx extends HttpServlet
{@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter out = res.getWriter();
out.print("From GET Method");
}
@Override
118 | P a g e
Adv. Java by Mr. RAGHU
NOTE:--
1>URL is case sensitive. i.e /data and /Data, /DATA, /DaTa are different.
119 | P a g e
Adv. Java by Mr. RAGHU
2>If Request URL is not matched with any <url-pattern> in web.xml, server returns
HttpStatus 404 – not Found
3>If URL matched and Request Method Type is not matched with any Servlet doXXX
method then server throws Http Status method then server throws Http Satus 405
Method not Allowed.
Ex:--Request is GET Type and sservlet has only doPost() and doPost() then 405 Error.
---------------------------------------------------------------------------------------------------------------
Statefull/State management:--
Session Management:--
=>Storing user related data at server for long time (Login=Logout Time) is know as
Session/State Management.
120 | P a g e
Adv. Java by Mr. RAGHU
----------------------------------------------------------------------------------------------------------------
Cookie:--
a>Cookie is a memory created by server and stored in browser.
b>Cookie stores data (at max 4KB) only text data.
c>A cookie created by server will be sent to browser using Http Response Head Area.
d>All cookies will be submitted along with your request using Http Request Head.
e>Cookie Stores data in key=value format. Those are also called as Attribute Name and
Attribute Value.
f>Every Cookie will be having max life time (expiry time). Default is -1 indicates on
browser close all cookies are removed from browser cache.
g>We/Programmer can set life time of a cookie using method setMaxAge in sec(int
value) values.
i.e 60 sec = 1 min
h>**A Cookie created by Server (S#1) can only read/modify/deleted by same Server(S#1)
only.
Not by other servers by default.
---------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
121 | P a g e
Adv. Java by Mr. RAGHU
Steps:--
1>Make New/First Request using browser
2>Server creates new Cookie and adds to Http Response (Head).
3>Response send back to the browser.
4>Browser creates all new cookies in Browser cache.
5>Browser submits all Cookies related to same Server using Http Request Head.
Limitations:--
=>In Browser we can disable Cookie concept, then application may not work properly.
=>Stores only Text data, not binary data like Images, Audio, Video, etc.
=>Secure data cannot be stored in Cookie.
Working on Cookie:--
1>To create one Cookie use class Cookie given by servlet HTTP API in package
“javax.servlet.http” use parameterized constructor.
Cookie c = new Cookie (name, value);
3>On request made, browser submits all Cookies to server using HTTP Request Head. To
read those codes is:
Cookie[] cks =
request.getCookies();
4>To read one Cookie data use index number and methods like getName(),
cks[0].getName(); cks[0].getValue);
122 | P a g e
Adv. Java by Mr. RAGHU
1>Create Cookie:--
2>Read Cookie:--
--------------------------------------------------------------------------------------------------------------
Folder Structure:--
123 | P a g e
Adv. Java by Mr. RAGHU
Code:--
1>Login.html (Under WebContent):--
<!DOCTYPE html>
<html><head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Welcome to Cookie Example</h2>
<form action ="create" method="POST">
<pre>
ID :<input type="text" name="uid"/><br>
Name :<input type="text" name ="uname"/><br>
<input type ="submit" value="submit"/>
</pre></form>
</body></html>
2>Create two servlet class one for Creating and another for Reading Cookies:
i>For Creating Cookies:--
package com.app.servlet;
public class CookiesCreateServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
//1.Read data From input
String uid = req.getParameter("uid");
String uname = req.getParameter("uname");
//2.Create Cookies
Cookie c1 = new Cookie("uid", uid);
Cookie c2 = new Cookie("uname", uname);
//3.Add to response
res.addCookie(c1);
res.addCookie(c2);
//4.Print done message
PrintWriter out = res.getWriter();
out.print("Cookies Created");
}
}
ii>For Reading Cookie:--
package com.app.servlet;
public class CookiesReadServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
//1.Read all Cookies from request-head
Cookie[] cks = req.getCookies();
//2.Print cookie name, value
PrintWriter out = res.getWriter();
if(cks!=null && cks.length!=0)
{
for(int i =0; i<cks.length; i++)
{
out.print("Cookie name = "+cks[i].getName()+
",value="+cks[i].getValue());
}}
else {
out.print("No Cookies Found");
}
}}
3>web.xml:--
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
125 | P a g e
Adv. Java by Mr. RAGHU
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" id="WebApp_ID" version="3.0">
<display-name>ServletCookies</display-name>
<servlet>
<servlet-name>c1</servlet-name>
<servlet-class>com.app.servlet.CookiesCreateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>c1</servlet-name>
<url-pattern>/create</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>c2</servlet-name>
<servlet-class>com.app.servlet.CookiesReadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>c2</servlet-name>
<url-pattern>/read</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Execution Order:--
#1>Start the server and Enter URL in browser:
http://localhost:3030/ServletCookies/create
#2>Enter details and submit Form.
#3>Enter below URL to view Cookies: http://localhost:3030/ServletCookies/read
126 | P a g e
Adv. Java by Mr. RAGHU
Types of Cookies:--
1>SessionCookies/Browsing Session Cookies:--
=>A Cookie which do not have expiration time As soon as the web browser is closed this
cookies gets destroyed.
2>Persistent Cookies:--
=>A Cookie is created with life-time and Destroyed based on the expiry time.
Coding Point:--
a>Create one new session.
HttpSession ses = request.getSession();
Or
HttpSession ses = request.getSession(true);
127 | P a g e
Adv. Java by Mr. RAGHU
128 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
Code:--
1>Login.html:--
<!DOCTYPE html>
<html><head>
129 | P a g e
Adv. Java by Mr. RAGHU
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head><body>
<h2>welcome to Login page!!</h2>
<form action="login" method="post">
<pre>
NAME : <input type="text" name="username"/>
PASSWORD : <input type="password" name="userpwd"/>
<input type="submit" value="Login"/>
</pre></form></body></html>
2>LoginCheckServlet:--
package com.app.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
131 | P a g e
Adv. Java by Mr. RAGHU
if(ses!=null) {
//remove user name
ses.removeAttribute("user");
//remove session
ses.invalidate();
}
//show Success Message
out.println("Successfully logged out");
out.println("<a href='login.html'>Login Here</a>");
}
}
4>ProfileServlet:--
package com.app.servlet;
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;
import javax.servlet.http.HttpSession;
public class ProfileServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
{
//read current session
HttpSession ses=req.getSession(false);
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
if(ses!=null)
{
//if session exist
132 | P a g e
Adv. Java by Mr. RAGHU
Object ob=ses.getAttribute("user");
out.println("Welcome to User ::"+ob);
out.print("<a href='logout'>Logout</a>");
}else
{
//session not exist
out.print("You are not logged in ");
out.print("<a href='login.html'>Please Login</a>");
}
} }
5>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" id="WebApp_ID" version="3.0">
<display-name>SessionManagement</display-name>
<welcome-file-list>
<welcome-file>Login.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginCheck</servlet-name>
<servlet-class>com.app.servlet.LoginCheckServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginCheck</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Profile</servlet-name>
<servlet-class>com.app.servlet.ProfileServlet</servlet-class>
</servlet>
133 | P a g e
Adv. Java by Mr. RAGHU
<servlet-mapping>
<servlet-name>Profile</servlet-name>
<url-pattern>/profile</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Logout</servlet-name>
<servlet-class>com.app.servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Logout</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
</web-app>
Execution Order:--
#1>Start the server and Enter URL in browser:
http://localhost:3037/SessionManagement/
#2>Enter user name as nareshit and password as admin and submit Form.
---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
#3>Click on logout Button for logout.
1>Tight coupling:-- If one code(class) gets changed then another code(class) gets
effected. But they are connected final.
Ex:-- class Parent {
Void get() {
Child c = new Child();
c.show();
}}
class Child {
Void show() { ---}
}
=>if we modify child class name (or moved) to another class) or method name (or
changed to another method) then parent class code gets effected (need to modify).
2>Loosely Couplinng:--Link (Integrate) two codes (classes) if child gets modified then it’s
parent should not be, changed should come only at link.(use Factory with POJI-POJO)
---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
=>In JDBC, to get one Communication object for all DB operations use “Singleton” design
pattern. Here use static block which will be executed only once while loading class.
Format:
public class _____Util {
135 | P a g e
Adv. Java by Mr. RAGHU
POJO/Model:-- A class not connected to any special Technology (like Servlets, JSP, JDBC,
Java Mail, JMS, JSF..) having simple variable with set/get methods. No logical/operations
methods.
[POJO = Plane Old Java Object]
**These classes object are used to store/read only data.
---------------------------------------------------------------------------------------------------------------
Coding Order:--
1.>ConnUtil (Singleton) :--This class return one connection obj
pack : com.app.util
class : ConnUtil.java
2.>Employee (Model) :-- It is used to store only FORM data and same inserted in DB
Table row.
pack : com.app.model
class : Employee.java
3.>IEmployeeDao(POJI) and EmployeeDaoImpl (POJO) used for loosely coupling process
136 | P a g e
Adv. Java by Mr. RAGHU
pack : com.app.dao
cinterface : IEmployeeDao.java
pack : com.app.dao
class : EmployeeDaoImpl.java
4>EmployeeDaoFactory (Factory class) :-- It creates POJO object and return POJI format.
pack : com.app.factory
class : EmpDaoFactory.java
5>register.html (UI Page) :-- It will display HTML Form to register employee. It is set as
welcome-file Location: Under “WebContent”
6>EmployeeRegisterServlet (HttpServlet) :-- This servlet will execute below steps.
137 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
Code:--
1>Create a ConnUtil class:--
package com.app.util;
import java.sql.Connection;
import java.sql.DriverManager;
138 | P a g e
Adv. Java by Mr. RAGHU
"system","system");
}
catch (Exception e) {
e.printStackTrace();
}
}
//return conn object
public static Connection getConn(){
return con;
}
}
2>Create an Employee Model class:--
package com.app.model;
public class Employee {
private int empId;
private String empName;
private String empGen;
private String empAddr;
//set/get methods
//alt+shift+S,R(SelectAll>OK)
}
141 | P a g e
Adv. Java by Mr. RAGHU
142 | P a g e
Adv. Java by Mr. RAGHU
---------------------------------------------------------------------------------------------------------------
Types of URL Patterns:--
Q>Why URL Patterns?
Ans>Browser can’t understand Java Objects and can’t make servletObj.service() method
call. So, programmer should write code in web.xml as.
143 | P a g e
Adv. Java by Mr. RAGHU
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>com.app.Emp</servlet-class>
</servlet>
=>Above code means creating a servlet object (by using container).
It means
Emp s1 = new Emp();
Next we should write code like:
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
=>It means link URL with above object, when browser enter above URL and then server
calls s1.service(req, res) method.
--------------------------------------------------------------------------------------------------------------
Q>How many Types of URL Patterns supported by servlet? Why?
Ans>3 types Those are
1>Exact Match ex:/insert
2>Extension Match ex :*.do, *.nareshit
3>Directory match Ex:/emp/*, /nareshit/*, /abc/*
1>Exact match:-- One servlet will do one task by default, in this case use this URL,
Pattern.
2>Extension Match:-- One servlet wants to do multiple operations based on request
URL. But it will not support all types of Parameters [input data] concept.
Ex Path parameters is not supported.
>>example Pattern : *.do
144 | P a g e
Adv. Java by Mr. RAGHU
145 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
if(p1==null || p2==null)
{
out.println("Provider P1, P2 inputs");
}
else { //parse data to double
double d1 =Double.parseDouble(p1);
double d2 =Double.parseDouble(p2);
//read request URI
String uri = req.getRequestURI();
if(uri.contains("add"))
{
out.print("Result is : "+(d1+d2));
}
else if(uri.contains("sub"))
{
out.print("Result is : "+(d1-d2));
}
else if(uri.contains("mul"))
{
out.print("Result is : "+(d1*d2));
}
else if(uri.contains("div")) {
out.print("Result is : "+(d1/d2));
}
else
out.println("Result is Not Found");
}
}}
2>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"
147 | P a g e
Adv. Java by Mr. RAGHU
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>URLPatterns19</display-name>
<servlet>
<servlet-name>URLS</servlet-name>
<servlet-class>com.app.servlet.PatternCheckServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>URLS</servlet-name>
<url-pattern>/pattern/*</url-pattern>
</servlet-mapping>
</web-app>
Execution Steps:--
=>Run on server and type bellow URL in browser:
Case#1>http://localhost:3037/URLPatterns19/pattern/add?p1=10&p2=20
Case#2>http://localhost:3037/URLPatterns19/pattern/sub?p1=10&p2=20
Case#3>http://localhost:3037/URLPatterns19/pattern/mul?p1=10&p2=20
Case#4>http://localhost:3037/URLPatterns19/pattern/div?p1=10&p2=20
Filter:-- Filters are auto-executable codes for servlets. These are used to execute “Pre-
processing logic on request” and “Post-processing logic on response”.
1>To create one filter write one class and implement Filter (I) interface given by
javax.servlet package.
2>It has 3 abstract methods also called as life cycle methods. Those are init(), doFilter(),
destroy().
3>After writing this filter class, must configure in web.xml using below code.
<filter>
<filter-name></filter-name>
<filter-class> </filter-class>
</filter>
=>It is used to create Filter class obj by servlet container (web container)
148 | P a g e
Adv. Java by Mr. RAGHU
<filter-mapping>
<filter-name> </filter-name>
<url-pattern> </url-pattern>
</filter-mapping>
=>This code is used to link one filter with servlet, i.e ****Filter URL Pattern must match
with servlet URL pattern.
4>Filter class Objects are created by Servlet container on server startup (default:
eager/early loading).
<load-on-startup> is not possible.
5>For one servlet we can write multiple Filter, execute in web.xml configuration order.
6>Filter Accept the init() parameters like servlet. Input to init method.
7>To unlink Filter with servlet, just change filter URL pattern .ie
**** servlet URL pattern != Filter URL pattern
=>It is also called as Filter are plugable. i.e Easy link/unlink.
8>Filter can be used only for either “pre-processing” or “Post-processing” or even both.
9>Browser makes request to servlet only but filter process it then goes to servlet.
10>***doFilter() method is available in Filter interface as life cycle method and in
FilterChain to call next Filter or servlet.
11>Filter are used in security Programming Session check, encrypt and decrypt, identity
verification, request data validation, response conversions etc..
12>One filter can be linked with multiple servlets also. But servlets URL pattern some
part must be same, then Filter URL Pattern should follow either Extension match or
directory match.
149 | P a g e
Adv. Java by Mr. RAGHU
------------------------------------------------------------------------------------------------------------------
150 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
Code:--
1>SampleServlet:--
package com.app.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
151 | P a g e
Adv. Java by Mr. RAGHU
}
3>TestFilterTwo:--
package com.app.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
4>web.xml:--
<?xml version="1.0" encoding="UTF-8"?>
153 | P a g e
Adv. Java by Mr. RAGHU
<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" id="WebApp_ID" version="3.0">
<display-name>ServletFilter20</display-name>
<servlet>
<servlet-name>SampleServlet</servlet-name>
<servlet-class>com.app.servlet.SampleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet</servlet-name>
<url-pattern>/sample</url-pattern>
</servlet-mapping>
<filter>
<filter-name>F1</filter-name>
<filter-class>com.app.filter.TestFilterOne</filter-class>
</filter>
<filter-mapping>
<filter-name>F1</filter-name>
<url-pattern>/sample</url-pattern>
</filter-mapping>
<filter>
<filter-name>F2</filter-name>
<filter-class>com.app.filter.TestFilterTwo</filter-class>
<init-param>
<param-name>data</param-name>
<param-value>Hello</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>F2</filter-name>
<url-pattern>/sample</url-pattern>
</filter-mapping>
154 | P a g e
Adv. Java by Mr. RAGHU
</web-app>
=>Enter bellow URL in browser:
Case#1: http://localhost:3037/ServletFilter/sample
Case#2: http://localhost:3037/ServletFilter20/sample?Hello
Servlet Listeners:--
A Listeners is a code (class-with-method) which will be executed by container
automatically on a event is created(fired) for an action.
Action:-- Doing is a task (execute method).
Event:-- On Action “Changing State of an Object” (ex: created=>Destroyed)
Listener:-- On event creation do some extra work.
=>ServletListeners are auto executable codes for ServletEvents.
=>All Events are classes and all Listeners are Interfaces.
Scope:-- It indicates time period of data in memory.
***Servlet Scopes:--
1>Request Scope 2>Session scope 3>Context Scope
=>These scope are used to store the data in memory in key=value format also known as
Attributes.
(Attribute name and Attribute value)
=>These scopes are used to store data and share data between Servlets
a>Request Scope:-- Used between two servlets
b>Session Scope:-- Used between multiple (not all) servlets between login to logout
time.
c>Context Scope:-- Used between all servlets server start to stop.
Scope Interface
Request Scope ServletRequest
Session Scope HttpSession
Context Scope ServletContext
155 | P a g e
Adv. Java by Mr. RAGHU
NOTE:--Listeners are used to execute extra work when events are performed (fired).
=>Servlets Supports 2 Types of Listeners
1>Lifecycle Listener 2>Attribute Listener
B>Attribute Events/Listeners:--
Action Event Listener Method
Request Attribute ServletRequest ServletRequest attributeAdded()
Added/removed/modified AttributeEvent AttributeListener attributeRemoved()
156 | P a g e
Adv. Java by Mr. RAGHU
attributeReplaced
SessionAttribute HttpSession HttpSession attributeAdded()
added/removed/modified BindingEvent AttributeListener attributeRemoved()
attributeReplaced
ContextAttribute ServletContext ServletContext attributeAdded()
added/removed/modified AttributeEvent AttributeListenre attributeRemoved()
attributeReplaced()
Step#3:--After writing class code, configure those in web.xml using below format.
<listener>
<listener-class>……</listener-class>
</listener>
157 | P a g e
Adv. Java by Mr. RAGHU
HttpSessionBindingListener:--
=>This Listeners are used to work on special type of classes, when these classes Object
added to session or removed from session.
Ex:--Employee class is provided by programmer, for this create object and add to session
or removed from session need extra automatic coding for this use above listener.
-----------------------------------------------------------------------------------------------------------------
158 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
Code:-
1>web.xml:--
159 | P a g e
Adv. Java by Mr. RAGHU
2>Servlet Class:--
package com.app.servlet;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
160 | P a g e
Adv. Java by Mr. RAGHU
import com.app.listeners.User;
public class TestServlet extends HttpServlet
{
protected void doGet(javax.servlet.http.HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException {
System.out.println("--Request Attribute Related events--");
req.setAttribute("user", "ajay");
req.setAttribute("user", "vijay");
req.removeAttribute("user");
System.out.println("=====================================");
System.out.println("--Session Attribute Related events--");
HttpSession session=req.getSession();
session.setAttribute("admin", "uday");
session.setAttribute("admin", "varun");
session.removeAttribute("admin");
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class MyServletRequestListener implements
ServletRequestAttributeListener,ServletRequestListener
{
//attribute specific
public void attributeRemoved(ServletRequestAttributeEvent event) {
System.out.println("Request Attribute Removed
:name="+event.getName()+",value="+event.getValue());
}
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
5>Context Listener:--
package com.app.listeners;
163 | P a g e
Adv. Java by Mr. RAGHU
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* Application Lifecycle Listener implementation class MyServletContextTestListener
*
*/
@WebListener
public class MyServletContextListener implements ServletContextAttributeListener,
ServletContextListener {
} }
6>Session Binding Listener:--
package com.app.listeners;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
/**
* Application Lifecycle Listener implementation class User
*
*/
@WebListener
public class User implements HttpSessionBindingListener
{
private String userData;
public User(String userData) {
this.userData=userData;
} public void valueBound(HttpSessionBindingEvent event) {
System.out.println("Session Bound:"+event.getName());
}
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("Session Unbound:"+event.getName());
}
public String getUserData() {
return userData;
}
public void setUserData(String userData) {
this.userData = userData;
}
}
=>Run as run on server and pass below URL in browser:
Servlets Annotations (Servlet 3.x):--
=>Servlet Annotations are introduced in Servlet API 3.x version (Tomcat version >=7.x).
165 | P a g e
Adv. Java by Mr. RAGHU
#1:--@WebServlet:-- This is used for servlet configuration supports URL Pattern, load on
startup, init-param etc.
2>Annotation mistakes are show at compile time only. But XML mistakes are shown at
runtime.
3>Minimum JDK version is : 6.X
Tomcat is: 7.X, Servlets is : 3.X
EMAIL : javabyraghu@gmail.com
FB: https://www.facebook.com/groups/thejavatemple/
167 | P a g e
Adv. Java by Mr. RAGHU
7>Servlet Container creates Object to Generated class and calls init method once.
Named as “jspInit()”
8>When browser/Client made request, then service method is executed Named as
“_jspService()”.
=>This method gives response back.
9>Finally destroy method is called before destroying object, named as “jspDestroy()”.
10>Servlet container destroy the object.
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
=>In JSP File we should write everything as Tag format only. We can write HTML Tags
and JSP Tags.
=>JSP Tags are again divided into 4 types.
1>Scripting Tags:--
=>It is used to write Java code, like variables, methods, block, inner classes, printing
statements etc.
2>Directive Tags:--
=>It is used to Link other sources with this file. Like import statements, link with other
JSP, Session linking, error pages etc.
169 | P a g e
Adv. Java by Mr. RAGHU
1.>SCRIPTING TAGS:--These are used to insert java code in JSP file as Tags given in 3
types.
a>Declration : <%! %>:--To insert code inside class and outside service method.
b>Scriplet <% %>:--To insert code inside service method and outside println().
c>Expression <%= %>:--To insert code inside println().
-----------------------------------------------------------------------------------------------------------------
a>Declaration : <%! %>:--
=>This tag is used to insert java code inside class and outside all methods.
Valid code:--
1.>instance or static variables
2>instance or static methods
3>instance or static blocks
4> Constructors [no use]
5>member (instance) or static inner class
Invalid Code:--
1.>Only writing Statements
Ex:- System.out.println()
2>only imports
E:--import javax.servlet;
170 | P a g e
Adv. Java by Mr. RAGHU
Ex:--
<!%
int sid=0;
void show(){…}
%>
Result : Valid
2. <%!
public static final String a=”A”;
%>
Result :-
3><%!
Int sid=show();
public int show() { return 10;}
%>
Result : Valid
4><%!
System.out.println(“HI”);
%>
Result: Invalid
5><%!
class Hello {
void show{ }
%>
Result : Valid
6><%!
{
System.out.println(“Hello”);
}
%>
Result : Valid
171 | P a g e
Adv. Java by Mr. RAGHU
7><%!
static {
String s = Hello”;
System.out.prinln(s);
}
%>
Result: Valid [s is local Variable]
8><%!
String s =”Hello”;
int a =s.length();
%>
Result : Valid
9><%!
A a = new A();
class A{ }
%>
Result :-Valid
10><%! %>
Result : Valid
valid Codes:--
a.>local variables
b.>Statements
c.>block [but not static]
d.>writing loops, conditional statements
e.>calling methods
f.>writing class [local class]
172 | P a g e
Adv. Java by Mr. RAGHU
Not Valid:--
a.>nesting of methods [writing one method in another method]
b>static variables or blocks.
Examples:--
1.><%
System.out.println(“HI”);
%>
Result: Valid
2.><%
for(int i=0; i<=10; i++) {….}
%>
Result: Valid
3><%
Date d = new Date();
System.out.println(d);
%>
Result: Valid
4>><%
public static final int a=10
System.out.println(a);
%>
Result: InValid
5>><%
Int a =10;
System.out.println(a);
%>
Result: Valid
6><%
A a = new A();
a.show();
%>
173 | P a g e
Adv. Java by Mr. RAGHU
Result: Valid
7><%
Class Sample{ }
%>
Result: Valid
8><%
Interface A { }
A a = new A() { }
%>
Result: Valid
Valid code:--
a>Any literal (without semi-column).
Ex:-- 10, “Hello”, ‘A’, -8.9
b>calling method returns non-valid
ex:--int show() { } is exist
ob.show(); [Valid]
c>printing variables, object references Collection variable.
InValid code:--
a>Writing statements.
b>declaring variables.
c>Calling void methods.
d>***Writing semicolons.
Examples:--
1><%=”Hello” %>==>[Valid]
2><%=10; %>==>[InValid]
3>assume show() returns int type
<%=ob.show() %>[valid]
174 | P a g e
Adv. Java by Mr. RAGHU
First Example:--
#1>Create one new dynamic web project
=>file =>new=>Dynamic Web Project
=>Enter name: FirstApp
=>choose also
Target Runtime : Apache Tomcat
Dynamic web module version : 2.5
=>next=>next=>finish
175 | P a g e
Adv. Java by Mr. RAGHU
FirstPage.jsp
<html><body>
<%! int count=0; %>
<%count++; %>
<%= "No of views: "+count%>
</body></html>
1. out JspWriter
2. request HttpServletRequest
3. response HttpServletResponse
4. session HttpSession
5. config ServletConfig
6. application ServletContext
7. page Object(java.lang)
8. pageContext PageContext
9. exception Throwable
PageContext :--
It is a global object created by WebContainer which holds other objects (implicite)
behaves like holder. It provides auto set/get methods to use them in code. Directly
cannot be used by Programmer.
176 | P a g e
Adv. Java by Mr. RAGHU
1>out:--This object is used to print the data on UI Page. It is type of JspWriter we can
use this object in script.
Ex:--
<%
out.println(“Hello”);
%>
Which is equal to:--
<%=”Hello” %>
Folder Structure:--
</html>
CheckLuck.jsp (under WebContent)
<html><body>
<%
String ob =request.getParameter("num");
int num= Integer.parseInt(ob);
java.util.Random r = new java.util.Random();
int gnum=r.nextInt(10);
if(num==gnum)
{
out.print("You won 10L Rupes");
}
else
{
out.print("Sorry!");
}
%>
</body></html>
=>Run on server Enter URL like: http://localhost:3030/ImpliciteObjet/Index.html
2.>Directive Tags:--These tags are used to link other resources (like import, include etc).
Syntax:--<%@ %>
178 | P a g e
Adv. Java by Mr. RAGHU
a.>page Directive:-- It is used to provide JSP Page level links, few are given as
=>contentType
=>session
=>import
=>isELIgnored
=>isErrorPage
=>pageEncoding
Etc…
Folder Structure:--
179 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
Code:-Index.html
<html><body>
<form action="JspJDBCIntegration.jsp" method="post">
<pre>
User Name: <input type="text" name="user"/><br>
Password : <input type="password" name="pass"/>
<input type="submit" value="Login"/>
</pre></form>
180 | P a g e
Adv. Java by Mr. RAGHU
</body></html>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP with JDBC Integration</title>
<body>
<%!
//Writing methods with logic
public Boolean checkUser(String un, String pwd)
{
boolean isExist=false;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"system","system");
PreparedStatement pstmt = con.prepareStatement("select * from userdata where un=?
and pwd=?");
pstmt.setString(1,un);
pstmt.setString(2,pwd);
ResultSet rs = pstmt.executeQuery();
if(rs.next())
{ /* user exist */
isExist=true;
}
Else {
181 | P a g e
Adv. Java by Mr. RAGHU
//not Exist
isExist=false;
}}
catch(Exception e)
{
System.out.println(e);
}
return isExist;
}
%>
182 | P a g e
Adv. Java by Mr. RAGHU
=>It is also called s static include. It means same content is coped to JSP first then
translated into .java file.
=>Finally one .java (.class).
=>It is used mainly in common lines of code re-using concept. Example considers below
different JSP pages having common lines at top and bottom of JSP.
=>In above JSP pages Top 10 lines of code is common in every page, so move to
Header.jsp and link this in every JSP using code.
< %@include file=”header.jsp”%>
183 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
Code:--
#1>Header.jsp:--
<img src ="menu.jpg"/>
<h3>This is A Header Page</h3>
#2>Footer.jsp:--
<img src="bottom.jpg"/>
184 | P a g e
Adv. Java by Mr. RAGHU
#3>Home.jsp:--
</head><body>
<h1>Welcome to Home page to all </h1>
<%@include file="Header.jsp"%>
<%@include file="Footer.jsp"%>
</body></html>
=>Run on server=>Enter URL like: http://localhost:3030/IncludeDirectory/Home.jsp
pageContext:--
=>It is one of implicit object in JSP which holds all page related data and other objects
internally. Provides them to them to page based on requirement.
=>It also store data using different scopes in memory as attributes.
SCOPE:-- It indicates time period of data in memory. This concept is used to specify life
time of data and where it can be accessed (shared).
=>Servlet has 3 scopes. Those are:
a>Request scope:--To share data between two servlets.
b>Session scope:--To share data between multiple servlets from login to logout.
c>Context scope:--To share data to all servlets, from server start to stop.
NOTE:--
1>Data will be stored in key = value format.
2>It is also called as Attribute methods used here : setAttribute() and getAttribute().
3>scope order is
185 | P a g e
Adv. Java by Mr. RAGHU
Type ID CONSTANT
1>Page 1 pageContext.PAGE_SCOPE
2>Request 2 pageContext.REQUEST_SCOPE
3>Session 3 pageContext.SESSION_SCOPE
4>Application 4 pageContext.APPLICATION_SCOPE
186 | P a g e
Adv. Java by Mr. RAGHU
b>pageCOntext.setAttribute(“uid”, “U123”,2);
c>pageContext.setAttibute(“uid”,”U123”, pageContext.REQUEST_SCOPE);
=>12-1
=>11
Example#1:-- ${variable}
=>It will try to read the data from scope memory. To indicate them EL has provided 4
implicit objects.
Given as:
a>pageScope b>sessionScope
c>requestScope d>applicationScope
=>If we write ${sid} as example then Search in page scope if found ok, else (not found)
then goto request, next session finally application.
=>If variable is not found in any scope then final value is null, printed as Scope on
browser.
=>default checking order is:
page-next=>request-next=>session-next=>application.
=>To avoid this default order and read from one direct scope use EL implicit objects.
188 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
189 | P a g e
Adv. Java by Mr. RAGHU
Example#2 : operators.jsp
Folder Structure:--
Code: Operators.jsp:--
</head><body>
<%
pageContext.setAttribute("myid", 500);
%>
<pre>
Data is: ${myid}
Exp1: ${myid <= 600} or ${myid le 600}
Exp2: ${myid != 600} or ${myid ne 600}
Exp3: ${myid ne 400 ? (myid mod 7): (myid div 8)}
Exp4: ${!empty myid} -- ${empty myid}
Exp5: ${myid + 20 - myid*2 - myid/3}
</pre> </body></html>
=>Run on server=>Enter URL like: http://localhost:3030/Scope2/Operators.jsp
NOTE:--
ne =>not equal to (!=)
eq = equal to (==)
Mod = % (reminder)
Div = /
1)SYNTAXES:
${expression}
190 | P a g e
Adv. Java by Mr. RAGHU
2) OPERATORS
191 | P a g e
Adv. Java by Mr. RAGHU
5) EXAMPLES OF EL EXPRESSIONS:--
EL Expression Result
${1 > (4/2)} false
${4.0 >= 3} true
${100.0 == 100} true
${(10*10) ne 100} false
${'a' < 'b'} true
${'hip' gt 'hit'} false
${4 > 3} true
${1.2E4 + 1.4} 12001.4
${3 div 4} 0.75
${10 mod 4} 2
${!empty param.Add} False if the request parameter
named Add is null or an empty string.
${pageContext.request.contextPath} The context path.
${sessionScope.cart.numberOfItems} The value of
the numberOfItems property of the
session-scoped attribute named cart.
192 | P a g e
Adv. Java by Mr. RAGHU
Syntax:--
String value =request.getParameter(“key”);
This code must be written in scriptlets in case of JSP. To avoid this java code EL has
provided 2 implicit objects.
a>param : one key value
b>paramValues : one key multiple values which stores like array.
=>Param data read syntax is:
${param.key} or
${param[‘key’]}
Folder Structure:--
193 | P a g e
Adv. Java by Mr. RAGHU
ID : ${param.eid} or ${param['eid']}
NAME : ${param.ename}
SAL : ${param.esal}
Projects : ${paramValues.proj[0]}, ${paramValues.proj[1]}, ${paramValues.proj[2]}
</pre>
</body>
</html>
=>Run in server and Enter URL like:
http://localhost:3030/ExpressionLanguage(EL)/QueryOrRequestParam.jsp?eid=5&enam
e=UDAY&esal=8.4&proj=JSP&proj=Spring&proj=Hibernate
Special EL Objects:--
Folder Structure:--
Code:--
1>Expression.jsp:--
<html> <body>
<% request.setAttribute("data", "abc"); %>
<pre>
194 | P a g e
Adv. Java by Mr. RAGHU
Data : ${data}
EMPTY? : ${empty data}
NOT EMPTY? : ${!empty data }
EQUAL TO ABC : ${data eq 'abc'} : ${'Hello' eq 'abc'}
TERNARI CHECK : ${data!=null?'YES':'NO'}
LOGICAL CHECK : ${data ne null and data eq 'abc'}
</pre> </body> </html>
2. Expression2.jsp:--
<html> <body>
<% request.setAttribute("data", 400); %>
<pre>
Data : ${data}
MOD? : ${data mod 8}
DIV? : ${data div 6}
EQUAL TO ABC : ${data eq 300} : ${300 ge 400}
LOGICAL CHECK : ${data ne 80 || data lt 200}
</pre></body> </html>
3.> ImplicitObject.jsp:--
<html><body>
${param.name}
${paramValues.courses[0]}
${paramValues.courses[1]}
<hr/>
${header.host } or ${header['host'] } all ${header}
${headerValues.accept[0]}
${pageContext.request.contextPath}
${pageContext.request.cookies[0].name}
</body> </html>
4. >ImplicitObject2.jsp:--
<html> <body>
<%
pageContext.setAttribute("user", "AJAY-A");
request.setAttribute("user", "AJAY-B");
session.setAttribute("user", "AJAY-C");
application.setAttribute("user", "AJAY-D"); %>
195 | P a g e
Adv. Java by Mr. RAGHU
<pre>
${user} or ${pageScope.user}
${requestScope.user}
${pageScope.user}
${pageScope.user}
</pre>
</body></html>
Folder Structure:--
Code: SpecialEL.jsp
<html><body><pre>
${header.cookie} or ${header['cookie']}
${header.host} or ${header['host']}
${header['accept_encoding']}
${cookie.JSESSIONID.name}
${cookie.JSESSIONID.value}
${pageContext.request.contextPath}
</pre></body></html>
=>Run on Server and Enter URL in browser:
http://localhost:3033/SpecialExpressionLanguage/SpecialEL.jsp
196 | P a g e
Adv. Java by Mr. RAGHU
197 | P a g e
Adv. Java by Mr. RAGHU
Format #2:-
<%
RequestDispatcher rd = request.getRequestDispatcher(“Data.jsp”);
rd.forward(request, response);
%>
Format#3:--
<%
pageContext.forward(“Data.jsp”);
%>
Example:--Application
Folder Structure:--
a.>Process.jsp:--
<html><body>
<jsp:forward page ="Data.jsp">
<jsp:param name="user" value="UDAY"/>
</jsp:forward>
</body></html>
b.>Data.jsp:--
198 | P a g e
Adv. Java by Mr. RAGHU
<html><body>
<h2>Welcome to Data Page</h2>
<% Object ob=request.getParameter("user");
out.println(ob); %>
</body></html>
2.><jsp:include> :-- Use this action tag for RequestDispatcher include operation. We can
also send parameters using this.
<jsp:include page="Data.jsp":>
<jsp:param name="user" value="ABC"/>
</jsp:include>
Java Bean:--Java Bean is a class. It is used to create object which holds data which can
be shared between project multiple classes.
>Creating object
>providing data
199 | P a g e
Adv. Java by Mr. RAGHU
>reading data
>passing object
>destroy object
=>It is done by web container only.
=>To share this object between JSPs, It must be under one of given scopes.
1>page scope (default scope)
2>request scope
3>session scope
4>Application scope
a.<jsp:useBean>:-- This action tag is used to read object from given scope. If object not
exist then it will create new Object and placed in same scope.
Syntax:--
<jsp:useBean id=”objName” class=”fullyQualifiedClassName”
Scope=”page/request/session/application”/>
%>
b><jsp:setProperty>:-- This line is used to provide the data to one variable in Bean.
Syntax:--
<jsp:setProperty property=”variableName” name=”objetName” value”data”/>
c><jsp:getProperty>:-- This line is used to read the data from given variable from
Bean(object).
Syntax:--
<jsp:getProperty property=”variableName” name=”objName”/>
201 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
Code:--
1>Create Employee Java Bean class under src folder:--
package com.app;
202 | P a g e
Adv. Java by Mr. RAGHU
//defaut constructor
//set,get method
//toString method
}
One.jsp:--
</head><body>
<jsp:useBean id ="emp" class="com.app.Employee" scope="request"/>
<jsp:setProperty property="empId" name="emp" value="102"/>
<jsp:setProperty property="empName" name="emp" value="Uday"/>
<jsp:setProperty property="empSal" name="emp" value="198.87"/>
<jsp:forward page="Two.jsp"/>
</body></html>
Two.jsp:--
</head><body>
Data from One jsp is :
<jsp:useBean id="emp" class ="com.app.Employee" scope="request"/>
<jsp:getProperty property="empId" name="emp"/>
<jsp:getProperty property="empName" name="emp"/>
<jsp:getProperty property="empSal" name="emp"/>
</body></html>
4>CUSTOM TAG:--
TAG:--A Tag is component (code) written in HTML, XML, XHTML,… (UI Technology)
which will do some task (Execute one work).
Types of Tags:--
Tags are defined as 2 types.
a>Pre-Defined Tags
203 | P a g e
Adv. Java by Mr. RAGHU
b>Custom Tags**
a.>Pre-Defined Tags:-- A tag already created by language which executes one work.
Ex:-- HTML Tags, JSP Tags, JSF Tags…
Pre –Defined tags in HTML:
Tag <b> = It makes text bold in HTML.
Tag <u> = It makes text underline in HTML.
b.>Custom Tags***:-- A Tag defined by programmer to execute one task is known as
Custom tag.
Coding Steps:--
#1>To write tag handler class provide one public class and extends SimpleTagSupport
class which is given in package: javax.servlet.jsp.target
=>Also override methods doTag() {….} and define logic inside this method.
204 | P a g e
Adv. Java by Mr. RAGHU
<taglib>
<tlib-version>1.3</tlib-version>
<jsp-version>2.1</jsp-version>
<short-name>………..</short-name>
<uri>……………..</uri>
<tag>
<name> TAG NAME </name>
<tag-class> FULLY CLASS NAME </tag-class>
<body-content> empty/scriptless/jsp </body-content>
<attribute>
<name>attribute name</name>
<required>true/false</required>
</attribute>
</tag>
</taglib>
Here, define one tag with any name which print message on JSP Page (in browser at
runtime).
Step#1:-- Create one Dynamic web project (web.xml is optional).
Step#2:-- Write one public class with any name and extends SimpleTagSupport also
override doTag(){…} and define logic there.
Folder Structure:--
Code: AddressTag.java:--
package com.app.tag;
import java.io.IOException;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
206 | P a g e
Adv. Java by Mr. RAGHU
<tag>
<name>nareshitAddr</name>
<tag-class>com.app.tag.AddressTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
#3 Import tag into JSP using <%@taglib %> and use tag in JSP.
Code:-Index.jsp:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="my" uri="http://nareshittech.com/mytag-add"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
207 | P a g e
Adv. Java by Mr. RAGHU
208 | P a g e
Adv. Java by Mr. RAGHU
out.print("<font colour=\"red\">");
out.print("<b>Nareshit Technology<b>");
out.print("</front>");
//to Store body data
StringWriter str = new StringWriter();
//read tag body and load to str Object
getJspBody().invoke(str);
out.print("</marquee>");
} }
Step#2:-- Copy above tld file and modify body-content from “empty” to scriptless” like
(in sample.tld)
<body-content>scriptless</body-content>
<tag>
<name>nareshitAddr</name>
<tag-class>com.app.tag.AddressTag</tag-class>
<body-content>scriptless</body-content>
</tag></taglib>
</body>
</html>
=>Run in server and Enter URL: http://localhost:3033/CustomTagWithBody13/Index.jsp
Flow Design:--
=>Attributes can be created and used in any order. Order is not followed.
210 | P a g e
Adv. Java by Mr. RAGHU
=>For every attribute write one variable in Tag handler class and provide set/get
methods.
211 | P a g e
Adv. Java by Mr. RAGHU
<short-name>Hello Tag</short-name>
<uri>http://nareshittech.com/mytag</uri>
<tag>
<name>nareshit</name>
<tag-class>com.app.tag.AddressTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>contact<name>
<required>true</required>
</attribute>
<attribute>
<name>branch<name>
<required>false</required>
</attribute>
</tag></taglib>
Tags Descriptions
1>c:out 1>It prints given expression on browser, It is similar to <%= ….%>
Expression tag.
2>c:set 2>It creates variable in given ‘scope’ Default is page.
3>c:remove 3>It delete variable from a particular scope.
4>c:if 4>To Write if condition statement
5>c:choose
6>c:when 5-7>It is like switch case
7>c:otherwise
8>c:forEach 8>It is like for each loop
9>c:forTokens 9>It works on String over given delimiter
10>c:param 10>It creates a parameter for URL.
11>c:redirect 11>It redirects to a new URL.
12>c:url 12>It creates a new URL.
13>c:import 13>It imports HTML content into current JSP
14>c:catch 14>It is used to store exception.
214 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
3>Looping statements in Core JSTL use forEach or forTokens to execute code in loop.
=>forEach behaves like for loop and also forEach over collection.
216 | P a g e
Adv. Java by Mr. RAGHU
=>forTokens makes one string into multiple parts based on delimiter ex:- space or ,
3>LoopingStatement.jsp (under WebContent):--
<%@page import="java.util.Arrays"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body><pre>
<c:set var="max" value="10"/>
<c:forEach begin="1" end="${max}" var="i"><c:out value="${i} Hello"/>
</c:forEach>
<% List<String> a1= Arrays.asList("A","B","C");
request.setAttribute("list", a1);%>
<c:forEach items="${list}" var="ob">
<c:out value="${ob}"/>
</c:forEach>
<c:set var="str" value="Hello I am Uday Kumar"/>
<c:forTokens items ="${str}" delims=" " var="s">
<c:out value="${s}"/><br/>
</c:forTokens>
</pre></body></html>
</head>
<body><pre>
<c:url var="search" value="https://www.google.com/search">
<c:param name="q" value="Hyderabad"/>
</c:url>
<c:redirect url="${search}"/>
</pre></body></html>
=>Run on Server and Enter URL: http://localhost:3033/JstlCoreTag/RedirectUrl.jsp
218 | P a g e
Adv. Java by Mr. RAGHU
int a=5/0;
%>
</c:catch>
<c:out value="${ae}"/>
</pre>
</body></html>
2>SQL Tags:-- These are used to perform SQL operation like select and non-select
(insert, update, delete).
=>Prefix used is ‘sql’.
Tags Descriptions
1>sql : setDataSource =>Use it for creating connection with DB.
2>sql:query =>Use for select operation.
3>sql:update =>Use for non-select operation.
4>sql:param =>Use this to pass parameter to SQL.
5>sql:transaction =>Use this to execute multiple non-select operations.
219 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
Data is
<c:forEach items="${rs.rows}" var="std">
Student ID : <c:out value="${std.sid}"/>
220 | P a g e
Adv. Java by Mr. RAGHU
3>formatting Tags:--
These are used to format number or data input in JSP page. i.e Change pattern of data
and data type of double/int.
Tags Descriptions
1>fmt:parseNumber =>It is used to Parse the string to double or number.
2>fmt:formatNumber =>It is used to format the numerical value with specific
format or precision.
3>fmt:formatData =>It formats the time date using the pattern and styles.
Folder Structure:--
${s}
<fmt:formatDate value="${s}"/>
<fmt:formatDate value="${s}" type="date"/>
<fmt:formatDate value="${s}" type="time"/>
<fmt:formatDate value="${s}" type="both"/>
<fmt:formatDate value="${s}" type="both" dateStyle="short"/>
<fmt:formatDate value="${s}" type="both" dateStyle="medium"/>
<fmt:formatDate value="${s}" type="both" dateStyle="long"/>
</pre></body></html>
=>Run on Server and Enter URL: http://localhost:3033/FormatingTags/Date.jsp
4>Function Tags:--These tags are used to perform String operation over given input
String data or any variable.
Tags Description
1>fn:contains() =>Given input string containing the specified substring.
2>fn:containsIgnoreCase() =>Given input string containing the specified substring.
3>fn:endsWith() =>given input string ends with the specified suffix or not?
4>fn:escapeXml() =>show XML tags as it is in.
5>fn:indexOf() =>Find index of a sub-string.
6>fn:trim() =>Removes the blank spaces from both the ends.
7>fn:startsWith() =>Used for check, given string is started with format or
substring.
8>fn:split() =>splits the string into an array of substrings.
9>fn:toLowerCase() =>converts all chars to lower case.
10>fn:toUpperCase() =>converts all chars to Upper case.
11>fn:substring() =>Find subset of a string.
12>fn:substringAfter() =>Find subset of string after specific substring.
13> fn:substringBefore() =>Find subset of string before specific substring.
14>fn:length() =>Find length of String.
15>fn:replace() =>Replace all the occurrence of a String with another
String.
224 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
<c:if test="${fn:contains(str,'Nareshit')}">
Hello Nareshit Tech#1
</c:if>
<c:if test="${fn:containsIgnoreCase(str,'nareshit')}">
Hello Nareshit Tech#2
</c:if>
<c:if test="${fn:startsWith(str,'Hel')}">
Hello Nareshit Tech#3
</c:if>
<c:if test="${fn:endsWith(str,'ies')}"> Hello Nareshit Tech#4 </c:if>
225 | P a g e
Adv. Java by Mr. RAGHU
Index : ${fn:indexOf(str,'from') }
<c:set var="str2" value=" Hello RAM "/>
LEN : ${fn:length(str2) }
<c:set var="str3" value="${fn:trim(str2) }"/>
LEN : ${fn:length(str3) }
LOWER : ${fn:toLowerCase(str3) }
UPPER : ${fn:toUpperCase(str3) }
REPLACE : ${fn:replace(str3,'Hello','hi') }
226 | P a g e
Adv. Java by Mr. RAGHU
${fn:escapeXml(s3)}
</pre>
</body>
</html>
XML Tags:-- These are used to read(parse) data from XML Content given in JSP file.
227 | P a g e
Adv. Java by Mr. RAGHU
Folder Structure:--
228 | P a g e
Adv. Java by Mr. RAGHU
<empSal>333464.78</empSal>
</emp>
</employee>
</c:set>
EMAIL : javabyraghu@gmail.com
FB: https://www.facebook.com/groups/thejavatemple/
229 | P a g e