ADV-JAVA by Ramchandra New (Update1)
ADV-JAVA by Ramchandra New (Update1)
ADV-JAVA by Ramchandra New (Update1)
JSE Module:
Or
It is installable software.
A. Major Version.
B. Minor Version.
A. Standalone Applications.
B. Gamming Applications.
C. Networking Applications.
D. Applet programs.
E. File Interaction applications.
F. Database interaction applications.
Standalone Applications:
CUI Applications:
These applications not provide any look and feel to end users.
GUI Applications:
A. Platform Independent:
Developing one application under one operating system
and compile in the same os and executing under different
operating systems.
A. Language:
B. Technology:
Java is a technology, it will provide specifications.
Specification means set of rules and guide lines.
If the rules and guide lines are open source then competition will be
increases, then we will get best software product.
C. Platform:
Java has its own platform[environment/provides
sufficient memory locations] to execute the programs in
the form JVM.
JEE Module:
Web Applications:
It is one web program which will get the request from the end
user and provides appropriate response to end user (client).
Thin Client:
Ex:
First client must be gets the details about server application from
repository.
If any application wants to provides services to client, that
application details must be placed into repository.
Once getting the details from the repository, then client interact
with server for appropriate services.
These applications we can also called Fat Client and Fat Server
Architecture.
Enterprise Applications:
Diagram:
JME Module:
Types of Projects:
Maintenance Projects:
Migration Projects:
Ex:
Types of API:
Pre-Define API:
User-Define API:
1) Temporary Settings.
2) Permanent Settings.
Temporary Settings:
With the help of above settings our command prompt recognizes the
binary files. (javac, java, javap command).
With the help of above settings our compiler and JVM can recognize
the predefine .class files.
Permanent Settings:
.jsp file
.html files
.jpeg files
.xml files
.properties files
.jsp
.html
.jpeg
.xml files
.properties files
public class A{
System.out.println("jar file");
javac A.java
Set the one.jar file in the class path then execute the program
java A
JVM ARCHITECTURE:
Virtual Machine:
1) Client JVM
2) Server JVM.
Java is internally communicate the with JVM, then JVM will come
into the picture, first JVM will read class name and JVM control will
go to secondary memory, that class byte code will be loaded from
secondary memory to primary memory.
1) Loading phase.
2) Linking phase.
3) Initialization phase.
Loading Phase:
In this phase the byte code (predefine and user define class) will be
loaded from secondary memory to primary with the help of bellow
classloaders.
1. ApplicationClassLoaderSubSystem
2. ExtensiveClassLoaderSubSystem
3. BootstrapClassLoaderSubSystem.
ApplicationClassLoaderSubSystem:
It will loads user define class files from current directly and
environment variable path.
ExtensiveClassLoaderSubSystem:
BootstrapClassLoaderSubSystem:
Linking:
1. Verifier
2. Preparer
3. Resolver.
1) Method Area
2) Heap Area
Method Area: In this area all class data is stored. that means all the
static data is available in the method area.
Heap Area: in this area all object data is stored. that means all the
non-static data is available in heap area.
2) Operand Stack:
3) Frame Data:
PC Registers:
If java wants communicate with c and c++ code, that code will
be available in Native method area.
If we interact with c and c++ code, we need libraries, those
will be given by Native Library, that library will be handover by
Native Method Interface to executable engine.
Execution Engine:
1. Interpreter
2. JIT Compiler
First profiler will identify the weather statements are single time or
looping statements.
Reflection API:
With the help of reflection API we can access both private and public
data.
1)Filed
2)Constructor
3)Method
4)Modifer
If want convert from int to string then Modifier class itself provides
some predefine method (toString()).
ABSTRACT 1024
FINAL 16
INTERFACE 512
NATIVE 256
PRIVATE 2
PROTECTED 4
PUBLIC 1
STATIC 8
STRICT 2048
SYNCHRONIZED 32
TRANSIENT 128
VOLATILE 64
1)getDeclaredFields()
2)getFields()
3)getDeclaredMethods()
4)getMethods()
5)getDeclaredConstructors()
6)getConstructors()
forName():
This method has been throwing one compile time exception i.e
Java.lang.ClassNotFoundException.
newInstance():
This is one instance factory methods, which is used to create object
with the help of class reference variable.
1) IllegalAccessException
2) InstantiationException
import java.io.FileNotFoundException;
import java.io.IOException;
public class A {
A(int x){
System.out.println("hi");
***********************************
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
for(Field f1:f){
if(modi.contains("private")){
System.out.println(f1);
f1.setAccessible(true);
System.out.println(f1.get(obj));
System.out.println(f1);
System.out.println("*****************");
Constructor[] c = cls.getDeclaredConstructors();
for(Constructor c1:c){
System.out.println(c1);
System.out.println("*****************");
Method[] m = cls.getDeclaredMethods();
for(Method a:m){
System.out.println(a);
System.out.println("*************");
Class[] e = a.getExceptionTypes();
for(Class e1:e){
System.out.println(e1);
}
Block:
Automatically executing.
Method:
a. Presentation Logic.
b. Business Logic.
c. Persistence logic.
Presentation Logic:
The logic, which is used to developing GUI for reading the data from
end user and providing response or output to end user, is called
Persistence logic.
Business Logic:
Persistence Logic:
JDBC
Whenever the java application in running mode, we can access the
different type of data in different memory areas of JVM.
For example static data, non-static or instance data and objects and
local data are available in method area, heap area and java stack
area respectively.
Once the java program execution completed all the data which is
available in different memory location will be destroy.
Introduction to JDBC:
It is a Trademark.
We don’t have any official name like Java Data Base Connectivity.
Persistence Store:
Persistence:
Persistence Logic:
Persistence Operations:
What is JDBC?
JDBC is a standard.
JDBC is a technology.
With the help of JDBC we can store and retrieving the data from
RDBMS.
Ex: oracle.jdbc.driver.OracleDriver
Ex: jdbc:oracle:thin:@localhost:1521:XE
Data Base Username will provide data base username for provides
security.
Data Base Password will provide data base password for provides
security.
1. JDBC API.
2. Driver software API. (JDBC Technology Based Software).
Driver API is used to call actual logic. This logic is different from one
database to other.
JDBC API is coming to our machine in the form of rt.jar file which is
located in our java software installation directory. That is
java\jre\lib\rt.jar file.
Ojdbc jar file is available in our data base installation directory that
is
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.ja
r
ODBC:
If the bug or error are raises in the native methods, there may be
chance of destroy the JVM.
To overcome this problem Java community people introduce one
technology or specification in the form of JDBC.
JDBC API is used for accessing the JDBC Driver software, which can
be drive (carry) our queries to data base and execute them in the
data base server and finally that outputs will be carry to end user or
java application, for this we need to establish the SESSION.
if(con !=null){
System.out.println("connection established");
}
else
System.out.println("not established");
}
import java.util.Scanner;
interface Animal{
void eat();
void sleep();
}
class AnimalFactory{
static Animal factoryAnimal(String animalName){
if(animalName.equalsIgnoreCase("lion")){
return new Lion();
}else if(animalName.equalsIgnoreCase("rabit")){
return new Rabit();
}return null;
}
}
class Lion implements Animal{
@Override
public void eat() {
System.out.println("eats non-veg");
}
@Override
public void sleep() {
System.out.println("sleeping in caves");
}
}
class Rabit implements Animal{
@Override
public void eat() {
System.out.println("eats veg");
}
@Override
public void sleep() {
System.out.println("sleeping in bushes");
}
}
class Tiger implements Animal{
@Override
public void eat() {
System.out.println("tiger eats non-veg");
}
@Override
public void sleep() {
System.out.println("tiger sleeping in caves");
}
}
public class FactoryMethod {
public static void main(String[] args) {
System.out.println("enter which animal object you
want");
Scanner scan = new Scanner(System.in);
String animalName = scan.next();
Animal obj = AnimalFactory.factoryAnimal(animalName);
//Animal obj = new Lion();
obj.eat();
obj.sleep();
}
}
interface Animal{
void eat();
void sleep();
class AnimalFactory{
InstantiationException, IllegalAccessException{
/*if(animalName.equalsIgnoreCase("lion")){
}else if(animalName.equalsIgnoreCase("rabit")){
}return null;*/
return (Animal)obj;
@Override
System.out.println("eats non-veg");
@Override
System.out.println("sleeping in caves");
}
@Override
System.out.println("eats veg");
@Override
System.out.println("sleeping in bushes");
@Override
@Override
Animal obj =
AnimalFactory.factoryAnimal(animalName);
obj.eat();
obj.sleep();
The Same factory method approach we can use for Driver software
loading process.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import oracle.jdbc.driver.OracleDriver;
if(con != null){
System.out.println("connection is
established");
System.out.println("connection object: "+con);
}
else
System.out.println("connection is not
established");
}
DriverManager.getConnection(-,-,-) will create object for
implementation class (T4CConection) of Connection and placed
object into Connection reference.
C:\oraclexe\app\oracle\product\10.2.0\server\NETWORK\ADMIN\
tnsnames file
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.ja
r
1. “jdbc:oracle:thin:@localhost:1521:xe”
2. “jdbc:oracle:thin:@Ramchandar-PC:1521:xe”
3. “jdbc:oracle:thin:@ipaddress:1521:xe”
Approach-2:
if(con != null){
System.out.println("connection is established");
System.out.println("con: "+con);
}
else
System.out.println("connection is not established");
Approach:3:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import oracle.jdbc.driver.OracleDriver;
class Demo extends OracleDriver{
Connection connection() throws SQLException{
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@lenovo-PC:1521:xe",
"system",
"manager");
return con;
}
}
public class JdbcDemoProgram2 {
public static void main(String[] args) throws SQLException{
Demo d = new Demo();
Connection con = d.connection();
if(con != null){
System.out.println("con: "+con);
System.out.println("connection established");
}
else
System.out.println("connection not established");
}
}
Approach:4:
Class.forName("oracle.jdbc.driver.OracleDriver");//fully
qualified name mandatory
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@lenovo-
PC:1521:xe","system","manager");
if(con != null){
System.out.println("connection is established");
System.out.println("con: "+con);
}
else
System.out.println("connection is not established");
Approach:5:
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@lenovo-
PC:1521:xe","system","manager");
if(con != null){
System.out.println("connection is established");
System.out.println("con: "+con);
}
else
System.out.println("connection is not established");
Appraoch:6:
Properties p = new Properties();
p.put("user","system");
p.put("password", "manager");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@lenovo-
PC:1521:xe", p);
if(con != null){
System.out.println("connection is established");
System.out.println("con: "+con);
}
else
System.out.println("connection is not established");
In the above program p.setProperty(-,-) key value must be
“user”, don’t write key like username or User.
Approach:7:
FileInputStream fis = new FileInputStream("db.properties");
Properties p = new Properties();
p.load(fis);
String driver = p.getProperty("driver");
String url = p.getProperty("url");
String user= p.getProperty("username");
String password = p.getProperty("password");
Class.forName(driver);
Connection con = DriverManager.getConnection(url,user,password);
if(con != null){
System.out.println("connection is established");
System.out.println("con: "+con);
}
else
System.out.println("connection is not established");
like bellow
p.setProperty("user", user);
p.setProperty("password", password);
Class.forName(driver);
Connection con =
DriverManager.getConnection(url,p);
System.out.println(con);
AutoLoading:
ojdbc6.jar\META-INF\services\java.sql.Driver file.
This feature only supported by the one jar file like ojdbc6.jar file.
a. oracle.jdbc.driver.OracleDriver
b. oracle.jdbc.OracleDriver
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@lenovo-
PC:1521:xe","system","manager");
if(con != null){
System.out.println("connection is established");
System.out.println("connection: "+con);
else
}
ResourceBundle:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class FirstJdbcDemo {
public static void main(String[] args)
throws ClassNotFoundException,
SQLException{
ResourceBundle rb =
ResourceBundle.getBundle("oracledb.properties");
String driver = rb.getString("drivername");
String url = rb.getString("urlname");
String user = rb.getString("username");
String password = rb.getString("password");
Class.forName(driver);
Connection con =
DriverManager.getConnection(url,user,password);
System.out.println("con: "+con);
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Class.forName("oracle.jdbc.driver.OracleDrivers");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@lenovo-
PC:1521:xe","system","manager");
if(con != null){
System.out.println("connection is established");
System.out.println("connection: "+con);
else
System.out.println("connection is not established");
Java.lang.ClassNotFoundException.
After that JVM executes static block from OracleDriver class. In this
static block OracleDriver object is created later forward
DriverManager class to register.
DriverManager is not create the connection it is just find out the url
of given driver and handover these details to driver class. Driver
classes itself create object and handover to DriverManager.
DriverManager will find out the suitable driver from registers drivers
by using driver.acceptURL().
ResultSet rs = st.executeQuery(-);
With the help of above line the given query is send and executed at
db side by using appropriate buffer.
If we want read the data from db we need to use rs.next() first, this
will help us to move the cursor from non-record area to record area.
If the record is available that record will given back to java side and
we should read that data by using rs.get() by passing index position
or column name.
Once all records reading finally rs.next() will return false, then our
reading operation will be closed.
Q) How many ways can we read data from ResultSet object?
A) There are two ways to read the data from ResultSet object.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
throws SQLException,ClassNotFoundException{
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"system","annie");
Statement st = con.createStatement();
System.out.println("st: "+st);
ResultSet rs =
System.out.println("rs: "+rs);
System.out.println("SID\tSNAME\tSAGE\tSFEE");
while(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)
+"\t"+rs.getInt(3)+"\t"+rs.getInt(4));
/*System.out.println(rs.getString(1)+"\t"+rs.getInt
(2)+"\t"
+"\t"+rs.getInt(3)+"\t"+rs.getInt(4));*///invalid
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDemo1 {
throws SQLException,ClassNotFoundException{
"jdbc:oracle:thin:@localhost:1521:xe",
"system","annie");
Statement st = con.createStatement();
System.out.println("st: "+st);
ResultSet rs =
System.out.println("rs: "+rs);
System.out.println("SFEE\tSAGE\tSNAME");
while(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getInt(2)+"\t"+rs.getStrin
g(3));
/*System.out.println(rs.getInt(1)+"\t"+rs.getString(2)
+"\t"+rs.getInt(3)+"\t"+rs.getInt(4));*///valid
/
*System.out.println(rs.getInt(1)+"\t"+rs.getInt(2)+"\t"+rs.getStri
ng(3)+"\t"+rs.getInt(4));*/ //invalid
/
*System.out.println(rs.getInt(1)+"\t"+rs.getInt(2)+"\t"+rs.getStri
ng(3)+"\t"+rs.getInt(1));*/ //valid
/*System.out.println(rs.getInt(1)+"\t"+rs.getInt(2)); */
//valid
/*System.out.println(rs.getInt(1)); */ //valid
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
throws SQLException,ClassNotFoundException{
"jdbc:oracle:thin:@localhost:1521:xe",
"system","annie");
Statement st = con.createStatement();
System.out.println("st: "+st);
ResultSet rs =
System.out.println("rs: "+rs);
System.out.println("SFEE\tSAGE\tSNAME");
while(rs.next()) {
/*System.out.println(rs.getInt("sfee")+"\t"
+rs.getInt("sage")+"\t"
+rs.getString("sname"));*/
/*System.out.println(rs.getInt("sfee")+"\t"
+rs.getInt("sage")+"\t"
+rs.getString("sname")+rs.getInt("sid"));*/
/*System.out.println(rs.getInt("sfee")+"\t"
+rs.getInt("sage")+"\t"
+rs.getString("sname")+rs.getInt(4));*/
Like how to use the class, member variables and methods, their
syntax….
API classes and interfaces byte code are using by the compiler and
JVM.
1. File--->new-->others--->java project--->next-->GiveName
for Project-->select jre(java version)-->finish.
--> crate class in our project.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
throws ClassNotFoundException,SQLException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@locahost:1521:xe",
"system","annie");
System.out.println();
run the application: right click on our class --->goto run as -->click
on java application.
exception: java.lang.ClassNotFoundExcepiton
to over come the above problem we need add ojdbc6.jar file to
ecliipse.
--->click on libraries
ResultSetMetaData:
It is a JDBC object.
In the above RSMD will give only eno, ename column information.
ResultSet is mainly design for reading the data from the row actual
data whereas RSMD will provide column information, which is quires
from RS.
ResultSet contains some methods to read and move the cursor from
one row to another row.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo1 {
public static void main(String[] args) throws
SQLException, ClassNotFoundException{
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@lenovo-
PC:1521:xe","system","manager");
if(con != null){
System.out.println("connection is established");
System.out.println("connection: "+con);
}
else
System.out.println("connection is not established");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from emp");
System.out.println("rs: "+rs);
st.executeQuery("select * from emp");
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("Number of Columns:
"+rsmd.getColumnCount());
System.out.println("Name of the Column :
"+rsmd.getColumnName(1));
System.out.println("Type of the Column :
"+rsmd.getColumnTypeName(1));
System.out.println("precision of Column:
"+rsmd.getPrecision(4));
System.out.println("scale of the Column:
"+rsmd.getScale(4));
System.out.println("constraint of
Column:"+rsmd.isNullable(1));
Desc command is not a sql command, it is design for sql prompt for
windows os.
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import com.myfactoy.ConnectionFactory;
Connection con =
ConnectionFactory.getMyConnection();
System.out.println("con: "+con);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select
sname,sid,sfee,sage from sbaj2to4");
System.out.println(rsmd.getColumnCount());
System.out.println(rsmd.getColumnType(1));
System.out.println(rsmd.getColumnTypeName(1));
System.out.println(rsmd.getColumnLabel(1));
System.out.println(rsmd.getPrecision(1));
System.out.println(rsmd.getScale(1));
System.out.println(rsmd.getColumnClassName(1));
System.out.println(rsmd.isNullable(1));
}
}
ParameterMetadata:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
DriverManager.getConnection("jdbc:oracle:thin:@localhost
:1521:xe",
"system","manager");
System.out.println("con: "+con);
PreparedStatement ps =
con.prepareStatement("insert into values
sbaj4to6(?,?,?)");
ParameterMetaData pmd =
ps.getParameterMetaData();
System.out.println(pmd.getParameterCount());
//System.out.println(pmd.getParameterMode(1))
;
//System.out.println(pmd.getPrecision(1));
//System.out.println(pmd.getScale(1));
}
}
Examples on Commands:
Select (DQL)
Non-select
Updatable (DML)
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
throws ClassNotFoundException,SQLException{
Class.forName("oracle.jdbc.driver.OracleDriver");
"jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement st = con.createStatement();
System.out.println("count: "+count);
con.close();
Statement Interface:
Special Case:
a. getResultSet().
b. getUpdateCount().
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
if(b){
ResultSet rs = st.getResultSet();
System.out.println("^^^^^^^");
while(rs.next()){
System.out.println(rs.getInt(1)+"..."+rs.getString(2));
}
}
else{
int updateCount = st.getUpdateCount();
System.out.println("updateCount: "+updateCount);
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
if(b){
ResultSet rs = st.getResultSet();
System.out.println("^^^^^^^");
while(rs.next()){
System.out.println(rs.getInt(1)+"..."+rs.getString(2));
}
}
else{
int updateCount = st.getUpdateCount();
System.out.println("updateCount: "+updateCount);
}
}
Execute() can run all type of queries. But we need to write more line
of code to view the records.
To run query and get the result within the single line we can go for
two more methods.
executeQuery()
executeUpdate()
System.out.println(rs.getInt(1)+"..."+rs.getString(2)+"...."+rs.getI
nt(3));
}
In which order using these method in that order only data will be
stored in Statement object.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
}
If we execute above program multiple times, the same data will be
inserting into emps table.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
Connection con;
try {
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"system","annie");
System.out.println("cnon: "+con);
Statement st = con.createStatement();
System.out.println("count: "+count);
catch (SQLIntegrityConstraintViolationException e) {
}
catch (SQLException e) {
e.printStackTrace();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLSyntaxErrorException;
import java.sql.Statement;
import java.util.Scanner;
Connection con;
try {
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"system","annie");
System.out.println("cnon: "+con);
Statement st = con.createStatement();
+","+sfee+")");
System.out.println("count: "+count);
catch (SQLIntegrityConstraintViolationException e) {
catch(SQLSyntaxErrorException e) {
catch (SQLException e) {
e.printStackTrace();
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcProgram5 {
public static void main(String[] args)
throws ClassNotFoundException, SQLException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"system",
"manager");
if(con!=null){
System.out.println("con: "+con.hashCode());
System.out.println("connection established");
}
else
System.out.println("connection not established");
Statement st = con.createStatement();
String query = "create table sbajram (eid number(5),ename
varchar2(20),esal number(10))";
int count = st.executeUpdate(query);
System.out.println("count: "+count);
}
}
In the above program executeUpdate() will return value like
zero(0).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcProgram5 {
public static void main(String[] args)
throws ClassNotFoundException, SQLException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"system",
"manager");
if(con!=null){
System.out.println("con: "+con.hashCode());
System.out.println("connection established");
}
else
System.out.println("connection not established");
Statement st = con.createStatement();
String query = "alter table sbaj add institute varchar2(20)";
int count = st.executeUpdate(query);
System.out.println("count: "+count);
}
}
Based on the values we are placing in query, queries are divided into
three types.
a. IN Input
b. Out Output
c. INOUT Both Input and Output.
We must set values for place holders (?) at run time meanwhile of
query execution.
In the above insert query first ‘?’ index is 1 and second ‘?’ index is 2.
Statement is one java object, which is used to send and execute the
query sql and pl/sql queries.
1. Statement.
2. PreparedStatement.
3. CallableStatement
So we need create the build plan only one and reuse it then we
should go for concept like PreparedStatement interface.
package jdbc.aj.ram;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
}
}
}
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.DriverManager;
public class FirstJdbcProg {
public static void main(String[] args) throws Exception{
System.out.println("=============");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system", "manager");
System.out.println("con: "+con);
Statement st = con.createStatement();
System.out.println("st: "+st);
PreparedStatement ps = con.prepareStatement("insert into
sbajemp(?,?,?,?)");
System.out.println("ps: "+ps);
}
}
PreparedStatement:
Those are
package jdbc.aj.ram;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)
+"\t"+rs.getInt(3));
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
int x = ps.executeUpdate();
System.out.println("x: "+x);
ps.setInt(1, 105);
ps.setString(2, "mahesh");
int y = ps.executeUpdate();
System.out.println("x: "+y);
}
}
Note: To execute the query one time better prefer Statement object.
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class JdbcDemo {
public static void main(String[] args)
throws SQLException{
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system
","manager");
System.out.println("con: "+con);
System.out.println("select your operation");
System.out.println("1.INSERT\t2.DELETE");
System.out.println("3.TRUNCATE\t4.UPDATE");
System.out.println("5.SELECT");
Scanner scan = new Scanner(System.in);
int operation = scan.nextInt();
switch(operation){
case 1: System.out.println("YOUR ARE SELECTING INSERT
OPERATION");
PreparedStatement ps1 = con.prepareStatement("insert into
sbaj2_4 values(?,?,?,?)");
System.out.println("enter student id");
int sid = scan.nextInt();
System.out.println("enter studnet name");
String sname = scan.next();
System.out.println("enter studnet fee");
int sfee = scan.nextInt();
System.out.println("enter studnet age");
int sage = scan.nextInt();
ps1.setInt(1, sid);
ps1.setString(2, sname);
ps1.setInt(3, sfee);
ps1.setInt(4, sage);
int count1 = ps1.executeUpdate();
System.out.println("recored inserted
successfully: "+count1);
break;
case 2: System.out.println("YOU ARE SELECTING DELETE
OPERATION");
PreparedStatement ps2 = con.prepareStatement("delete from
sbaj2_4 where sno=?");
System.out.println("enter studnet number");
int sid1 = scan.nextInt();
ps2.setInt(1, sid1);
int count2 = ps2.executeUpdate();
System.out.println("recored deleted:
"+count2);
break;
case 3: System.out.println("YOU ARE SELECTING
TRUNCATE OPERATION");
PreparedStatement ps3 =
con.prepareStatement("truncate table sbaj2_4");
int count3 = ps3.executeUpdate();
System.out.println("all records are delected:
"+count3);
break;
case 4: System.out.println("YOU ARE SELECTING UPDATE
OPERATION");
PreparedStatement ps4 =
con.prepareStatement("update sbaj2_4 set sname=? where
sno=?");
System.out.println("enter studnet name for
updation");
String sname1 = scan.next();
System.out.println("enter studnet number");
int sid2 = scan.nextInt();
ps4.setString(1, sname1);
ps4.setInt(2, sid2);
int count4 = ps4.executeUpdate();
System.out.println("records are updated:
"+count4);
break;
case 5: System.out.println("YOU ARE SELECTING
SELECT OPERATION");
PreparedStatement ps5 = con.prepareStatement("select *
from sbaj2_4");
ResultSet rs = ps5.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getIn
t(3)
+"\t"+rs.getInt(4));
}
}
}
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class JdbcDemo {
public static void main(String[] args)
throws SQLException{
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","s
ystem","manager");
System.out.println("con: "+con);
String query = "update sbaj2_4 set sfee=? where
sno=?";
PreparedStatement ps=
con.prepareStatement(query);
Scanner scan = new Scanner(System.in);
System.out.println("Enter Student fee");
int sfee = scan.nextInt();
System.out.println("Enter Student number");
int sno = scan.nextInt();
ps.setInt(1, sfee);
ps.setInt(2, sno);
int count = ps.executeUpdate();
System.out.println("count: "+count);
}
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class JdbcDemo {
public static void main(String[] args)
throws SQLException{
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","manager
");
System.out.println("con: "+con);
Scanner scan = new Scanner
(System.in);
System.out.println("do you want do the
System.out.println("select your
operation");
System.out.println("1.INSERT
\t2.DELETE");
System.out.println("3.TRUNCATE
\t4.UPDATE");
System.out.println("5.SELECT");
int operation = scan.nextInt();
switch(operation){
case 1: System.out.println("YOUR ARE
values(?,?,?,?)");
System.out.println("enter
student id");
int sid = scan.nextInt();
System.out.println("enter
studnet name");
String sname = scan.next();
System.out.println("enter
studnet fee");
int sfee = scan.nextInt();
System.out.println("enter
studnet age");
int sage = scan.nextInt();
ps1.setInt(1, sid);
ps1.setString(2, sname);
ps1.setInt(3, sfee);
ps1.setInt(4, sage);
int count1 =
ps1.executeUpdate();
System.out.println("recored
DELETE OPERATION");
PreparedStatement ps2 = con.prepareStatement("delete
from sbaj2_4
where sno=?");
System.out.println("enter
studnet number");
int sid1 = scan.nextInt();
ps2.setInt(1, sid1);
int count2 =
ps2.executeUpdate();
System.out.println("recored
deleted: "+count2);
break;
case 3: System.out.println("YOU ARE SELECTING
TRUNCATE OPERATION");
PreparedStatement ps3 = con.prepareStatement
ps3.executeUpdate();
System.out.println("all
UPDATE OPERATION");
PreparedStatement ps4 =
con.prepareStatement("update sbaj2_4 set sname=?
where
sno=?");
System.out.println("enter
studnet number");
int sid2 = scan.nextInt();
ps4.setString(1, sname1);
ps4.setInt(2, sid2);
int count4 =
ps4.executeUpdate();
System.out.println("records
(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3)
+"\t"+rs.getInt(4));
}//while
}//switch
System.out.println("do you want continue if no
type no");
flag = scan.next();
}//while
}
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcDemo {
public static void main(String[] args)
throws ClassNotFoundException,SQLException{
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
System.out.println("con: "+con);
/* //program-1
Statement st = con.createStatement();
int count = st.executeUpdate(
"insert into sbaj6to8
values(111,'vikram',9000,40)");
System.out.println(count+" records inserted");
int count1 = st.executeUpdate("delete from
sbaj6to8 where deptno=20");
System.out.println(count1+" records deleted");
ResultSet rs = st.executeQuery("select * from
sbaj6to8");
System.out.println("ENO\t\tENAME\t\tESAL\t\tDEPTNO")
;
while(rs.next()){
System.out.println(rs.getInt(1)+"\t\t"+rs.getString(2)
+"\t\t"+rs.getInt(3)+"\t\t"+rs.getInt(4));
}
con.close();
*/
PreparedStatement ps =
con.prepareStatement("select * from sbaj6to8");
ResultSet rs = ps.executeQuery();
System.out.println("ENO\t\tENAME\t\tESAL\t\tDEPTNO")
;
while(rs.next()){
System.out.println(rs.getInt(1)+"\t\t"+rs.getString(2)
+"\t\t"+rs.getInt(3)+"\t\t"+rs.getInt(4));
}
PreparedStatement ps1 =
con.prepareStatement("delete from sbaj6to8 where
deptno=10");
int count = ps1.executeUpdate();
System.out.println(count+". recoreds are
deleted");
con.close();
}
}
Withthe help of single Statement object we can exeuctes
single(same) query multiple times and different types of queries.
With the help of single PreparedStatement object we can execute
same query multiple times but not different type of queries.
CallableStatement:
StoredProcedure is reusable.
is
variable declarations;
begin
end;
Is
Variable declaration
Begin
logic
Return <result>;
End;
Types of Parameters:
To send input and to read output from stored procedure, every db
will support three types of parameters.
1. IN
2. OUT
3. INOUT
Eno IN Number,
“{?:=cal functionname(?)}”
CallableStatement object we can create by using following method.
That is prepareCall(String call);
is
oldsal empram.sal%type;
begin
commit;
end;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
cs.registerOutParameter(3,Types.VARCHAR);
cs.registerOutParameter(4,Types.NUMERIC);
cs.registerOutParameter(5,Types.VARCHAR);
cs.setInt(1,eno);
cs.setInt(2, incrsal);
cs.execute();
//Reading process should depends on placehold out
parameters
//type but not depends on column index
in table
String ename = cs.getString(3);
int sal = cs.getInt(4);
String dept = cs.getString(5);
System.out.println(ename+"..."+sal+"..."+dept);
cs.close();
con.close();
}
}
/*ResultSet rs = cs.executeQuery();
System.out.println("rs: "+rs);
rs.next();
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getInt(3));
System.out.println(rs.getString(4));
*/
int empnumber = cs.getInt(3);
String empName = cs.getString(4);
int empSal = cs.getInt(5);
String empDept = cs.getString(6);
System.out.println(empnumber+".."+empName+"..."+empSal+"..."
+empDept);
}
}
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Scanner;
import jdbc.aj.ram.ConnectionFactory;
public class JdbcProgram11 {
public static void main(String[] args)
throws SQLException{
Connection con = ConnectionFactory.getConnect();
System.out.println("con: "+con);
CallableStatement cs = con.prepareCall("select * from
empram");
ResultSet rs = cs.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+".."+rs.getString(2)+".."+
rs.getInt(3)+"..."+rs.getString(4));
}
}
}
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Scanner;
import jdbc.aj.ram.ConnectionFactory;
public class JdbcProgram11 {
public static void main(String[] args)
throws SQLException{
Connection con = ConnectionFactory.getConnect();
System.out.println("con: "+con);
CallableStatement cs = con.prepareCall("insert into
empram values(?,?,?,?)");
Scanner scan = new Scanner(System.in);
System.out.println("enter employee number");
int eno = scan.nextInt();
System.out.println("enter employee name");
String ename = scan.next();
System.out.println("enter employee sal");
int esal = scan.nextInt();
System.out.println("enter employee dept");
String edept = scan.next();
cs.setInt(1, eno);
cs.setString(2, ename);
cs.setInt(3, esal);
cs.setString(4,edept);
int count = cs.executeUpdate();
System.out.println("count: "+count);
}
}
begin
return amount;
end;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
}
If given employee id not available while interacting with table
trhough function then we will get exception.
Transaction Management:
They are:
By default all new connections are opened in auto commit mode true
only.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
con.setAutoCommit(false);
Statement st = con.createStatement();
st.execute("insert into emps
values(110,'a',4444)");
st.execute("update emps set eid=301 where
ename='kam'");
st.execute("delete from emps where eid=444");
con.commit();
System.out.println("****************8");
}catch(SQLException e){
System.out.println("some problem");
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
Statement st = con.createStatement();
st.execute("insert into emps
values(110,'a',4444)");
st.execute("update emps set eid=301 where
ename='kam'");
st.execute("delete from emps where eid=444");
}
}
In the above program records directly committed into main table the
reason the setAutoCommit(true) by default.
QueryDemo.java
package com.ram.query;
JdbcDemo.java
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.ram.query.QueryDemo;
public class JdbcDemo {
public static void main(String[] args){
Connection con = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:152
1:xe",
"system",
"manager");
con.setAutoCommit(false);
Statement st = con.createStatement();
st.executeUpdate(QueryDemo.QUERY1);
System.out.println("programmer go and
check ur db console");
Thread.sleep(10000);
st.executeUpdate(QueryDemo.QUERY2);
System.out.println("programmer go and
check ur db console");
Thread.sleep(10000);
st.executeUpdate(QueryDemo.QUERY3);
System.out.println("programmer go and
check ur db console");
Thread.sleep(10000);
con.commit();
}catch(Exception e){
System.out.println("catch block");
try {
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.ram.query.QueryDemo;
public class JdbcDemo {
public static void main(String[] args){
Connection con = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:152
1:xe",
"system",
"manager");
con.setAutoCommit(false);
Statement st = con.createStatement();
int count1 = st.executeUpdate(
"insert into sbaj6to8
values(102,'sam',7000,20)");
System.out.println(count1+".record
inserted");
int count2 = st.executeUpdate(
"delete from sbaj6to8 where
eno=103");
System.out.println(count2+".record
deleted");
int count = st.executeUpdate(
"update sbaj6to8 set deptno=20
where eno=105");
System.out.println(count+".records
updated");
if(count == 0){
System.out.println("11111111111");
con.rollback();
}
else{
System.out.println("222222222");
con.commit();
}
}catch(Exception e){
System.out.println("catch block");
try {
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
import java.sql.*;
public class Test{
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
st.executeUpdate(query1);
System.out.println("1st query inserted");
Thread.sleep(20000);
st.executeUpdate(query2);
System.out.println("2nd query inserted");
Thread.sleep(20000);
con.commit();
System.out.println("records are commited");
Thread.sleep(20000);
}catch(Exception e){
System.out.println("problem comes here");
e.printStackTrace();
if(con!=null){
try{
con.rollback();
}catch(Exception e1){
e1.printStackTrace();
}
}
}
}
In the above both query1 and query2 are valid then both the insert
statement will updated to database main table with support of
commit(), otherwise no insert query will be updatable into database
main table.
Program on savePoint():
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
public class TransactionManagementDemo {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("con: "+con);
con.setAutoCommit(false);
Statement st = con.createStatement();
st.executeUpdate(
"insert into sbajemp values (204,'ram4',99991,'hr4')");
st.executeUpdate(
"insert into sbajemp values (205,'ram5',99992,'hr5')");
Savepoint sv = con.setSavepoint();
st.executeUpdate(
"insert into sbajemp values (201,'ram1',99993,'hr1')");
st.executeUpdate(
"insert into sbajemp values (202,'ram2',99994,'hr2')");
st.executeUpdate(
"insert into sbajemp values (203,'ram3',99995,'hr3')");
con.rollback(sv);
con.commit();
}catch(ClassNotFoundException e){
System.out.println("class is not existed");
e.printStackTrace();
}
catch(SQLException e){
System.out.println("problem database connection");
e.printStackTrace();
}
}
}
Batch Updations:
The above method adds given sql command to this Statement object
batch.
The above method is used to handover the all sql commands stored
in statement object batch to the database.
The above method is used to removes all queries from the batch and
make this statement object batch as empty.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
int[] ia = st.executeBatch();
System.out.println(ia[0]+" rows inserted");
System.out.println(ia[1]+" rows updated");
System.out.println(ia[2]+" rows delete");
con.commit();
System.out.println("recoreds commit completed");
}catch(Exception e){
e.printStackTrace();
if(con!=null){
try{
con.rollback();
}catch(Exception e1){
e1.printStackTrace();
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
“system",
"manager");
System.out.println("con: "+con);
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement(
ps.setInt(1, 205);
ps.setString(2, "megha");
ps.setInt(3, 999999);
ps.setString(4,"faculty");
ps.addBatch();
int a[]=ps.executeBatch();
System.out.println(a);
con.commit();
}catch(Exception e){
e.printStackTrace();
if(con!=null){
try {
con.rollback();
e1.printStackTrace();
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Jdbcprogram15 {
public static void main(String[] args){
Connection con=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"system",
"manager");
System.out.println("con: "+con);
con.setAutoCommit(false);
PreparedStatement ps =
con.prepareStatement("insert into empram
values(?,?,?,?)");
Scanner scan = new Scanner(System.in);
for(int i =1; i<=3;i++){
System.out.println("enter employee number");
int eno = scan.nextInt();
System.out.println("enter employee name");
String ename= scan.next();
System.out.println("enter employee salaray");
int esal = scan.nextInt();
System.out.println("enter employee department");
String edept = scan.next();
ps.setInt(1,eno);
ps.setString(2, ename);
ps.setInt(3,esal);
ps.setString(4, edept);
ps.addBatch();
}
int a[]=ps.executeBatch();
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
con.commit();
}catch(Exception e){
System.out.println("controle comes to here");
e.printStackTrace();
if(con!=null){
try {
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
}
import java.sql.*;
import java.util.Scanner;
try{
con =
DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe"
,"system","manager");
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement(
ps.setInt(1, sid);
ps.setString(2, sname);
ps.setInt(3, sage);
ps.setInt(4,sfee);
ps.setString(5, spassword);
ps.addBatch();
ps.setInt(2,sid1);*/
int[] a = ps.executeBatch();
System.out.println(a[0]+".records inserted");
con.commit();
catch(Exception e){
e.printStackTrace();
try {
con.rollback();
e1.printStackTrace();
finally{
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
In the above program we will get exception while adding new query
into preparedstatement object by using addBatch().
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Scanner;
public class Demo1 {
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
public class VideoASInput {
public static void main(String[] args) throws SQLException,
IOException{
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","sys
tem","manager");
System.out.println(con);
Statement st = con.createStatement();
int count = st.executeUpdate("create table video(video blob)");
PreparedStatement ps = con.prepareStatement("insert into video
values(?)");
File f = new File("C:\\Users\\Public\\Videos\\Sample
Videos\\Wildlife.wmv");
FileInputStream fis = new FileInputStream(f);
ByteArrayOutputStream byins = new ByteArrayOutputStream();
while (fis.available()>0) {
byins.write(fis.read());
}
byte[] videobytes = byins.toByteArray();
ps.setBytes(1, videobytes);
int count1=ps.executeUpdate();
System.out.println(count1);
Statement st1 = con.createStatement();
ResultSet rs =st1.executeQuery("select * from video");
while(rs.next())
{
File file1 = new File("E://ram.mp4");
FileOutputStream foStream = new
FileOutputStream(file1);
InputStream is2 = rs.getBinaryStream(1);
int i=0;
while((i=is2.read())!=-1){
foStream.write(i);
}
}
}
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
}catch(Exception e){
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class JdbcDemo {
public static void main(String[] args)
throws ClassNotFoundException,SQLException,
IOException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe
", "system",
"manager");
System.out.println("con: "+con);
PreparedStatement ps =
con.prepareStatement("insert into studentsbaj
values(?,?,?)");
Scanner scan = new Scanner(System.in);
System.out.println("enter student number");
int sid = scan.nextInt();
System.out.println("enter student name");
String sname = scan.next();
System.out.println("enter student image
path");
String sphoto = scan.next();
while(rs.next()){
int sid1 = rs.getInt(1);
String sname1 = rs.getString(2);
System.out.println(sid1+"\t"+sname1);
InputStream is = rs.getBinaryStream(3);
FileOutputStream fos =
new
FileOutputStream("C:\\Users\\Ramchandar\\Desktop\\"+s
name1+".jpg");
int i = 0;
while((i= is.read())!=-1){
fos.write(i);
}
}
}
}
Commit;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.imageio.ImageIO;
import jdbc.aj.ram.ConnectionFactory;
public class JdbcProgram9{
public static void main(String[] args)
throws SQLException, IOException{
Connection con = ConnectionFactory.getConnect();
System.out.println(con);
/*PreparedStatement ps =
con.prepareCall("insert into empblob values(?,?)");
Scanner scan = new Scanner(System.in);
System.out.println("enter employee number");
int eno = scan.nextInt();
File f = new File("mypic.gif");
FileInputStream fis = new FileInputStream(f);
ps.setInt(1, eno);
ps.setBinaryStream(2, fis,(int)f.length());
int count = ps.executeUpdate();
System.out.println(count);
*/
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from empblob");
while(rs.next()){
System.out.println(rs.getInt(1));
InputStream is = rs.getBinaryStream(2);
BufferedImage img =ImageIO.read(is);
FileOutputStream fos =
new FileOutputStream("emp-"+rs.getInt(1)+".png");
ImageIO.write(img, "png", fos);
System.out.println("image created");
}
}
}
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.imageio.ImageIO;
import jdbc.aj.ram.ConnectionFactory;
public class JdbcProgram9{
public static void main(String[] args) throws SQLException,
IOException{
Connection con = ConnectionFactory.getConnect();
System.out.println(con);
/*PreparedStatement ps = con.prepareCall("insert into
empblob values(?,?)");
Scanner scan = new Scanner(System.in);
System.out.println("enter employee number");
int eno = scan.nextInt();
File f = new File("anni 012.jpg");
FileInputStream fis = new FileInputStream(f);
ps.setInt(1, eno);
ps.setBinaryStream(2, fis,(int)f.length());
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from empblob");
while(rs.next()){
System.out.println(rs.getInt(1));
InputStream is = rs.getBinaryStream(2);
BufferedImage img =ImageIO.read(is);
FileOutputStream fos = new
FileOutputStream("mypic15.bmp");
}
}
}
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Scanner;
int i = ps.executeUpdate();
System.out.println(i +" inserted");
}
catch(Exception e){
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCDemo {
public static void main(String[] args)throws
ClassNotFoundException, SQLException,
IOException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe
", "system","annie");
PreparedStatement ps = con.prepareStatement(
"insert into sbaj2_4c
values(?,?,?)");
Scanner scan = new Scanner(System.in);
boolean flag=true;
int totalrecords=0;
while(flag) {
System.out.println("how many text files
do you want to insert");
int nofiles = scan.nextInt();
for(int i=1;i<=nofiles;i++) {
System.out.println("enter student
id");
int sid = scan.nextInt();
System.out.println("enter student
name");
String sname = scan.next();
System.out.println("enter file
path");
String filepath = scan.next();
File f = new File(filepath);
FileReader fr = new FileReader(f);
ps.setInt(1, sid);
ps.setString(2, sname);
ps.setCharacterStream(3,fr,
(int)f.length() );
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
fw.flush();
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDemo {
public static void main(String[] args)throws
ClassNotFoundException, SQLException,
IOException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe
", "system","annie");
/*Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from
sbaj2_4c");*/
PreparedStatement ps =
con.prepareStatement("select * from sbaj2_4c");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
int sid = rs.getInt(1);
String sname = rs.getString(2);
Reader r = rs.getCharacterStream(3);
FileWriter fw = new
FileWriter("C:\\Users\\Ramchandar\\Desktop\\"+sname+s
id+".txt");
int i=0;
while((i=r.read()) !=-1) {
fw.write(i);
fw.flush();
}
}
con.close();
}
}
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCDemo {
public static void main(String[] args)throws
ClassNotFoundException, SQLException,
IOException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe
", "system","annie");
PreparedStatement ps =
con.prepareStatement("select * from sbaj2_4c where
sid=?");
Scanner scan = new Scanner(System.in);
System.out.println("enter student id for
selecting the file");
int id = scan.nextInt();
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
int sid = rs.getInt(1);
String sname = rs.getString(2);
Reader r = rs.getCharacterStream(3);
FileWriter fw = new
FileWriter("C:\\Users\\Ramchandar\\Desktop\\"+sname+s
id+".txt");
int i=0;
while((i=r.read()) !=-1) {
fw.write(i);
fw.flush();
}
}
con.close();
}
}
How to insert multiple file into database in jdbc:
package jdbc;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class JdbcDemo {
public static void main(String[] args)
throws ClassNotFoundException,SQLException,
IOException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe
", "system",
"manager");
System.out.println("con: "+con);
PreparedStatement ps =
con.prepareStatement("insert into course
values(?,?,?)");
Scanner scan = new Scanner(System.in);
System.out.println("How many records do you
want to insert");
int records = scan.nextInt();
int count = 0;
for(int i=1;i<=records;i++){
System.out.println("ENTER COURSE NAME");
String cname = scan.next();
System.out.println("ENTER FACULTY
NAME");
String fname = scan.next();
System.out.println("ENTER COURSE DETAILS
FILE PATH");
String cfpath = scan.next();
ps.setString(1,cname);
ps.setString(2, fname);
File f = new File(cfpath);
FileReader fr = new FileReader(f);
ps.setCharacterStream(3, fr,
(int)f.length());
count = count+ps.executeUpdate();
}
System.out.println(count+".records
inserted");
}
}
SQL> commit;
Commit complete.
ENO MARKS
101 MYTYPE1(11, 22, 33)
import java.io.IOException;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import ram.factory.ConnectionFactory;
public class Demo {
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe"
,"system","manager");
System.out.println("con: "+con);
Statement st = con.createStatement();
int count = st.executeUpdate("insert into mytype1tab
values(102,mytype1(55,66,77))");
System.out.println("count: "+count);
}
}
}
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
PreparedStatement ps = con.prepareStatement(
"insert into sajtype values(?,?)");
Scanner scan = new Scanner(System.in);
System.out.println("Ener student
identification number");
int sid = scan.nextInt();
ps.setInt(1, sid);
oracle.sql.ArrayDescriptor ad =
oracle.sql.ArrayDescriptor.createDescriptor("AJTYPE",
con);
for(int i=0;i<3;i++){
ia[i] = scan.nextInt();
}
oracle.sql.ARRAY a = new oracle.sql.ARRAY(ad,
con, ia);
ps.setArray(2, a);
int count= ps.executeUpdate();
System.out.println("count: "+count);
}
}
How to create object type data in oracle:
import java.sql.Array;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Demo {
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager")
;
System.out.println("con: "+con);
Statement st = con.createStatement();
int count = st.executeUpdate("insert into myobjtab
values(101,myobj('vizag','ap'))");
System.out.println("count: "+count);
}
}
}
}
How to Create Connection Factory in JDBC:
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectionFactory {
private Properties myProperties;
private Driver driver;
private String driverName;
private String url;
private String userName;
private String password;
private FileInputStream fis;
private static ConnectionFactory connectionFactory=null;
ConnectionFactory(){
try{
fis = new FileInputStream("MyProperties.properties");
myProperties = new Properties();
myProperties.load(fis);
driverName = myProperties.getProperty("driver");
driver = (Driver)Class.forName(driverName).newInstance();
url = myProperties.getProperty("url");
userName = myProperties.getProperty("user");
password = myProperties.getProperty("password");
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException("problem in connection
development");
}
}
public static Connection getConnection() throws
SQLException{
if(connectionFactory == null)
connectionFactory = new ConnectionFactory();
return connectionFactory.driver.connect(connectionFactory.url,
connectionFactory.myProperties);
}
}
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDemo {
public static void main(String[] s) throws SQLException{
Connection con = ConnectionFactory.getConnection();
if(con!=null){
System.out.println("con: "+con);
System.out.println("connection established");
}
else
System.out.println("connection not established");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from empram");
while(rs.next()){
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
}
}
Types Of ResultSet:
1. Forward ResultSet(TYPES_FORWARD_ONLY)
2. Scrollable ResultSet(
TYPES_SCROLL_SENSITIVE
TYPES_SCROLL_INSENSITIVE
)
3. Scrollable and Updateable ResultSet
(CONCUR_UPDATABLE).
4. Scrollable and Readonly Resultset(CONCUR_READ_ONLY).
Statement st = con.createStatement();
The above statement not providing any information to Statement
object for creating particular ResultSet type.
So by statmenet object will creates forward only ResultSet.
If we want to read the from top to bottom as well as bottom to top,
we should go for either TYPES_SCROLL_SENSITIVE or
TYPES_SCROLL_INSENSITIVE result set.
By default oracle thin driver not support, to work with this resultset
sensitive.
We should write column names instead of ‘*’.
We should write rs.refreshRow() in while loop.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
rs.refreshRow();
if(cnt==0)
Thread.sleep(40000);
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t
"+rs.getInt(3)+"\t"+rs.getString(4));
cnt++;
}
}
}
With out using any update, delete, insert query we can able to place
the data into db server table by using UpdatableResultSet.
b. By using updateRow().
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
System.out.println("=======================");
rs.beforeFirst();
while(rs.next()){
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
}
}
From the java application if we want to update the data which is
available in database in two ways.
a. by writing bellow query
update sbajemp set esal=5000 where eid=104;
b. by using updateInt(-,-).
updateInt(-,-) logic itself generate query for updating the data
in db.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
System.out.println("==========================");
while(rs.previous()){
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
}
}
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
System.out.println("==========================");
while(rs.previous()){
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
rs.first();
rs.relative(2);
System.out.println("==========================");
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
rs.last();
rs.relative(-1);
System.out.println("==========================");
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
}
WHENEVER WE WORKING WITH UPDATEABLE RESULTSET DON’T
USE ‘*’ SYMBOL, WE MUST AND SHOULD USE COLUMN NAMES,
ORDER OF THE COLUMNS ARE VERY MUCH IMPORTANT TO UPDATE
AND INSERT THE RECORDS IN DB SERVER TABLE.
We can delete the data from database from our java application in
two ways.
a. By using following query.
Delete from sbajemp where eid = 107;
b. By using deleteRow().
deleteRow() itself writing the query for delete record from
db.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
System.out.println("==========================");
while(rs.previous()){
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
rs.first();
rs.relative(2);
System.out.println("==========================");
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
rs.last();
rs.relative(-1);
System.out.println("==========================");
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
rs.last();
rs.deleteRow();
rs.beforeFirst();
System.out.println("==========================");
while(rs.next()){
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
}
}
we can insert record into database in two ways from our java
applicaton.
a. By using the following query
Insert into sbajemp values(103,’uma’,9500,’hr’);
b. By using insertRow().
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
System.out.println("==========================");
while(rs.previous()){
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
rs.first();
rs.relative(2);
System.out.println("==========================");
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
rs.last();
rs.relative(-1);
System.out.println("==========================");
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
rs.last();
rs.deleteRow();
rs.beforeFirst();
System.out.println("==========================");
while(rs.next()){
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
rs.moveToInsertRow();//not writing this statement
we //will get exception no current row
rs.updateInt(1, 104);
rs.updateString(2, "pritam");
rs.updateInt(3, 5000);
rs.updateString(4, "faculty");
rs.insertRow();
rs.beforeFirst();
System.out.println("==========================");
while(rs.next()){
System.out.println(rs.getInt("eno")
+"\t"+rs.getString("ename")+"\t"+rs.getInt("sal")
+"\t"+rs.getString("dept"));
}
}
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class JdbcDemo {
public static void main(String[] args)
throws ClassNotFoundException,SQLException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs =
st.executeQuery("select eno,ename,esal,deptno from
sbaj6to8");
Scanner scan = new Scanner(System.in);
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
}
System.out.println("------------------");
rs.beforeFirst();
while(rs.next()){
System.out.println("update "+rs.getInt(1)+" employee
salary");
int salary = scan.nextInt();
rs.updateInt(3, salary);
rs.updateRow();
}
System.out.println("------------------");
rs.beforeFirst();
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
}
con.close();
System.out.println("program completed");
}
}
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe
",
"system","manager");
Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE
,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select
sid,sname,jd from stddate");
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+
"\t"+
rs.getDate(3));
}
System.out.println("---------------------");
/*java.util.Date d = new java.util.Date();
java.sql.Date sd = new
java.sql.Date(d.getTime());*/
Scanner scan = new Scanner(System.in);
System.out.println("enter day");
int day = scan.nextInt();
System.out.println("enter month");
int month= scan.nextInt();
System.out.println("enter year");
int year = scan.nextInt();
java.sql.Date sd = new
java.sql.Date(year,month,day);
rs.beforeFirst();
rs.next();
rs.updateString(2, "ram");
rs.updateDate(3, sd);
rs.updateRow();
rs.beforeFirst();
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+
"\t"+
rs.getDate(3));
}
con.close();
}
}
Methods in ResultSet (updateable):
Statement st =
con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResutlSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery
("select eid,ename,esal,dept from sbajemp");
rs.last() : cursor pointing to last record of the table.
rs.first() : cursor pointing to first record of the table.
rs.next() : forward the controle from non-record area to
record area.
rs.beforeFirst(): cursor is pointing to non-record area
which is avilable before first record.
rs.afterLast() : cursor is pointing to non-record area
which is avilable after last record.
rs.moveToInsertRow(): it is used for move our cursor for
inserting new record.
rs.insertRow(): used to place the record into table.
rs.updateXxx(): used to update old data with new data.
rs.deleteRow(): used to delete the record from the table.
rs.isClosed():
rs.close():
rs.isAfterLast():
rs.isBeforeFirst():
rs.isFirst():
rs.isLast():
rs.relative();
rs.absolute()
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
rs.beforeFirst();
/*System.out.println(rs.getInt(1)+"\t"+rs.getString
(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));//
Exhausted Resultset
*/
System.out.println(rs.isBeforeFirst());//true
rs.last();
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
rs.afterLast();
/*System.out.println(rs.getInt(1)+"\t"+rs.getString
(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));// Exhausted
Resultset
*/
System.out.println(rs.isAfterLast());//true
rs.first();
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
System.out.println("-----"+rs.isFirst());
rs.last();
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
System.out.println("======"+rs.isLast());
rs.relative(-3);
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
/*rs.relative(4);
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));//exhausted ResultSet
*/
rs.absolute(-3);
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
rs.absolute(3);
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
rs.afterLast();
rs.absolute(3);
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
rs.afterLast();
/*rs.relative(-2);
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));*/
rs.last();
rs.relative(-2);
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
rs.beforeFirst();
rs.absolute(7);
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
System.out.println(rs.isClosed());//false
con.close();
System.out.println(rs.isClosed());//true
}
}
DataBaseMetaData:
It is one JDBC API object, used for getting the details about
database name, version, driver name, version, database username,
URL etc…..
We can develop this object by using Connection object.
System.out.println(dbmd.getDatabaseProductName());
System.out.println(dbmd.getDatabaseProductVersion());
System.out.println(dbmd.getDatabaseMajorVersion());
System.out.println(dbmd.getDatabaseMinorVersion());
System.out.println(dbmd.getUserName());
System.out.println(dbmd.getDriverName());
System.out.println(dbmd.getDriverVersion());
}
catch(Exception e){
e.printStackTrace();
}
}
}
Connection Pooling:
As we know that opening and closing connection to data base
is very costlier job and it requires more resources and time
consume.
This is will effect to performance of the system.
Connection Pool:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.PooledConnection;
import oracle.jdbc.pool.OracleConnectionPoolDataSource;
public class Demo1 {
Statement st = con.createStatement();
while(rs.next()){
System.out.println(rs.getInt(1)+"...."+rs.getString(2));
}
}
}
Programmatic proof about connection pooling:
MyPooledManager.java:
import java.sql.SQLException;
import oracle.jdbc.pool.OracleConnectionPoolDataSource;
JdbcDemo1.java:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.PooledConnection;
import oracle.jdbc.pool.OracleConnectionPoolDataSource;
}
}
JdbcDemo2.java:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.PooledConnection;
mysql-connector.jar
-----------------------------
Drivercom.mysql.jdbc.Driver
url jdbc:mysql://localhost:3306/ram
username:root
password: root
use ram;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
System.out.println(rs.getInt(1)+"..."+rs.getString(2));
}
How work with both the database from the same program with
different table names:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class Demo {
public static void main(String[] args)
throws ClassNotFoundException,
SQLException{
Scanner scan = new Scanner(System.in);
System.out.println("enter your driver name");
String driverName = scan.next();
System.out.println("enter your db url");
String url = scan.next();
System.out.println("enter your db username");
String username = scan.next();
System.out.println("enter your db password");
String password = scan.next();
System.out.println("");
Class.forName(driverName);
Connection con = DriverManager.getConnection(
url,username,password);
System.out.println("con: "+con);
Statement st = con.createStatement();
if(driverName.equals("oracle.jdbc.driver.OracleDriver
")){
ResultSet rs = st.executeQuery("select *
from sbaj6to8");
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)
+"\t"+rs.getInt(4)+"\t"+rs.getInt(4));
}
}
else{
ResultSet rs = st.executeQuery("select * from
stdtable");
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2))
;
}
}
}
}
How work with both the database from the same program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Demo {
public static void main(String[] s)
throws ClassNotFoundException,SQLException{
Scanner scan = new Scanner(System.in);
System.out.println("enter driver name");
String driver = scan.next();
System.out.println("enter url");
String url = scan.next();
System.out.println("enter username");
String user = scan.next();
System.out.println("enter password");
String password = scan.next();
Class.forName(driver);
Connection con =
DriverManager.getConnection(url,user,password);
System.out.println("con: "+con);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from
sbajtab");
System.out.println("SID\tSNAME\tSAGE");
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)
+"\t"+rs.getInt(3));
}
}
}
Oracledb.properties:
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username=system
password=annie
mysqldb.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/sbaj9to11
username=root
password=root
JdbcDemo.java:
//How to communicating with multiple databases and
table for fetching the data, from our java appn by
using .properties:
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Scanner;
public class JdbcDemo1 {
public static void main(String[] args)
throws ClassNotFoundException, SQLException,
IOException{
Scanner scan = new Scanner(System.in);
System.out.println("which database do you
required to"
+ " communicate\n1.Oracle
2.Mysql");
int dbtype = scan.nextInt();
switch(dbtype) {
case 1: FileInputStream fis =
new
FileInputStream("src/oracledb.properties");
Properties p = new Properties();
p.load(fis);//read datafrom fis in
the form key-value
String driver =
p.getProperty("driver");
String url = p.getProperty("url");
String user =
p.getProperty("username");
String password =
p.getProperty("password");
Class.forName(driver);
Connection con =
DriverManager.getConnection(url,user,password);
Statement st =
con.createStatement();
System.out.println("con: "+con);
System.out.println("st : "+st);
ResultSet rs =
st.executeQuery("select *
from sbaj9to11");
System.out.println("rs: "+rs);
while(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+
"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
}
break;
case 2: FileInputStream fis1 =
new
FileInputStream("src/mysqldb.properties");
Properties p1 = new Properties();
p1.load(fis1);//read datafrom fis in
the form key-value
String driver1 =
p1.getProperty("driver");
Oracledb.properties:
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username=system
password=annie
mysqldb.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/sbaj9to11
username=root
password=root
JdbcDemo.java
//How to communicating with multiple databases and
table
// for fetching the data, from our java appn:
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Scanner;
public class JdbcDemo1 {
public static void main(String[] args)
throws ClassNotFoundException, SQLException,
IOException{
Scanner scan = new Scanner(System.in);
System.out.println("which database do you
required to"
+ " communicate\n1.Oracle
2.Mysql");
int dbtype = scan.nextInt();
FileInputStream fis = null;
if(dbtype == 1) {
fis = new
FileInputStream("src/oracledb.properties");
}
else if(dbtype==2) {
fis = new
FileInputStream("src/mysqldb.properties");
}
Properties p = new Properties();
p.load(fis);//read datafrom fis in the form
key-value
String driver = p.getProperty("driver");
String url = p.getProperty("url");
String user = p.getProperty("username");
String password = p.getProperty("password");
Class.forName(driver);
Connection con =
DriverManager.getConnection(url,user,password);
Statement st = con.createStatement();
System.out.println("con: "+con);
System.out.println("st : "+st);
switch(dbtype) {
case 1: ResultSet rs=st.executeQuery("select
* from sbaj9to11");
System.out.println("rs: "+rs);
while(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+
"\t"+
rs.getInt(3)+"\t"+rs.getInt(4));
}
break;
case 2: ResultSet rs1
=st.executeQuery("select * from stdtab");
System.out.println("rs1: "+rs1);
while(rs1.next()) {
System.out.println(rs1.getInt(1)+"\t"+rs1.getString(2
));
}
}
}
}
How insert Date related information int database:
QueryDemo.java:
package kit.aj.date;
Later we are creating Date object of sql package and sending this
long value to constructor of Date class of sql package.
This constructor will convert that entire value into the following
format
“year-month-date”.
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class JdbcDemo {
public static void main(String[] args)
throws ClassNotFoundException,SQLException{
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:XE","system","manager");
System.out.println("con: "+con);
Statement st = con.createStatement();
//Date d = new Date("01/01/2000");
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/YY");
String s =sdf.format(d);
System.out.println(s);
/*int count =
st.executeUpdate("insert into stddate values(104,'ram','01-jan-
2000')");*/
int count =
st.executeUpdate("insert into stddate values(104,'ram','"+s+"')");
System.out.println(count+".record inserted");
}
}
JdbcDateDemo:
package kit.aj.date;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
import jdbc.aj.ram.ConnectionFactory;
ps.setInt(1,sno);
ps.setString(2, sname);
ps.setInt(3, sage);
ps.setDate(4, d2);
int updatecount = ps.executeUpdate();
System.out.println("updatecount: "+updatecount);
}
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Scanner;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe
","system","manager");
System.out.println("con: "+con);
Statement st = con.createStatement();
boolean b = st.execute(
"create table emptable (eid number, ename
varchar2(15),ejd date)");
System.out.println("table created: "+b);
Date d = new Date();
PreparedStatement ps = con.prepareStatement(
"insert into emptable
values(?,?,?)");
Scanner scan = new Scanner(System.in);
System.out.println("enter employee number");
int eid = scan.nextInt();
System.out.println("enter employee name");
String ename = scan.next();
ps.setInt(1, eid);
ps.setString(2, ename);
java.sql.Date sd = new
java.sql.Date(d.getTime());
ps.setDate(3, sd);
int count = ps.executeUpdate();
System.out.println(count+".record inserted");
}
}
package kit.aj.date;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
import jdbc.aj.ram.ConnectionFactory;
public class JdbcDateDemo {
public static void main(String[] args)
throws SQLException{
Connection con = ConnectionFactory.getConnect();
System.out.println("con: "+con);
PreparedStatement ps =
con.prepareStatement(QueryDemo.INSERTQUERY);
System.out.println("enter year");
int year = scan.nextInt();
System.out.println("enter month");
byte month = scan.nextByte();
System.out.println("enter day");
byte day = scan.nextByte();
Date d2 = new Date(year,month,day);
ps.setInt(1,sno);
ps.setString(2, sname);
ps.setInt(3, sage);
ps.setDate(4, d2);
int updatecount = ps.executeUpdate();
System.out.println("updatecount: "+updatecount);
}
}
Date d2 = new Date(year,month,day);
Whenever we with above statement we need follow this rule
that is
actual year - 1900.
for example if we want enter 1997, we need to enter 97.
the reason whenever we enter year internally the above constructor
add 1900 for the given year.
System.out.println("enter year");
int year = scan.nextInt();
System.out.println("enter month");
int month = scan.nextInt();
System.out.println("enter day");
int day = scan.nextInt();
String s = day+"-"+month+"-"+year;
package com.ram;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Scanner;
public class JdbcDemo{
public static void main(String[] args)
throws ClassNotFoundException,SQLException,
ParseException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","sy
stem","annie");
System.out.println("con: "+con);
PreparedStatement ps = con.prepareStatement(
"insert into stddate values(?,?,?)");
String s = "2015-5-5";
java.sql.Date sd = java.sql.Date.valueOf(s);
Scanner scan = new Scanner(System.in);
System.out.println("enter student id");
int sid = scan.nextInt();
System.out.println("enter student name");
String sname = scan.next();
ps.setInt(1, sid);
ps.setString(2, sname);
ps.setDate(3, sd);
int count = ps.executeUpdate();
System.out.println("count: "+count);
}
}
Drawbacks of ResultSet:
a.It is not extends java.io.Serializable interface.
b.Ihis object unable to travel throughout the
network.
c.By default ResultSet is forward and read only
mode.
d.If we want make our ResultSet as updateable and
scrollable programmer itself declare ResultSet
mode.
e.If we want to work ResultSet programmer should
create Connection and Statement objects.
f.It is not developed on top Bean Mechanizam (No
setters and getters).
RowSet:
JdbcRowSet:
1. It is connected rowset.
2. Whenever we work with JdbcRowSet the database
connection should be in connective mode.
3. It is implements java.io.Serializable interface.
4. It can travel throught the networks.
5. By default it is scorable and read only and updatebale also.
6. It will having one implementation class which is given by the
Oracle db server that is OralceJdbcRowSet.
import java.sql.SQLException;
import oracle.jdbc.rowset.OracleJDBCRowSet;
public class Check {
public static void main(String[] args)
throws ClassNotFoundException, SQLException{
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleJDBCRowSet jrs = new OracleJDBCRowSet();
jrs.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
jrs.setUsername("system");
jrs.setPassword("manager");
jrs.setCommand("select * from sbaj11to01");
jrs.execute();
while(jrs.next()){
System.out.println(jrs.getInt(1)+"\t"+
jrs.getString(2)+"\t"+jrs.getInt(3)+"\t"+jrs.getInt(4)
+"\t"+jrs.getString(5));
}
System.out.println("----------------------");
while(jrs.previous()){
System.out.println(jrs.getInt(1)+"\t"+
jrs.getString(2)+"\t"+jrs.getInt(3)+"\t"+jrs.getInt(4)
+"\t"+jrs.getString(5));
}
}
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
import oracle.jdbc.rowset.OracleJDBCRowSet;
js.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
js.setUsername("system");
js.setPassword("manager");
js.setCommand("insert into sbaj4to6
values(102,'sam',2000)");
js.execute();
}
}
Program on JdbcRowSet with dynamic values with
Scanner class:
import java.sql.SQLException;
import java.util.Scanner;
import oracle.jdbc.rowset.OracleJDBCRowSet;
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleJDBCRowSet oc = new OracleJDBCRowSet();
oc.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
oc.setUsername("system");
oc.setPassword("manager");
oc.setCommand("insert into sbaj6to8
values(?,?,?,?)");
Scanner scan = new Scanner(System.in);
System.out.println("enter some employee id");
int eno = scan.nextInt();
System.out.println("enter some employee
name");
String ename = scan.next();
System.out.println("enter some employee
sal");
int esal = scan.nextInt();
System.out.println("enter some employee
deptno");
int deptno = scan.nextInt();
oc.setInt(1, eno);
oc.setString(2, ename);
oc.setInt(3, esal);
oc.setInt(4, deptno);
oc.execute();
}
}
Program on JdbcRowSet with dynamic values with out
Scanner class:
package jdbc;
import java.sql.SQLException;
import oracle.jdbc.rowset.OracleJDBCRowSet;
//JdbcRowSet js =
RowSetProvider.newFactory().createJdbcRowSet();
js.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
js.setUsername("system");
js.setPassword("manager");
}
}
Program jdbcRowSet for Select query:
package jdbc;
import java.sql.SQLException;
import oracle.jdbc.rowset.OracleJDBCRowSet;
public class JdbcDemo4 {
public static void main(String[] args)
throws ClassNotFoundException,
SQLException{
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleJDBCRowSet oc=
new OracleJDBCRowSet();
oc.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
oc.setUsername("system");
oc.setPassword("manager");
oc.setCommand("select * from sbaj6to8");
oc.execute();
while(oc.next()){
System.out.println(oc.getInt(1)+"\t"+oc.getString(2)+
"\t"+oc.getInt(3)+"\t"+oc.getInt(4));
}
}
}
Program on JdbcRowSet for update the data:
package jdbc;
import java.sql.SQLException;
import oracle.jdbc.
rowset.OracleJDBCRowSet;
public class JdbcDemo4 {
public static void main(String[] args)
throws ClassNotFoundException,
SQLException{
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleJDBCRowSet oc=
new OracleJDBCRowSet();
oc.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
oc.setUsername("system");
oc.setPassword("manager");
oc.setCommand("update sbaj6to8 set esal=5000 where
eno=101");
oc.execute();
System.out.println("====================");
}
}
How to insert records into database table without
using query by using JdbcRowSet:
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
public class JdbcDemo1 {
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
JdbcRowSet js =
RowSetProvider.newFactory().createJdbcRowSet();
js.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
js.setUsername("system");
js.setPassword("annie");
js.setCommand("select sid,sname,sage,sfee from
sbaj4to6");
js.execute();
while(js.next()){
System.out.println(js.getInt(1)+"\t"+js.getString(2)+"\t"
+js.getInt(3)+"\t"+js.getInt(4));
}
js.moveToInsertRow();
js.updateInt(1, 203);
js.updateString(2, "akhil3");
js.updateInt(3, 20);
js.updateInt(4, 2000);
js.insertRow();
js.moveToCurrentRow();
}
}
How to update data in the database table by using
JdbcRowset:
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
public class JdbcDemo1 {
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
//JdbcRowSet js = new OracleJDBCRowSet();
JdbcRowSet js =
RowSetProvider.newFactory().createJdbcRowSet();
js.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
js.setUsername("system");
js.setPassword("annie");
js.setCommand("select sid,sname,sage,sfee from sbaj4to6
where sid=101");
js.execute();
js.next();
js.updateInt(3, 60);
js.updateInt(4, 5000);
js.updateRow();
}
}
Class.forName("oracle.jdbc.driver.OracleDriver");
//JdbcRowSet js = new OracleJDBCRowSet();
JdbcRowSet js =
RowSetProvider.newFactory().createJdbcRowSet();
js.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
js.setUsername("system");
js.setPassword("annie");
js.setCommand("select sid,sname,sage,sfee from sbaj4to6
where sid=101");
js.execute();
js.next();
js.deleteRow();
}
}
CachedRowSet:
It is disconnected rowset.
package jdbc;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import oracle.jdbc.rowset.OracleCachedRowSet;
js.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
js.setUsername("system");
js.setPassword("manager");
js.setCommand("insert into sbaj4to6
values(103,'mani',3000)");
js.execute();
}
}
Program on cachedrowset for reading the data:
package jdbc;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import oracle.jdbc.rowset.OracleCachedRowSet;
Class.forName("oracle.jdbc.driver.OracleDriver");
//JdbcRowSet js = new OracleJDBCRowSet();
CachedRowSet js =
RowSetProvider.newFactory().createCachedRowSet();
js.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
js.setUsername("system");
js.setPassword("manager");
js.setCommand("select * from sbaj6to8");
js.execute();
while(js.next()){
System.out.println(js.getInt(1)+"\t"+js.getString(2)+
"\t"
+js.getInt(3)+"\t"+js.getInt(4));
}
}
}
Program on cachedrowset for inserting records without using query:
package jdbc;
import javax.sql.RowSetMetaData;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import javax.sql.RowSetMetaData;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
WebRowSet:
It is mainly design for working web applications.
If we want place database table recods into xml file(write records
information into xml) and if we want read records form xml file, then
we should use WebRowSet.
package jdbc;
import java.io.File;
import java.io.FileWriter;
import oracle.jdbc.rowset.OracleWebRowSet;
public class SetDemo {
public static void main(String[] args) throws
Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleWebRowSet js = new OracleWebRowSet();
js.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
js.setUsername("system");
js.setPassword("manager");
js.setCommand("select * from sbaj4to6");
js.execute();
crs1.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
crs1.setUsername("system");
crs1.setPassword("ram");
crs1.setCommand("select
sid,sname,sage,sfee,scourse from student");
crs1.setMatchColumn(2);
crs1.execute();
crs2.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
crs2.setUsername("system");
crs2.setPassword("ram");
crs2.setCommand("select
sid,sname,cj,aj,oracle from marks");
crs2.setMatchColumn(2);
crs2.execute();
OracleJoinRowSet rs = new OracleJoinRowSet();
rs.addRowSet(crs1);
rs.addRowSet(crs2);
while(rs.next()){
System.out.print(rs.getString(1)+" ");
System.out.print(rs.getString(2)+" ");
System.out.print(rs.getString(3)+" ");
System.out.print(rs.getString(4)+" ");
System.out.print(rs.getString(5)+" ");
System.out.print(rs.getString(6)+" ");
System.out.print(rs.getString(7)+" ");
System.out.print(rs.getString(8)+" ");
System.out.print(rs.getString(9)+" ");
System.out.print(rs.getString(10)+" ");
}
}
}
The data which is available in JoinRowSet that is
always in the form of String only, no need represent
datatype for reading separately.
package jdbc;
import oracle.jdbc.rowset.OracleCachedRowSet;
import oracle.jdbc.rowset.OracleJoinRowSet;
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleCachedRowSet crs1= new
OracleCachedRowSet();
crs1.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
crs1.setUsername("system");
crs1.setPassword("abc");
crs1.setCommand("select eno,ename,esal from
sbaj6to8");
crs1.setMatchColumn(2);
crs1.execute();
crs2.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
crs2.setUsername("system");
crs2.setPassword("abc");
crs2.setCommand("select sno,sname,sfee from
sbaj4to6");
crs2.setMatchColumn(2);
crs2.execute();
OracleJoinRowSet rs = new OracleJoinRowSet();
rs.addRowSet(crs1);
rs.addRowSet(crs2);
while(rs.next()){
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));
//System.out.println(rs.getString(6));
}
}
}
import java.sql.SQLException;
import java.util.Scanner;
import javax.sql.RowSet;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.Predicate;
import oracle.jdbc.rowset.OracleFilteredRowSet;
class Filter1 implements Predicate{
private String colName;
public Filter1 (String colName){
this.colName=colName;
}
@Override
public boolean evaluate(RowSet rs) {
System.out.println("evaluate method");
try{
CachedRowSet crs = (CachedRowSet)rs;
String object = crs.getString(colName);
if(object!=null &&
(object.charAt(0)=='R')||(object.charAt(0)=='r')){
return true;
}
else return false;
}catch(Exception e){
}
return false;
}
@Override
public boolean evaluate(Object value, int column)
throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean evaluate(Object value, String
columnName) throws SQLException {
// TODO Auto-generated method stub
return false;
}
}
public class JdbcDemo3 {
public static void main(String[] args)
throws SQLException,ClassNotFoundException{
Class.
forName("oracle.jdbc.driver.OracleDriver");
OracleFilteredRowSet oc = new OracleFilteredRowSet();
oc.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
oc.setUsername("system");
oc.setPassword("manager");
oc.setCommand("select * from sbaj6to8");
oc.setFilter(new Filter1("ename"));
oc.execute();
while(oc.next()){
System.out.println(oc.getInt(1)+"
"+oc.getString(2)+" "+oc.getInt(3));
}
}
}
ResourceBundle in JDBC:
Db.properties:
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username=system
password=abc
package jdbc;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.sql.*;
public class Test{
public static void main(String[] args)
throws SQLException{
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system","manager"
);
Statement st = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs =st.executeQuery("select * from sbaj6to8");
try(con;st;rs){
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4)+"\t"+rs.getString(5));
}//while
}//try with resource
System.out.println("================");
/* try {
Statement st1 = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
*/
/* try {
ResultSet rs1 = st.executeQuery("select * from sbaj6to8");
} catch (SQLException e) {
e.printStackTrace();
*/
try {
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)
+"\t"+rs.getInt(3)+"\t"+rs.getInt(4)+"\t"+
rs.getString(5));
}
} catch (SQLException e) {
e.printStackTrace();
}
} //main
}//class
Q) Once we close Connection are we able to work with its
related Statement and ResultSet objects or not?
A) No. The reason once we close connection object then
automatically its related Statement and ResultSet objects are
also closed.
import java.sql.*;
public class Test {
public static void main(String[] args){
Connection con = null;
Statement st = null;
ResultSet rs = null;
try{
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","manager");
st = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
rs = st.executeQuery("select * from sbaj6to8");
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+
rs.getInt(3)+"\t"+rs.getInt(4)+"\t"+rs.getString(5));
}
}
catch (SQLException e) {
System.out.println("catch block");
e.printStackTrace();
}
finally{
try {
System.out.println("our connection successfully closed");
con.close();
} catch (SQLException e) {
System.out.println("finally catch block");
e.printStackTrace();
}
}
/*System.out.println(
"How to find whether connection was closed or not");
try {
Statement st1 = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}*/
/*try {
rs.first();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
ResultSet rs1 = st.executeQuery("select * from
sbaj6to8");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Test.java:
import java.sql.SQLException;
import java.util.Scanner;
import com.dto.Student;
import com.dto.Check;
public class Test{
public static void main(String[] args)throws
SQLException {
Scanner scan = new Scanner(System.in);
System.out.println("Enter student id");
int sid = scan.nextInt();
System.out.println("enter Student name");
String sname = scan.next();
System.out.println("enter student age");
int sage = scan.nextInt();
System.out.println("enter student fee");
int sfee = scan.nextInt();
System.out.println("enter student course");
String scourse = scan.next();
//Student s = new
Student(sid,sname,sage,sfee,scourse);
Student s = new Student();
s.setSid(sid);
s.setSname(sname);
s.setSage(sage);
s.setSfee(sfee);
s.setScourse(scourse);
Check.insert(s);
}
}
Check.java:
package com.dto;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Servlets:
----------
From java 1.2 onwards after introducing Servlets, Jsp concepts
into java,
we have three flavour in java.
1. Java2SE/ J2SE
2. Java2EE/ J2EE
3. Java2ME/ J2ME
2 represents version number.
From java 1.5 onwards, sun micro system delete the 2 for
representation and start calling directly as
1. JavaSE / JSE
2. JavaEE / JEE
3. JavaME / JME
JSE:
----
1. Java Stanadard Edition.
2. It is used to develop Standalone applications.
3. It is installable software.
4. Standalone applications may be CUI, GUI.
5. CUI we can develop through commandprompt.
6. GUT we can develop through Browsers (windows/Frame).
7. Standalone resource are sharable by the only one person at
a time,
that means data is not sharable between multiple client or
enduser at a time.
8. we required command prompt to compile and execute the
programs by using javac, java commands.
9. We required JDK software intallation.
10. JDK contains both compiler and JVM.
11. We are always using command prompt for giving the data
to program and getting response from program and
print the data (output) on command prompt by
using System.out.println() statements.
12. To work with JSE programs we required JDK API.
13. We save our .java files and .class files any folder and in
any directory.
14. we can compile and execute the program from any where in
our machine.
JEE:
-----
1. Java Enterprise Edition.(Java2 Platfrom Enterprise Ediition)
2. It is not installable software.
3. We can develop web, distributed, enterprise application.
4. These application resources can be sharable between
multiple user at a time through web in throughout
world.
5. To develop applications in JEE, we required JDK software
installation and JEE API.
6. To compile the program we required commandprompt and
javac command. This command given by JDK
software.
7. To execute the program we required Browsers( google
chrome, Mozilla firefox, Internet Explorer, Safari,
Opera Mini) and Servers(Apache tomcat, Glass Fish, web
logic..)-
8. We are always view the data or content on browsers only
either static or dynamic.
9. To print the data on browser, we use out.println()
statements.
10. We are always save our .class file in specific
folder that is "webapps".
11. To provide response to all the enduser, that means to
execute program and giving response all the endusers,
with in the same time we required servers. ( Apache Tomcat,
GlassFish, Weblogic,JBoss).
Software Technology:
------------------------
1. Technology will provides some rules and guide lines.
2. Rules are comming in the form interface.
3. Guide line are comming in the form of classes.
4. The combination of interface and classes simply we can
called as API.
5. These technology are usefull for developing technology
based software.
6. Here JDBC, SERVLETS, JSP are technologies.
7. Apache Tomcat, GlassFish, JBoss, Weblogic all are
technology based softwares.
WebApplication:
------------------
It is one type of applications running through web or running
under the servers for provides resources to as.l the end-user
through out world at a time is called web application.
we can develop web applications we have three technologies.
1. Java
2. Asp.Net
3. PHP
these web applications we can also called thin client- thick server.
thin client means only browser is sufficient no need of any extra
software configurations. Thick server means we required extra
software installation process.
a. HTML
b. java script
c. css
d. ajax
ex: www.nareshit.com
www.java4s.com
ex: www.gmail.com
www. facebook.com
interface Sim{
public abstract void call();
public abstract void sms();
}
class Mobile{
public static void main(String[] s1){
Sim s = new Vodafone();
s.call();
s.sms();
//loosely coupling
s = new Idea();
s.call();
s.sms();
}
}
---------------------------------------------------------------------------------
Q)what is the difference between web application and web site?
site means memory/location which is holds applications.
In general, every body feels like both are same but there is a
small difference between web site and web application.
JEE:
-----
It is one type of flavour/edition in java from 1.2
It is a technology.
It will provide specifications(rule and guide lines).
Rules comming in the form of interface
Guide lines comming in the form classes.
It is the combination following specifications.
1. Protocols specifications.
2. Servlet specifications.
3. jsp specifications.
4. EJB specifications.
5. Middleware services specifications.
Server functionalities:
--------------------------
1. getting client request.
2. loading/deploy the web components (loading the bytecode)
3. creating instances(object).
4. processing the request
5. if required communicating with files, database, any middileware
services
6. generating response
7. handover response to client
8. destroying the instances.
9. undeploy the web components.
Types of Servers:
--------------------
Mainly Servers are two types.
1. Web Server.
2. Application Server.
WebServer:
A server which will provide services to/implementation for/
logic for servlet specifications and jsp specifications and protocol
specifications.
ex: Apache Tomcat.
It will support web protocols like http, https, smtp ....
Application Server:
A server which will provide services to/implementation for/
logic for
all specifications given by JEE Technology is called Applications
Server.
What is WebComponent:
It is reusable object for providing services to end user.(servlet,
jsp, ejb..)
1. Browsers:
a) Mozilla Firefox.
b) Opera Mini.
c) Safari
d) Google Chrome
e) Internet explorer etc...
2. Web Components:
a) Servlets
b) Jsp
c) html
d) css
e) java script
f) images
g) .property files
3. Servers
a) Apache Tomcat
b) Weblogic
c) Websphere
d) Glassfish
e) JBoss
Typs of websites:
--------------------
there two types websites.
1. Informative websites
2. service oriented websites.
The websites will provides only static information for all the
endusers is called informative websites.
Internals of webserver:
----------------------------
WebServer mainly contains the following implementatios.
1. Http protocol implementation classes.
2. Servlet implementations classes
3. jsp implementation classes
4. Servlet container
5. Jsp container
6. Middleware services implementation classes.
class Servlet{
String servletName = "welcomeservlet";
private Servlet(){}
//static Servlet obj = new Servlet();
static Servlet obj = null;
static Servlet getObjectForServlet(){
//return new Servlet();
if(obj == null){
obj = new Servlet();
return obj;
}
else
return obj;
}
}
class Container{
public static void main(String[] s){
/*Servlet s1 = new Servlet();
System.out.println(s1.servletName);
Servlet s2 = new Servlet();
System.out.println(s2.servletName);
*/
Servlet s1 = Servlet.getObjectForServlet();
System.out.println(s1.servletName);
Servlet s2 = Servlet.getObjectForServlet();
System.out.println(s2.servletName);
System.out.println(s1.hashCode()+"...."+s2.hashCode());
}
}
Servlet:
---------
servelt is one technology will provides dynamic response to
enduser.
For providing response to enduser servlet container will uses
one separate thread.
Servlet will work on multithread mechanisam.
That provides response with in the less time, that means
performance of an application is more.
servlet concept developed on top of java technology.
So it is the platform independency concept.
Thread is a light weight process, uses less memory.
Servlet will reponse to all the enduser equally.
Definition:
-------------
Servlet is one JEE web technology, is used to generate dynamic
web content.
Servlet is one JEE Web technology, is used to create single
instance-multiple response process.
Servlet is one JEE Web technology, will increases services of
web and application servers.
Servlet is one JEE Web technology, will provices rules and
guide lines to develop our own web components.
Servlet is one class (userdefine)it is used to extends new
features.
In new tab apache tomact home page will come. Left side of that
page we have download link and different versions.
WelcomeServlet.java:
-------------------------
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class WelcomeServlet extends GenericServlet{
@Override
public void service(ServletRequest request,
ServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<marquee>Hello welcome first program</marquee>");
out.println("</body>");
out.println("</html>");
}
}
6. Develop web.xml file:
extract our project-->extract WebContent-->extract WEB-INF
and check web.xml file, if available use it. If not available create
web.xml in the following manner.
right click on WEB-INF-->select new -->select othersselect
generalclick on File-->given name as web.xml--> click on finish
button.
</web-app>
DateServletDemo.java:
package com.kit.aj;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
Web.xml:
<web-app>
<servlet>
<servlet-name>date</servlet-name>
<servlet-class>com.kit.aj.DateServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>date</servlet-name>
<url-pattern>/date</url-pattern>
</servlet-mapping>
</web-app>
Servlet-Singleton:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
System.out.println("SingletoServletDemo Object:
"+this+"..."+this.hashCode());
System.out.println("Current Thread Object:
"+Thread.currentThread()+"..."+
Thread.currentThread().hashCode()
+"..."+Thread.currentThread().getName());
System.out.println("ServletRequest Object:
"+request+"..."+request.hashCode());
System.out.println("ServletResponse Object:
"+response+"..."+response.hashCode());
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pw.print("<html>");
pw.print("<body>");
pw.println("SingletoServletDemo Object:
"+this+"..."+this.hashCode());
pw.print("<br/>");
pw.println("Current Thread Object:
"+Thread.currentThread()+"..."+
Thread.currentThread().hashCode()
+"..."+Thread.currentThread().getName());
pw.print("<br/>");
pw.println("ServletRequest Object:
"+request+"..."+request.hashCode());
pw.print("<br/>");
pw.println("ServletResponse Object:
"+response+"...."+response.hashCode());
pw.print("</body>");
pw.print("</html>");
}
Web.xml:
<web-app>
<servlet>
<servlet-name>single</servlet-name>
<servlet-
class>com.aj.ram.SingletonServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>single</servlet-name>
<url-pattern>/single</url-pattern>
</servlet-mapping>
</web-app>
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.SingleThreadModel;
}
<web-app>
<servlet>
<servlet-name>model</servlet-name>
<servlet-class>ServletModelDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>model</servlet-name>
<url-pattern>/model</url-pattern>
</servlet-mapping>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class WelcomeServlet extends GenericServlet{
public void service(ServletRequest
request,ServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='yellow'>");
out.println("<h1>THIS IS SERVLET
RESPONSE</H1>");
out.println("</body>");
try{
System.out.println("try block");
out.println("current
object:"+this.hashCode());
out.println("thread
object :"+Thread.currentThread().hashCode());
out.println("ServletRequest:"+request);
out.println("ServletResponse:
"+response);
out.println("PrintWriter: "+out);
Thread.sleep(10000);
}
catch(InterruptedException ie){
System.out.println("catch block");
ie.printStackTrace();
}
}
}
current object:1558299375
thread object :728287330
ServletRequest:org.apache.catalina.connector.RequestFacad
e@24dbc169
ServletResponse:
org.apache.catalina.connector.ResponseFacade@7a976a0a
PrintWriter:
org.apache.catalina.connector.CoyoteWriter@28b3290d
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class WelcomeServlet extends GenericServlet{
public void service(ServletRequest
request,ServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='yellow'>");
out.println("<h1>THIS IS SERVLET
RESPONSE</H1>");
out.println("</body>");
try{
System.out.println("try block");
out.println("current
object:"+this.hashCode()+"<br/>");
out.println("thread
object :"+Thread.currentThread().hashCode()+"<br/>");
out.println("ServletRequest:"+request.hashCode()
+"<br/>");
out.println("ServletResponse:
"+response.hashCode()+"<br/>");
out.println("PrintWriter:
"+out.hashCode()+"<br/>");
Thread.sleep(10000);
Date d = new Date();
out.println("Response time is: "+d);
}
catch(InterruptedException ie){
System.out.println("catch block");
ie.printStackTrace();
}
}
}
Eclipse Browser:
-----------------------------------------------------------------------
Outside of eclipse browser:
out.println("ServletRequest:"+request.hashCode()+"<br/>");
out.println("ServletResponse:
"+response.hashCode()+"<br/>");
out.println("PrintWriter:
"+out.hashCode()+"<br/>");
out.println("ServletConfig:
"+sconfig+"<br/>");
out.println("servletContext:
"+scontext+"<br/>");
Thread.sleep(10000);
Date d = new Date();
}
catch(InterruptedException ie){
System.out.println("catch block");
ie.printStackTrace();
}
}
}
Loading Phase:
Whenever end user sending request to servlet, first servlet
container will loads servlet class bytecode from secondary memory
to primary memory. In the meanwhile static variable and static block
static method are executing.
Instantiation phase:
In this phase servlet container will creates object for our own
servlet class. Meanwhile of object creation for our servlet class non-
static/instance variables, instance methods and instance blocks will
be executing and construcotr will be executing.
Initialization phase:
In above phase we don’t fill with initialization values in to
servlet object. That problem will be solved in this step. Servlet
container itself reading initialization values from web.xml file and
creates ServletConfig object and filled those initialization values and
calling the init (ServletConfig sc) by passing ServletConfig object.
Servicing phase:
Servlet container will creates ServletRequest object and
ServletResponse object and calling service (-,-) by passing request
and response objects by using servlet object witch is created in
instantiation phase.
Destroy phase:
In phase servlet object will be destroy by calling destroy().
Whenever our server shutdown or restart or project undeploy from
the server this phase be executing by the container.
GenericServlet:
Web.xml
<web-app>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>com.ram.aj.MyServlet</servlet-
class>
<init-param>
<param-name>fno</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>sno</param-name>
<param-value>200</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
</web-app>
One more approach to avoiding java.lang.NullPointerException:
Web.xml:
<web-app>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>com.ram.aj.MyServlet</servlet-
class>
<init-param>
<param-name>fno</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>sno</param-name>
<param-value>200</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
</web-app>
MyServlet.java:
package com.ram.aj;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MyServlet extends GenericServlet{
ServletConfig scfg;
@Override
public void init(ServletConfig sc)throws ServletException{
System.out.println("this is myservlet
init(ServletConfig)");
scfg=sc;
}
@Override
public void service(ServletRequest request,ServletResponse
response)
throws IOException,ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body bgcolor='Yellow'>");
out.println("<H2><MARQUEE>THIS SECONDSERVLET
PROGRAM</MARQUEE></H2>");
String fno = scfg.getInitParameter("fno");
String sno = scfg.getInitParameter("sno");
int fn = Integer.parseInt(fno);
int sn = Integer.parseInt(sno);
out.println("The Result is: "+(fn+sn));
out.println("</body>");
out.println("</html>");
}
}
Each and every servlet having their own servletconfig object, one
servlet related config object data can’t shared by other servlet
object
FirstServlet.java:
package com.ram.aj;
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FirstServlet extends GenericServlet{
@Override
public void service(ServletRequest request, ServletResponse
response)throws ServletException, IOException{
ServletConfig sc = getServletConfig();
System.out.println(sc.getInitParameter("fno"));
System.out.println(sc.getInitParameter("sno"));
}
}
SecondServlet.java:
package com.ram.aj;
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SecondServlet extends GenericServlet{
@Override
public void service(ServletRequest request, ServletResponse
response)throws ServletException, IOException{
ServletConfig sc = getServletConfig();
System.out.println(sc.getInitParameter("fno"));
System.out.println(sc.getInitParameter("sno"));
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.ram.aj.FirstServlet</servlet-class>
<init-param>
<param-name>fno</param-name>
<param-value>100</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>second</servlet-name>
<servlet-class>com.ram.aj.SecondServlet</servlet-
class>
<init-param>
<param-name>sno</param-name>
<param-value>200</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
</web-app>
Developing our own servlet By implementing javax.servlet.Servlet
interface:
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class LifeCycleServletDemo implements Servlet{
static int a = m1();
static int m1(){
System.out.println("static m1 method");
System.out.println("a: "+0);
return 111;
}
static{
System.out.println("static blocks");
}
int b = m2();
int m2(){
System.out.println("non-static m2 method");
System.out.println("b: "+0);
return 222;
}
{
System.out.println("non-static blocks");
}
@Override
public void init(ServletConfig arg0) throws ServletException {
System.out.println("init method");
}
@Override
public ServletConfig getServletConfig() {
System.out.println("getServletConfig method");
return null;
}
@Override
public String getServletInfo() {
System.out.println("getServletInfo method");
return null;
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println("service method");
}
@Override
public void destroy() {
System.out.println("destroy method");
}
}
Drawback: The drawback of program is we are always overrides the
all the methods of javax.servlet.Servlet interface.
But when we work with Generic and HttpServlet we are not facing
this type problem.
web.xml:
<web-app>
<servlet>
<servlet-name>life</servlet-name>
<servlet-class>LifeCycleServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>life</servlet-name>
<url-pattern>/life</url-pattern>
</servlet-mapping>
</web-app>
<load-on-startup>:
If we are writing other than integer number like float and String and
char, Boolean values we will get SAXParseException and server is
not starting.
Example on <load-on-startup>:
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println("service method");
}
}
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println("service method");
}
}
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println("service method");
}
}
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println("service method");
}
}
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println("service method");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>fs</servlet-name>
<servlet-class>FirstServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>ss</servlet-name>
<servlet-class>SecondServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>ts</servlet-name>
<servlet-class>ThirdServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>fos</servlet-name>
<servlet-class>FourthServlet</servlet-class>
<load-on-startup>-2</load-on-startup>
</servlet>
<servlet>
<servlet-name>fifth</servlet-name>
<servlet-class>FifthServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ss</servlet-name>
<url-pattern>/ss</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ts</servlet-name>
<url-pattern>/ts</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>fos</servlet-name>
<url-pattern>/fos</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>fifth</servlet-name>
<url-pattern>/fifth</url-pattern>
</servlet-mapping>
</web-app>
<web-app>
<servlet>
<servlet-name>fs</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs/ss/hai12</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>fis</servlet-name>
<servlet-class>FifthServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fis</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- <welcome-file-list>
<welcome-file>/fs/ss/hai12</welcome-file>
</welcome-file-list> -->
</web-app>
URL is provides security to our web component and also hides the
technology, which we were used in developing web component.
If the end user not understands the technology which I was used, he
is unable send virus or hacking programs.
That means simply we can say URL provides security from
unauthorized end users.
In web.xml
--------------
<url-pattern>/life</url-pattern>
In web.xml:
--------------
<url-pattern>/life/mylife/123</url-pattern>
In web.xml:
--------------
<url-pattern>/678ram</url-pattern>
Fromm browser: /678ram
In web.xml:
/life$
From browser:
/life$ (valid)
/life# (invalid)
Directory match url patten:
Start with / and ends with *
In web.xml:
---------------
<url-patten>/life/sb/*</url-pattern>
/life/sb/ram
/life/sb/sam
/life/sb/A.java
/life/sb/A.c
/sb/life/B.cpp(invalid)
/life/sb.c(invalid)
Extension match url pattern:
In web.xml:
---------------
<url-patten>*.java</url-pattern>
From browser: /ram.java
/sam.java
/kiran.ram.java
/ram/sam.java
/ram/sa/123.java
/kiran.ram.javas (invalid)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MSWordServletDemo extends GenericServlet {
@Override
public void service(ServletRequest req,
ServletResponse res)throws ServletException,IOException{
res.setContentType("application/msword");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<table border='2'>");
out.println("<tr><th>FacultyName</th><th>Subjects</th></tr>");
out.println("<tr><td>Ram</td><td>AdvancedJava</td></tr>");
out.println("<tr><td>Ravi</td><td>Oracle</td></tr>");
out.println("<tr><td>SathishB</td><td>Spring</td></tr>");
out.println("<tr><td>Natraz</td><td>AllJavaCourses</td></tr>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
out.println("</body>");
out.println("</html>");
}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
out.println("</body>");
out.println("</html>");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>MSWordServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>xs</servlet-name>
<servlet-class>XMLServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xs</servlet-name>
<url-pattern>/xs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>es</servlet-name>
<servlet-class>MSExcelServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>es</servlet-name>
<url-pattern>/es</url-pattern>
</servlet-mapping>
</web-app>
Execution: urls:
http://localhost:1111/ResponseTypes/ms
http://localhost:1111/ResponseTypes/xe
http://localhost:1111/ResponseTypes/es
Welcome files or Home pages are used to navigate the web pages of
website.
These are provides more flexibility to interact with website.
<welcome-file-list>
<welcome-file>…….</welcome-file>
</welcome-file-list>
In web.xml file servlet url pattern and .html file name is same then
first preference gives to Servlet only.
In web.xml file servlet url pattern and .jsp file name is same then
first preference gives to Servlet only.
<web-app>
<servlet>
<servlet-name>ws</servlet-name>
<servlet-class>WelcomeFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ws</servlet-name>
<url-pattern>/index.jsp</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
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-app>
<servlet>
<servlet-name>ws</servlet-name>
<servlet-class>WelcomeFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ws</servlet-name>
<url-pattern>/ws</url-pattern>
</servlet-mapping>
<!-- <servlet>
<servlet-name>hs</servlet-name>
<servlet-class>HelloServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hs</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> -->
<welcome-file-list>
<welcome-file>ws</welcome-file>
</welcome-file-list>
</web-app>
With <load-on-startup>
1. ServletContext
2. ServletConfig
3. Servlet object
4.ServletRequest
5.ServletResponse
6.PrintWriter
7.HttpSession
Without <load-on-startup>
1. ServletContext
2.ServletRequest
3.ServletResponse
4.PrintWriter
5. ServletConfig
6. Servlet object
7.HttpSession
Scope Objects:
These are used for carrying the information from one request to
another or one servlet to another servlet or one client to another
client are called Scope objects.
We have three scope objects.
1. Request[ServletRequest]
2. Session[HttpSession]
3. Context (in Servlet)/application in jsp)
[ServletContext].
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class AtmServlet extends GenericServlet {
@Override
public void service(ServletRequest request,
ServletResponse response)
throws ServletException,IOException{
request.setAttribute("accNo", 1234567);
RequestDispatcher rd =
request.getRequestDispatcher("/bs");
rd.forward(request, response);
}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class BankServlet extends GenericServlet {
@Override
public void service(ServletRequest request,
ServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Integer accNo =
(Integer) request.getAttribute("accNo");
out.println("<html>");
out.println("<body>");
out.println("Account Number is: "+accNo);
out.println("</body>");
out.println("</html>");
}
}
<web-app>
<servlet>
<servlet-name>fs</servlet-name>
<servlet-class>AtmServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>bs</servlet-name>
<servlet-class>BankServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bs</servlet-name>
<url-pattern>/bs</url-pattern>
</servlet-mapping>
</web-app>
In the above program if we are sending request to AtmServlet we
are getting proper output only.
If we are sending request to BankServlet we will get null value.
Form the same browser in different window if we are sending
request to BankServlet, we will get null value again.
From the different browser, if we are sending request to
BankServlet, again we will get null value only.
Session Object:
For own browser, servlet container will create one session object.
The same session object content will be used by different servlets in
our application.
import java.io.IOException;
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;
public class AtmServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
HttpSession session = request.getSession();
session.setAttribute("accNo", 777777);
RequestDispatcher rd =
request.getRequestDispatcher("/bs");
rd.forward(request, response);
}
}
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 BankServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
Integer accNo =
(Integer) session.getAttribute("accNo");
out.println("<html>");
out.println("<body>");
out.println("Account Number is: "+accNo);
out.println("</body>");
out.println("</html>");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>fs</servlet-name>
<servlet-class>AtmServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>bs</servlet-name>
<servlet-class>BankServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bs</servlet-name>
<url-pattern>/bs</url-pattern>
</servlet-mapping>
</web-app>
Context Object:
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class AtmServlet extends GenericServlet {
@Override
public void service(ServletRequest request,
ServletResponse response)
throws ServletException,IOException{
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
ServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
Integer accNo =
(Integer) context.getAttribute("accNo");
out.println("<html>");
out.println("<body>");
out.println("</body>");
out.println("</html>");
}
<web-app>
<servlet>
<servlet-name>fs</servlet-name>
<servlet-class>AtmServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>bs</servlet-name>
<servlet-class>BankServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bs</servlet-name>
<url-pattern>/bs</url-pattern>
</servlet-mapping>
</web-app>
<web-app>
<servlet>
<servlet-name>add</servlet-name>
<servlet-class>AddingServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
From browser Side:
We need to enter data in the following format:
http://localhost:portnumber/projectname/url?
firstparamname=paramvalues&secondparamname=paramvalue&.......
http://localhost:1111/HtmlServletCommunication/add?fno=200&sno=150
Note: don’t use any other special character and spaces in the
URL, if we type wrongly we get errors.
In the above approach end user unable type URL in the correct format.
To resolve this problem we should for html pages.
AddingServletDemo:
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-app>
<servlet>
<servlet-name>add</servlet-name>
<servlet-class>AddingServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
http://localhost:1111/HtmlServletCommunication/add.html
We will get add.html page
Later enter first number value is 500 and second number
value is 200 and click ADD button
After click on ADD button browser engine will convert above URL
into following manner
http://localhost:1111/HtmlServletCommunication/add?fno=500&sno=200
on browser we will get output like
Result Is: 700
In the above approach also there is one small drawback that is every time end user
click on back arrow button or end user will make new request from brower url to
add.html for entering new values for adding.
To avoiding above problem we should use hyperlink.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
In above approach end user every time click on “click me” hyperlink.
Sometimes may be end user not showing interest to click on hyperlink.
To resolve this problem we should add bellow code in the place of hyperlink
code.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
In the above approach old values are not display in the text
fields.
Whatever values we entered in request, if we want to display
those values in the text field we need to write the following code
in the place of RequestDispatcher in the previous program.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
out.println("<html>");
out.println("<body>");
out.println("Enter First Number: <input type='text' name='fno'
value='"+fno+"'/><br/>");
out.println("Enter Second Number: <input type='text' name='sno'
value='"+sno+"'/><br/>");
out.println("<input type='submit' value='add'>");
out.println("Result Is: "+result);
out.println("</body>");
out.println("</html>");
}
}
Add.html code and in servlet html related both are same. In above program if
the end user sending request to AddingServletDemo directly we face one
exception java.lang.NumberFormatException.
To overcome this problem we need to write the following code.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("firstnumber: "+firstNumber);
System.out.println("secondnumber: "+secondNumber);
int result=0;
String a="null";
String b="null";
if( (firstNumber == null || secondNumber ==null) ||
(a.equals(secondNumber)) || (b.equals(secondNumber)) ){
firstNumber="";
secondNumber="";
}
else{
int fno = Integer.parseInt(firstNumber);//""
int sno = Integer.parseInt(secondNumber);//"200"
result = fno+sno;//300
}
out.println("<form action='./add'>");
out.println("Enter First Number: <input type='text' name='fno'
/></br>");
out.println("Enter second number: <input type='text'
name='sno' /></br>");
out.println("<input type='submit' value='add'/>");
out.println("</form>");
if(!(firstNumber.isEmpty())){
out.println("result: "+result);
}
}
}
If the end user not inserting any data into text fields and click on
Add button will get again java.lang.NumberFormatException
to resolve this problem, we can use HTML5 attribute like “required”
in text field declaration in AddingServletDemo.java file
we can re write the code as bellow.
out.println("<form action='./add'>");
out.println("Enter First Number: <input type='text'
required name='fno' /></br>");
out.println("Enter second number: <input type='text'
required name='sno' /></br>");
out.println("<input type='submit' value='add'/>");
out.println("</form>");
Calculation Application:
cal.html:
<form>
<a href='./add.html'>ADDITION</a><br/>
<a href='./sub.html'>SUBTRACTION</a><br/>
<a href='./mul.html'>MULTIPLICATION</a><br/>
<a href='./div.html'>DIVISION</a><br/>
</form>
add.html:
<form action='./add'>
Enter First Number: <input type='text' name='fno'/><br/>
Enter Second Number: <input type='text' name='sno'/><br/>
<input type='submit' value='add'/>
</form>
sub.html:
<form action='./sub'>
Enter First Number: <input type='text' name='fno'/><br/>
Enter Second Number: <input type='text' name='sno'/><br/>
<input type='submit' value='sub'/>
</form>
mul.html:
<form action='./mul'>
Enter First Number: <input type='text' name='fno'/><br/>
Enter Second Number: <input type='text' name='sno'/><br/>
<input type='submit' value='mul'/>
</form>
div.html:
<form action='./div'>
Enter First Number: <input type='text' name='fno'/><br/>
Enter Second Number: <input type='text' name='sno'/><br/>
<input type='submit' value='div'/>
</form>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
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-app>
<servlet>
<servlet-name>add</servlet-name>
<servlet-class>AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sub</servlet-name>
<servlet-class>SubServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sub</servlet-name>
<url-pattern>/sub</url-pattern>
</servlet-mapping><servlet>
<servlet-name>mul</servlet-name>
<servlet-class>MulServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mul</servlet-name>
<url-pattern>/mul</url-pattern>
</servlet-mapping><servlet>
<servlet-name>div</servlet-name>
<servlet-class>DivServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>div</servlet-name>
<url-pattern>/div</url-pattern>
</servlet-mapping>
</web-app>
Servlet1.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Servlet1 extends GenericServlet{
int a;
int b;
@Override
public void init(ServletConfig sc)throws
ServletException{
System.out.println("servlet1 intit method:
");
System.out.println("config: "+sc);
a =
Integer.parseInt(sc.getInitParameter("p1"));
b =
Integer.parseInt(sc.getInitParameter("p2"));
}
@Override
public void service(ServletRequest request,
ServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='yellow'>");
out.println("The Result is: "+(a+b));
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
<init-param>
<param-name>p1</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>p2</param-name>
<param-value>200</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
</web-app>
ServletConfifDemo.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
public void service(ServletRequest req,ServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
if(con!=null){
System.out.println("con: "+con);
out.println("connection created");
}
else{
out.println("connection not established");
}
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>sc</servlet-name>
<servlet-class>ServletConfigDemo</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>manager</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sc</servlet-name>
<url-pattern>/sc</url-pattern>
</servlet-mapping>
</web-app>
In the above we are always placing same type of record
If we want place different types of records, we should
Go for following program.
<body bgcolor="pink">
<form action="./sc">
Enter Employee Number:
<input type="text" name="eno"/><br/>
Enter Employee Name :
<input type="text" name="ename"/><br/>
Enter Employee Salary:
<input type="text" name="esal"/><br/>
Enter Employee dept :
<input type="text" name="edept"/><br/>
<input type="submit" value="Enter"/>
</form>
</body>
ServletConfigDemo.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
catch(Exception e){
e.printStackTrace();
}
}
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
int eno = Integer.parseInt(req.getParameter("eno"));
String ename = req.getParameter("ename");
int esal = Integer.parseInt(req.getParameter("esal"));
String edept = req.getParameter("edept");
if(con!=null){
System.out.println("con: "+con);
out.println("connection created");
try {
st = con.createStatement();
int count = st.executeUpdate("insert into empram
values("+eno+",'"+ename+"',"+esal+",'"+edept+"')");
System.out.println("count: "+count);
} catch (SQLException e) {
e.printStackTrace();
}
}
else{
out.println("connection not established");
}
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>sc</servlet-name>
<servlet-class>ServletConfigDemo</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>manager</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sc</servlet-name>
<url-pattern>/sc</url-pattern>
</servlet-mapping>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
catch(Exception e){
e.printStackTrace();
}
}
@Override
public void service(ServletRequest req,ServletResponse
res)throws
ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
int eno = Integer.parseInt(req.getParameter("eno"));
String ename = req.getParameter("ename");
int esal = Integer.parseInt(req.getParameter("esal"));
String edept = req.getParameter("edept");
if(con!=null){
System.out.println("con: "+con);
out.println("connection created");
try {
st = con.createStatement();
int count = st.executeUpdate("insert into
empram values("+eno+",'"+ename+"',"+esal+",'"+edept+"')");
System.out.println("count: "+count);
} catch (SQLException e) {
e.printStackTrace();
}
}
else{
out.println("connection not established");
}
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
catch(Exception e){
e.printStackTrace();
}
}
@Override
public void service(ServletRequest req,ServletResponse
res)throws
ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
if(con!=null){
System.out.println("con: "+con);
out.println("connection created");
try {
st = con.createStatement();
ResultSet rs = st.executeQuery("select * from
empram");
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getInt(3));
System.out.println(rs.getString(4));
System.out.println("------------------");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
else{
out.println("connection not established");
}
}
}
<body bgcolor="pink">
<form action="./fs">
Enter Employee Number: <input type="text"
name="eno"/><br/>
Enter Employee Name : <input type="text"
name="ename"/><br/>
Enter Employee Salary: <input type="text"
name="esal"/><br/>
Enter Employee dept : <input type="text"
name="edept"/><br/>
<input type="submit"
value="Enter"/>
</form>
</body>
<web-app>
<context-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-
value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-
value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>system</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>manager</param-value>
</context-param>
<servlet>
<servlet-name>fs</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ss</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ss</servlet-name>
<url-pattern>/ss</url-pattern>
</servlet-mapping>
</web-app>
Program on ServletConfig getInitParameterNames():
Web.xml:
<web-app>
<servlet>
<servlet-name>sc</servlet-name>
<servlet-class>SCServlet</servlet-class>
<init-param>
<param-name>p1</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>p2</param-name>
<param-value>200</param-value>
</init-param>
<init-param>
<param-name>p3</param-name>
<param-value>300</param-value>
</init-param>
<init-param>
<param-name>p4</param-name>
<param-value>400</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sc</servlet-name>
<url-pattern>/sc</url-pattern>
</servlet-mapping>
</web-app>
SCServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
Enumeration<String> e= sc.getInitParameterNames();
int i=0;
int j=0;
while(e.hasMoreElements()) {
s[i] = e.nextElement();
ia[j]=
Integer.parseInt(sc.getInitParameter(s[i]));
++i;
++j;
}
}
@Override
public void service(ServletRequest
request,ServletResponse response)
throws ServletException,IOException{
int total=0;
for(int i=0;i<ia.length;i++) {
total= total+ia[i];
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='yellow'>");
out.println("<center><font size='6' color='black'>The Result
Is: "+(total)+"</center>");
out.println("</body>");
}
}
Drawbacks of GenericServlet:
-----------------------------------
When ever client sending the request data, that data will be
attached to browser URL and visible to everyone so security
problem.
We cannot get http protocol specification like
Security:
Whatever we entered in the .html file all the data will added to
browser url. So there is no security for securable data.
Client state persistence.
RequestHeader information.
Session tracking
No redirecting process.
To overcome that problems we should go for HttpServlet
interface.
Http Protocol:
----------------
Http is a communication channel between web client (browser)
and web server (tomcat) for data exchanging.
Http is a stateless protocol.
The meaning of stateless protocol is once response is
committed, it(server) doesn’t remember old client (request).
If we are sending one more request to server, http will treat
the same client as new client.
If we are using http, every request will be treated as new
client.
Http is a specification.
That means it will provide rules and guidelines to web client
and web server.
<web-app>
<servlet>
<servlet-name>hs</servlet-name>
<servlet-class>HttpServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hs</servlet-name>
<url-pattern>/hs</url-pattern>
</servlet-mapping>
</web-app>
<body bgcolor='red'>
<form action="./hs" method='get'>
<input type='submit' value='click'/>
</form>
</body>
Why ServletContainer not calls doXxx()?
These method are specific to http protocol specifications.
If container calls doXxx() directly, then other protocol
requests cannot be processing.
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HttpServletDemo extends HttpServlet {
/*@Override
public void service (ServletRequest req,
ServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("This is HttpServlet-public service");
}
@Override
protected void service (HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("This is HttpServlet-protected service");
}*/
@Override
protected void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("This is HttpServlet-doGet()");
}
@Override
protected void doPost (HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("This is HttpServlet-doPost()");
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@WebServlet("/as")
public class AddServlet extends HttpServlet {
/*@Override
public void doPost (HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
int fno =
Integer.parseInt(req.getParameter("fno"));
int sno =
Integer.parseInt(req.getParameter("sno"));
int result = fno+sno;
out.println("This is HttpServlet-doPost <br/>");
out.println("Result: "+result);*/
@Override
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
int fno =
Integer.parseInt(req.getParameter("fno"));
int sno =
Integer.parseInt(req.getParameter("sno"));
int result = fno+sno;
out.println("This is HttpServlet-doGet() <br/>");
out.println("Result: "+result);
Enumeration headerNames =
req.getHeaderNames();
while(headerNames.hasMoreElements()){
String headerName = (String)
headerNames.nextElement();
out.println(headerName+"<br/>");
String headerValue =
req.getHeader(headerName);
out.println(headerValue+"<br/>");
}
}
}<!-- <body bgcolor='red'>
<form action="./hs" method='get'>
Enter First No: <input type='text' name="fno"/>
Enter Second No: <input type='text' name="sno"/>
<input type='submit' value='add'/>
</form>
</body> -->
<body bgcolor='red'>
<form action="./hs" method='get'>
fno: <input type='text' name="fno"/>
sno: <input type='text' name="sno"/>
<web-app>
<servlet>
<servlet-name>hs</servlet-name>
<servlet-class>AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hs</servlet-name>
<url-pattern>/hs</url-pattern>
</servlet-mapping>
</web-app>
<!-- <web-app>
<servlet>
<servlet-name>hs</servlet-name>
<servlet-class>HttpServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hs</servlet-name>
<url-pattern>/hs</url-pattern>
</servlet-mapping>
</web-app> -->
Input.html:
<html>
<body bgcolor='yellow'>
<form action='./db' method='GET'>
<input type='submit' value='EMPLOYEEDETAILS'/>
</form>
<form action='./db' method='POST'>
<input type='submit' value='NEWRECORDS'/>
</form>
</body>
</html>
Web.xml:
<web-app>
<servlet>
<servlet-name>db</servlet-name>
<servlet-class>com.nit.ram.DBServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>db</servlet-name>
<url-pattern>/db</url-pattern>
</servlet-mapping>
</web-app>\
DBServlet.java:
package com.nit.ram;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DBServlet extends HttpServlet {
Connection con;
Statement st;
@Override
public void init(ServletConfig sc)throws ServletException{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
st=con.createStatement();
}catch(ClassNotFoundException c){
System.out.println("----------------");
c.printStackTrace();
}catch(SQLException c){
System.out.println("****************");
c.printStackTrace();
}
}
@Override
public void doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='pink'>");
out.println("<table border='7'>");
out.println("<tr><th>EID</th><th>ENAME</th><th>ESAL</th></tr>");
try {
ResultSet rs = st.executeQuery("select * from
employee");
while(rs.next()){
out.println("<tr><td>"+rs.getInt(1)+"</td><td>"+
rs.getString(2)+"</td><td>"+rs.getInt(3)+"</td></tr>");
}
} catch (SQLException e) {
System.out.println("^^^^^^^^^^^^^^^^^^^^^");
e.printStackTrace();
}
out.println("</table>");
out.println("</body>");
}
@Override
public void doPost(HttpServletRequest request,HttpServletResponse
response)throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='pink'>");
try {
int count=st.executeUpdate(
"insert into employee values(106,'raj',6500)");
out.println(count+".Record Inserted.......");
} catch (SQLException e) {
System.out.println("#########################");
e.printStackTrace();
}
out.println("</body>");
}
}
doGet():
1. It is design for getting the data from server
2. Data will visible in brower url.
3. We can not send secure data.
4. We can send only limited data.
5. We can send only 1024 characters data
6. We can’t upload files the reason is url supports only
characters but not binary format data
7. We have four approaches to work with doGet().
a. By default browser
b. By method=’get’
c. Writing data directly in URL.
d. By using HyperLink.
doPost():
1. It is design for uploading the data into server
2. Data will not visible in brower url.
3. We can send secure data.
4. We can send unlimited data.
5. There is no limitation for data sending.
6. We can upload files
7. We have only one approaches to work with doPost().
a. By method=’get’
</body>
</html>
RequestDemo.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestDemo extends HttpServlet{
@Override
public void doPost(HttpServletRequest
request,HttpServletResponse
response)throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='yellow'>");
out.println("<h2>THIS IS REQUESTDEMO DOGET
METHOD</H2>");
out.println("<body>");
}
}
Working Servlet without Eclipse:
1. Download apache tomcat software.
2. Install the appache tomcat.
HttpServletResponse res)throws
ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
int fno = Integer.parseInt(req.getParameter("fno"));
int sno = Integer.parseInt(req.getParameter("sno"));
int result = fno+sno;
out.println("Result is: "+result);
}
}
and saved into ServletDemo/WEB-INF/classes folder.
\Tomcat 8.0\lib\servlet-api.jar;
(enter)
C:\Users\lenovo\Desktop\ServletDemo\WEB-INF\classes>
javac AddServlet.java
we will get AddServlet.class file in the same classes folder.
input values.
Note: If we are working with any jar files placed those jar files
into WEB-INF/lib folder.
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class ServletChainingDemo1 extends GenericServlet{
@Override
public void init(ServletConfig sc )throws ServletException{
System.out.println("scd1 init method");
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
System.out.println("scd1 service method");
ServletChainingDemo2 sd = new
ServletChainingDemo2();
sd.service(req,res);
}
}
ServletChainingDemo2.java
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
<web-app>
<servlet>
<servlet-name>sc1</servlet-name>
<servlet-class>ServletChainingDemo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sc1</servlet-name>
<url-pattern>/sc1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sc2</servlet-name>
<servlet-class>ServletChainingDemo2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sc2</servlet-name>
<url-pattern>/sc2</url-pattern>
</servlet-mapping>
</web-app>
System.out.println("==================");
Servlet2 obj = new Servlet2();
obj.service(request, response);
}
}
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
}
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
1. Servlet.
2. JSP Files.
3. Html files.
4. Normal Text Files.
RequestDispatcher rd2 =
getServletContext().getRequestDispatcher(-);
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Servlet1 extends GenericServlet{
@Override
public void service(ServletRequest request,
ServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='yellow'>");
out.println("<h1>THIS IS SERVLET-1 RESPONSE</H1>");
out.println("<h1>S1-Request:"+request.hashCode()
+"</h1>");
out.println("<h1>S1-Response:"+response.hashCode()
+"</h1>");
out.println("<body>");
RequestDispatcher rd =
request.getRequestDispatcher("./s2");
//rd.forward(request, response);
rd.include(request, response);
}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
public void service(ServletRequest request,
ServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='Green'>");
out.println("<h1>THIS IS SERVLET-2 RESPONSE</H1>");
out.println("<h1>S2-Request:"+request.hashCode()
+"</h1>");
out.println("<h1>S2-Response:"+response.hashCode()
+"</h1>");
out.println("<body>");
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
public void init(ServletConfig sc)throws ServletException{
System.out.println("servlet-1 init method");
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
System.out.println("servlet1 service method");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<H1>THIS IS SERVLET-1 SERVICE");
//RequestDispatcher rd = req.getRequestDispatcher("./s2");
//rd.forward(req, res);
//rd.include(req, res);
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
public void init(ServletConfig sc)throws ServletException{
System.out.println("servlet-2 init method");
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
System.out.println("servlet2 service method");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<H1>THIS IS SERVLET-2 SERVICE");
out.println("<H1>THIS IS SERVLET-2 RESPONSE");
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
Hello.html:
First.jsp
second.txt:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Servlet1 extends GenericServlet{
@Override
public void init(ServletConfig sc)
throws ServletException{
System.out.println("servlet-1 init method");
}
@Override
public void service(ServletRequest req,
ServletResponse res)
throws ServletException, IOException {
System.out.println("servlet1 service method");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<H1>THIS IS SERVLET-1 SERVICE");
RequestDispatcher rd = req.getRequestDispatcher("./s2");
//rd.forward(req, res);
rd.include(req, res);
RequestDispatcher rd1=req.getRequestDispatcher("./hello.html");
rd1.include(req, res);
/*RequestDispatcher rd2=req.getRequestDispatcher("./first.jsp");
rd2.forward(req, res);
RequestDispatcher rd3=req.getRequestDispatcher("./second.txt");
rd3.forward(req, res);*/
out.println("<H1>THIS IS SERVLET-1 RESPONSE");
}
}
After writing the forward(-,-) in servlet don’t use forward(-,-).
sndRedirect(-):
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet{
@Override
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
System.out.println("servlet1 service method");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<H1>THIS IS SERVLET-1 SERVICE");
//res.sendRedirect("https://www.google.com");
res.sendRedirect("./s2");
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
</html>
Servlet1.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet{
static{
System.out.println("servlet1-static block");
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws
ServletException,
IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String s1 = request.getParameter("uname");
request.setAttribute("uname", s1);
//request.getRequestDispatcher("./s2").forward(request,
response);
response.sendRedirect("./s2");
//response.sendRedirect("http://localhost:3016/SRD2/s
3");
}
}
Servlet2.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet{
static{
System.out.println("servlet2-static block");
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws
ServletException,
IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String s1 = (String) request.getAttribute("uname");
out.println("<h1>THIS SERVLET-TWO RESPONSE");
out.println("End User Name Is: "+s1+"</h1>");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
Program on sendRedirect(-) for checking charing the sesssion scope
object data sharable or not:
User.html:
<html>
<body bgcolor='wheat'>
<form action='./s1' method='get'>
Enter user Name: <input type = 'text'
name="uname"/>
<input type='submit' value='submit'/>
</form>
</body>
</html>
Servlet1.java
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 Servlet1 extends HttpServlet{
static{
System.out.println("servlet1-static block");
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws
ServletException,
IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String s1 = request.getParameter("uname");
HttpSession session = request.getSession();
session.setAttribute("uname", s1);
response.sendRedirect("./s2");
//response.sendRedirect("http://localhost:3016/SRD2/s
3");
}
}
Servlet2.java:
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 Servlet2 extends HttpServlet{
static{
System.out.println("servlet2-static block");
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws
ServletException,
IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String s1 = (String)
session.getAttribute("uname");
out.println("<h1>THIS SERVLET-TWO RESPONSE");
out.println("End User Name Is: "+s1+"</h1>");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
Program on sendRedirect(-) for checking sharing the context scope
object data sharable or not:
User.html:
<html>
<body bgcolor='wheat'>
<form action='./s1' method='get'>
Enter user Name: <input type = 'text'
name="uname"/>
<input type='submit' value='submit'/>
</form>
</body>
</html>
Servlet1.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet{
static{
System.out.println("servlet1-static block");
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws
ServletException,
IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String s1 = request.getParameter("uname");
ServletContext sc = getServletContext();
sc.setAttribute("uname", s1);
response.sendRedirect("./s2");
//response.sendRedirect("http://localhost:3016/SRD2/s
3");
}
}
Servle2.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
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 Servlet2 extends HttpServlet{
static{
System.out.println("servlet2-static block");
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws
ServletException,
IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletContext sc = getServletContext();
String s1 = (String)sc.getAttribute("uname");
out.println("<h1>THIS SERVLET-TWO RESPONSE");
out.println("End User Name Is: "+s1+"</h1>");
}
}
Web.xm:
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
TestServlet1.java
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;
TestServlet3.java
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;
static{
System.out.println("testservlet3 loading");
@Override
HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html");
out.println("<body bgcolor='yellow'>");
out.println("THIS IS TESTSERVLET3 RESPONSE");
Web.xml:
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>TestServlet1</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s3</servlet-name>
<servlet-class>TestServlet3</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>s3</servlet-name>
<url-pattern>/s3</url-pattern>
</servlet-mapping>
</web-app>
Test2 Project:
TestServlet2.java
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;
static{
System.out.println("testservlet2 loading");
@Override
HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html");
out.println("<body bgcolor='yellow'>");
String username=request.getParameter("user");
out.println("username: "+username);
out.println("THIS IS TESTSERVLET2 RESPONSE");
Web.xml:
<web-app>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>TestServlet2</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
SquareServlet.java:
package com.aj.rd;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SquareServlet extends HttpServlet{
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse
response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='cyan'>");
String num = request.getParameter("num");
int no = Integer.parseInt(num);
int square = no*no;
out.println("<h2>Square Of The Given Number
Is: "+square+"</h2><br/>");
ServletContext sct1 = getServletContext();
ServletContext sct2 =
sct1.getContext("/CubeServletProject");
RequestDispatcher rd =
sct2.getRequestDispatcher("/cs");
rd.include(request, response);
out.println("</body>");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>ss</servlet-name>
<servlet-
class>com.aj.rd.SquareServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ss</servlet-name>
<url-pattern>/ss</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>
Input.html:
<html>
<body bgcolor='orangered'>
<form action='./ss'>
Enter Number For Square and Cube:
<input type='text' name='num'/><br/>
<input type='submit' value='ENTER'/>
</form>
</body>
</html>
CubeServletProject:
CubeServlet.java:
package com.aj.rd;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CubeServlet extends HttpServlet{
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse
response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String num = request.getParameter("num");
int no = Integer.parseInt(num);
int cube = no*no*no;
out.println("<h2>Cube Of The Given Number Is:
"+cube+"</h2><br/>");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>cs</servlet-name>
<servlet-class>com.aj.rd.CubeServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>cs</servlet-name>
<url-pattern>/cs</url-pattern>
</servlet-mapping>
</web-app>
Do following changes in
Servlers/ApacheTomcat/context.xml fle in eclipse like
bellow
<Context crossContext=’true’>
</Context>
If we have only one text field on top of one name and trying to read
the data from that table we should prefer method like
getParameter(-).
First.html
<html>
<body bgcolor='pink'>
<form action="./s1">
<table>
<tr>
<td>Courses</td>
</tr>
<tr>
<td>Course1</td>
<td><input type='text' name="course" value=''/>
</tr>
<tr>
<td>Course2</td>
<td><input type='text' name="course" value=''/>
</tr>
<tr>
<td>Course3</td>
<td><input type='text' name="course" value=''/>
</tr>
<tr>
<td>Course4</td>
<td><input type='text' name="course" value=''/>
</tr>
</table>
<input type='submit' value='CLICK'/>
</form>
</body>
</html>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet{
@Override
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
System.out.println("servlet1 service method");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<H1>THIS IS SERVLET-1 SERVICE</H1><br/>");
String name = req.getParameter("name");
out.println("Name: "+name);
String[] s = req.getParameterValues("course");
for(String s1: s){
out.println(s1+"<br/>");
}
out.println("<H1>THIS IS SERVLET-1 RESPONSE");
}
}
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
<html>
<body bgcolor='pink'>
<form action="./s1">
Enter Name : <input type='text' name='name'/><br/>
Enter Age : <input type='text' name='age'/><br/>
Enter course: <input type='text' name='course'/><br/>
Enter fee : <input type='text' name='fee'/><br/>
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
HttpServletResponse res)
res.setContentType("text/html");
out.println("<H1>THIS IS SERVLET-1
SERVICE</H1><br/>");
Enumeration e= req.getParameterNames();
while(e.hasMoreElements()){
out.println(tfn+"...."+tfv);
Enumeration<String> e1 = req.getHeaderNames();
while(e1.hasMoreElements()){
out.println(headerName+":::"+headerValue);
System.out.println(headerName+"::"+headerValue);
}
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
</web-app>
<html>
<body bgcolor='pink'>
<form action="./s1">
Enter Name : <input type='text' name='name'/><br/>
Enter Age : <input type='text' name='age'/><br/>
Enter course: <input type='text' name='course'/><br/>
Enter fee : <input type='text' name='fee'/><br/>
Program On getParameterMap():
This method will read the data like text filed name and its
values in the format of Map object from ServletRequest Object.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
response)throws ServletException,IOException{
response.setContentType("text/html");
out.println("<body bgcolor='yellow'>");
Map<String,String[]>map =request.getParameterMap();
while(it.hasNext()){
System.out.println("---------------");
out.println(ent.getKey()
+"..."+Arrays.toString(ent.getValue()));
out.println("<body>");
}
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
HttpServletResponse res)
res.setContentType("text/html");
out.println("<H1>THIS IS SERVLET-1
SERVICE</H1><br/>");
RequestDispatcher rd =
req.getRequestDispatcher("./s2");
rd.forward(req, res);
}
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;
}
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
<html>
<body bgcolor='Yellow'>
<form action="./s1">
Enter Name : <input type='text' name='name'/><br/>
<input type='submit' value='CLICK'/>
</form>
</body>
</html>
Session Tracking
What is Session?
a. Cookie
b. Hidden Form Fields
c. URL Rewriting
d. HttpSession
Cookie:
a. Persisntence cookie.
b. Non-persistance cookie.
Non-Persistance cookie:
The cookie are available upto before closing browser are called
Non-persistance cookies.
Persistance cookie:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
HttpServletResponse res)
res.setContentType("text/html");
res.addCookie(c);
out.println("</form>");
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
HttpServletResponse res)
/*Cookie[] c = req.getCookies();
*/
}
<html>
<body bgcolor='Yellow'>
<form action="./s1">
Enter Name : <input type='text' name='name'/><br/>
<input type='submit' value='CLICK'/>
</form>
</body>
</html>
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
Program on cookie:
Index.html:
<html>
<body>
<form>
<a href="./login.html">Login</a><br/>
<a href="./los">LogoutServlet</a><br/>
<a href="./ps">ProfileServlet</a><br/>
<input type='submit' value="submit"/>
</form>
</body>
</html>
Login.html:
<html>
<form action="./ls">
Enter your name: <input type='text' ame='name'/><br/>
Enter your password: <input type='text'
name='password'/><br/>
<input type='submit' value='submit'/>
</form>
</html>
Link.html:
<a href="./login.html">Login</a><br/>
<a href="./los">LogoutServlet</a><br/>
<a href="./ps">ProfileServlet</a><br/>
LoginServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
RequestDispatcher rd =
request.getRequestDispatcher("./link.html");
rd.include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("naaz")){
out.print("<br/>Welcome, "+name);
response.addCookie(ck);
}else{
out.print("<br/>sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request,
response);
out.close();
LogoutServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request,
response);
ck.setMaxAge(0);
response.addCookie(ck);
ProfileServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request,
response);
Cookie ck[]=request.getCookies();
if(ck!=null){
String name=ck[0].getValue();
if(!name.equals("")||name!=null){
out.print("<br/><b>Welcome to Profile</b>");
out.print("<br/>Welcome, "+name);
}else{
request.getRequestDispatcher("login.html").include(request,
response);
out.close();
Web.xml:
<web-app>
<servlet>
<servlet-name>ls</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ls</servlet-name>
<url-pattern>/ls</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>los</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>los</servlet-name>
<url-pattern>/los</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ps</servlet-name>
<servlet-class>ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ps</servlet-name>
<url-pattern>/ps</url-pattern>
</servlet-mapping>
</web-app>
How to add multiple cookies to response object:
User.html:
<html>
<body bgcolor='cyan'>
<form action='./ts'>
Enter User Name: <input type='text'
name='username'/><br/>
Enter User password: <input type='text' name='password'/>
<input type='submit' value='login'/>
</form>
</body>
</html>
Web.xml:
<web-app>
<servlet>
<servlet-name>ts</servlet-name>
<servlet-class>com.ram.aj.cookie.TestServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>ts</servlet-name>
<url-pattern>/ts</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ds</servlet-name>
<servlet-class>com.ram.aj.cookie.DisplayServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>/ds</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>user.html</welcome-file>
</welcome-file-list>
</web-app>
TestServlet.java
package com.ram.aj.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet{
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response )
throws IOException,ServletException{
String username = request.getParameter("username");
String password = request.getParameter("password");
Cookie c1 = new Cookie("user",username);
Cookie c2 = new Cookie("password",password);
response.addCookie(c1);
response.addCookie(c2);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<body bgcolor='orangered'>");
pw.println("<h2>In TestServlet user is:
"+username+"<br/>");
pw.println("In TestServlet password is:
"+password+"</h2>");
pw.println("<form action='./ds'>");
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DisplayServlet extends HttpServlet{
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response )
throws IOException,ServletException{
Cookie[] c = request.getCookies();
System.out.println(c.length);
String username=null;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<body bgcolor='red'>");
for(Cookie c1: c){
System.out.println(c1.getValue());
pw.println("<h2>In DisplayServlet user is:
"+c1.getValue()+"</h2>");
}
pw.println("</body>");
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response )
throws IOException,ServletException{
doPost(request,response);
}
}
Program on Cookie between more than two servlets:
Login.html:
<html>
<body bgcolor='yellow'>
<form action='./s1'>
Enter Student Name: <input type='text'
name='uname'/><br/>
Enter Student pawd:<input type='password'
name='upwd'/><br/>
<input type='submit' value='Login'/>
</form>
</body>
</html>
Servlet1.java:
package com.ram.proj1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
response)throws ServletException,IOException{
response.setContentType("text/html");
out.println("<body bgcolor='pink'>");
response.addCookie(c);
out.println("<form action='./s2'>");
out.println("</form>");
out.println("</body>");
}
Servlet2.java:
package com.ram.proj1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
response)throws ServletException,IOException{
response.setContentType("text/html");
out.println("<body bgcolor='Yellow'>");
Cookie[] c1 = request.getCookies();
System.out.println(c1);
if(c1==null){
else{
out.println("<form action='./s3'>");
out.println("</form>");
out.println("</body>");
Servlet3.java:
package com.ram.proj1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet3 extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='Yellow'>");
Cookie[] c1 = request.getCookies();
System.out.println(c1);
if(c1==null){
out.println(" You are not recongized as same
client......");
}
else{
String name = c1[0].getValue();
Web.xml:
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>com.ram.proj1.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>com.ram.proj1.Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s3</servlet-name>
<servlet-class>com.ram.proj1.Servlet3</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s3</servlet-name>
<url-pattern>/s3</url-pattern>
</servlet-mapping>
</web-app>
In the above program we are always using same request and
response objects.
User.html:
<html>
<body bgcolor='red'>
<form action='./fs'>
Enter Your Name: <input type='text'
name='name'/><br/>
Enter Your Password: <input
type='password' name='password'/><br/>
<input type='submit' value='submit'/>
</form>
</body>
</html>
FirstServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
throws ServletException,IOException{
response.setContentType("text/html");
out.println("<body bgcolor='pink'>");
if(password.equals("suji")){
out.println("Mr. "+name);
out.println("<form action='./ss'>");
out.println("<input type='submit'
value='submit'/>");
out.println("</form>");
else{
out.println("sorry your password incorrect....");
request.getRequestDispatcher("./user.html").include(request,
response);
out.println("</body>");
SecondServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
throws ServletException,IOException{
response.setContentType("text/html");
out.println("<body bgcolor='pink'>");
out.println("</body>");
Web.xml:
<web-app>
<servlet>
<servlet-name>fs</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ss</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ss</servlet-name>
<url-pattern>/ss</url-pattern>
</servlet-mapping>
</web-app>
How to disable cookies in browser:
Web.xml:
<web-app>
<servlet>
<servlet-name>cs1</servlet-name>
<servlet-class>CookieServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cs1</servlet-name>
<url-pattern>/cs1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>cs2</servlet-name>
<servlet-class>CookieServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cs2</servlet-name>
<url-pattern>/cs2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>user.html</welcome-file>
</welcome-file-list>
</web-app>
CookieServlet1.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
response)
throws ServletException,IOException{
response.setContentType("text/html");
out.println("<body bgcolor='pink'>");
out.println("<form action='./cs2'>");
out.println("<input type='submit'
value='submit'></center>");
out.println("</form>");
out.println("</body>");
CookieServlet2.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
response)throws ServletException,IOException{
response.setContentType("text/html");
out.println("<body bgcolor='yellow'>");
Cookie[] c= request.getCookies();
int i=0;
if(c!=null) {
while(i<c.length) {
out.println(c[i].getName()+"..."+c[i].getValue()+"<br/>");
i=i+1;
else {
out.println("</body>");
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
HttpServletResponse res)
out.println("<input
type='submit'value='submit'/><br/>");
out.println("</form>");
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
HttpServletResponse res)
res.setContentType("text/html");
out.println("Servlet-Hidden: "+username);
}
<html>
<body bgcolor='Yellow'>
<form action="./s1">
Enter Name:<input type='text' name='name'/><br/>
<input type='submit' value='CLICK'/>
</form>
</body>
</html>
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
HttpServletResponse res)
res.setContentType("text/html");
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
HttpServletResponse res)
res.setContentType("text/html");
out.println("Servlet-Hidden: "+username);
}
}
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
<html>
<body bgcolor='Yellow'>
<form action="./s1">
Enter Name:<input type='text' name='name'/><br/>
<input type='submit' value='CLICK'/>
</form>
</body>
</html>
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;
@Override
HttpServletResponse res)
res.setContentType("text/html");
session.setAttribute("enduser",username);
RequestDispatcher rd =
req.getRequestDispatcher("./s2");
rd.forward(req, res);
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;
@Override
HttpServletResponse res)
res.setContentType("text/html");
String enduserName =
(String) session.getAttribute("enduser");
out.println("servlet2-session: "+enduserName);
}
}
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
<html>
<body bgcolor='Yellow'>
<form action="./s1">
Enter Name:<input type='text' name='name'/><br/>
<input type='submit' value='CLICK'/>
</form>
</body>
</html>
Filter:
--> Is one java object(JEE).
--> Is one web component is usesd for
developing web application like servlet and jsp
--> It is one servlet container/server managed
java object.
--> Like Servlet, Filter is also having life cycle
methods.
like init(-)
destroy()
doFilter(-,-,-)
All the above methods are calling by ServletContainer.
Thats why we are calling filter is one servlet container
managed object.
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
public void init(FilterConfig fc )throws
ServletException{
System.out.println("filter - init method");
}
@Override
public void doFilter(ServletRequest requst,
ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
System.out.println("doFilter method");
}
@Override
public void destroy(){
System.out.println("destroy method-filter");
}
}
Web.xml:
<web-app>
<filter>
<filter-name>mf</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>mf</filter-name>
<url-pattern>/mf</url-pattern>
</filter-mapping>
</web-app>
Program on Filter to provide response to browser:
Input.html:
<html>
<body bgcolor='yellow'>
<form action='./mf'>
<input type='submit' value='SUBMIT'/>
</form>
</body>
</html>
MyFilter.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MyFilter implements Filter {
FilterConfig fc=null;
@Override
public void init(FilterConfig fc )throws
ServletException{
System.out.println("filter - init method");
System.out.println("fc: "+fc);
this.fc = fc;
}
@Override
public void doFilter(ServletRequest requst,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
System.out.println("doFilter method");
String fno = fc.getInitParameter("fno");
String sno = fc.getInitParameter("sno");
int i = Integer.parseInt(fno);
int j = Integer.parseInt(sno);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor='yellow'>The
Result is: "
+(i+j)+"</body>");
}
@Override
public void destroy(){
System.out.println("destroy method-filter");
}
}
Web.xml
<web-app>
<filter>
<filter-name>mf</filter-name>
<filter-class>MyFilter</filter-class>
<init-param>
<param-name>fno</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>sno</param-name>
<param-value>200</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>mf</filter-name>
<url-pattern>/mf</url-pattern>
</filter-mapping>
</web-app>
Proramming on filter:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
public void destroy() {
System.out.println("Filter destroy()");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("Filter doFilter()");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("file executing before servlet<br/>");
chain.doFilter(req, res);
out.println("file executing after servlet<br/>");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("Filter init()");
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("MyServlet is processing the request<br/>");
<web-app>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping>
<filter>
<filter-name>mf</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>mf</filter-name>
<url-pattern>/ms</url-pattern>
</filter-mapping>
</web-app>
<form action="./ms">
<input type='submit' value='submit'/>
</form>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MyFilter implements Filter {
@Override
public void destroy() {
System.out.println("Filter destroy()");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("Filter doFilter()");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("file executing before servlet<br/>");
String username = req.getParameter("username");
String password = req.getParameter("password");
if(password.equals("ramchandra")){
System.out.println("if");
chain.doFilter(req, res);
}
else{
System.out.println("else");
RequestDispatcher rd = req.getRequestDispatcher("./test.html");
rd.include(req,res);
}
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
res.setContentType("text/html");
}<body bgcolor='yellow'>
<form action="./ms">
Enter UserName: <input type='text' name='username'/><br/>
Enter Password: <input type='password' name='password'/><br/>
<input type='submit' value='submit'/>
</form>
</body>
<web-app>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping>
<filter>
<filter-name>mf</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>mf</filter-name>
<url-pattern>/ms</url-pattern>
</filter-mapping>
</web-app>
<body bgcolor='yellow'>
<form action="./ms">
Enter UserName : <input type='text' name='username'/><br/>
Enter Password : <input type='password' name='password'/><br/>
Enter Employee Id: <input type='text' name='eid'/><br/>
Enter Employee Name:<input type ='text' name='ename'/><br/>
Enter Employee Sal: <input type='text' name='esal'/><br/>
Enter Employee Dept: <input type='text' name="edept"/>
<input type='submit' value='submit'/>
</form>
</body>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
System.out.println("Filter destroy()");
@Override
System.out.println("Filter doFilter()");
res.setContentType("text/html");
if(username.equals("yaane") &&
password.equals("ramchandra")){
System.out.println();
chain.doFilter(req, res);
else{
System.out.println("else");
RequestDispatcher rd = req.getRequestDispatcher("./test.html");
rd.include(req,res);
}
@Override
System.out.println("Filter init()");
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
Connection con;
Statement st;
@Override
System.out.println("sc: "+sc);
String driver = sc.getInitParameter("driver1");
System.out.println("driver: "+driver);
try {
Class.forName(driver);
con =
DriverManager.getConnection(url,username,password);
st = con.createStatement();
catch (ClassNotFoundException e) {
System.out.println("catch block-CNFE");
e.printStackTrace();
catch (SQLException e) {
System.out.println("catch block-SQL");
e.printStackTrace();
@Override
res.setContentType("text/html");
try {
catch (SQLException e) {
System.out.println("service-catch");
Or
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
Connection con;
//Statement st;
@Override
System.out.println("sc: "+sc);
System.out.println("driver: "+driver);
try {
Class.forName(driver);
con = DriverManager.
getConnection(url,username,password);
//st = con.createStatement();
}
catch (ClassNotFoundException e) {
System.out.println("catch block-CNFE");
e.printStackTrace();
catch (SQLException e) {
System.out.println("catch block-SQL");
e.printStackTrace();
@Override
res.setContentType("text/html");
try {
//int updatecount=
//"+eid+",'"+ename+"',"+esal+",'"+edept+"')");
PreparedStatement ps =
con.prepareStatement(
ps.setInt(1, eid);
ps.setString(2, ename);
ps.setInt(3, esal);
ps.setString(4, edept);
catch (SQLException e) {
System.out.println("service-catch");
}
<web-app>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>driver1</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>url1</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</init-param>
<init-param>
<param-name>username1</param-name>
<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password1</param-name>
<param-value>manager</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping>
<filter>
<filter-name>mf</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>mf</filter-name>
<url-pattern>/ms</url-pattern>
</filter-mapping>
</web-app>
Those values will be inject into FilterConfig object. Later that object will be
placed into init(FilterConfig fc) of MyFilter class.
We can read these values again form our application by using one method of
FilterConfig object that is getInitParameter(-).
Special scenario:
<web-app>
<filter>
<filter-name>first</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>first</filter-name>
<!-- <url-pattern>/ms</url-pattern> -->
<servlet-name>fms</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>fms</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fms</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
html action attribute value and servlet-mapping tag url-pattern value not
match request is not forward to servlet, it will check filter url-pattern
value if match controle goes to only filter otherwise request not going
filter also.
<filter>
<filter-name>first</filter-name>
<filter-class>MyFilter1</filter-class>
</filter>
<filter>
<filter-name>second</filter-name>
<filter-class>MyFilter2</filter-class>
</filter>
<filter-mapping>
<filter-name>second</filter-name>
<url-pattern>/ms</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>first</filter-name>
<url-pattern>/ms</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>fms</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fms</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Filter execution order depend upon <filter-mapping> tag order in web.xml file
from top to bottom.
<web-app>
<filter>
<filter-name>first</filter-name>
<filter-class>MyFilter1</filter-class>
</filter>
<filter>
<filter-name>second</filter-name>
<filter-class>MyFilter2</filter-class>
</filter>
<filter-mapping>
<filter-name>second</filter-name>
<servlet-name>fms</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>first</filter-name>
<url-pattern>/ms</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>fms</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fms</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Container always gives first preference to <url-pattern> only later <Servlet-
name> in this time <filter-mapping> order not usefull.
How to make relation between multiple filter to Servlet individually:
<web-app>
<filter>
<filter-name>first</filter-name>
<filter-class>MyFilter1</filter-class>
</filter>
<filter-mapping>
<filter-name>first</filter-name>
<url-pattern>/ms</url-pattern>
</filter-mapping>
<filter>
<filter-name>second</filter-name>
<filter-class>MyFilter2</filter-class>
</filter>
<filter-mapping>
<filter-name>second</filter-name>
<url-pattern>/fms</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>fms</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fms</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>fms</servlet-name>
<url-pattern>/fms</url-pattern>
</servlet-mapping>
</web-app>
Listeners
Programon listener:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("servletcontext is destroyed");
ServletContext sc = arg0.getServletContext();
sc.removeAttribute("name");
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("servletcontext is created");
ServletContext sc = arg0.getServletContext();
sc.setAttribute("name", "ram");
}
<web-app>
<listener>
<listener-class> ServletContextHandler</listener-class>
</listener>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
Program on Listener with DB:
Web.xml:
<web-app>
<welcome-file-list>
<welcome-file>Testing.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>DBListener</listener-class>
</listener>
<servlet>
<servlet-name>ss</servlet-name>
<servlet-class>SelectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ss</servlet-name>
<url-pattern>/ss</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>is</servlet-name>
<servlet-class>InsertServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>is</servlet-name>
<url-pattern>/is</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>us</servlet-name>
<servlet-class>UpdateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>us</servlet-name>
<url-pattern>/us</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ds</servlet-name>
<servlet-class>DeleteServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>/ds</url-pattern>
</servlet-mapping>
</web-app>
Testing.html:
<html>
<body bgcolor='black'>
<form action='./ss'>
<input type='submit' value='SELECT'/>
</form>
<form action='./is'>
<input type='submit' value='INSERT'/>
</form>
<form action='./us'>
<input type='submit' value='UPDATE'/>
</form>
<form action='./ds'>
<input type='submit' value='DELETE'/>
</form>
</body>
</html>
DBListener.java:
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe"
,"system",
"annie");
sc.setAttribute("connection", con);
} catch (Exception e) {
System.out.println("=================");
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent
event) {
System.out.println("destroyed method
executing");
try {
if(con!=null) {
con.close();
}
}catch(Exception e) {
System.out.println("****************");
}
}
}
SelectServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
try {
ServletContext sc =
request.getServletContext();
Connection con = (Connection)
sc.getAttribute("connection");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from
sbaj9to11");
while(rs.next()) {
out.println(rs.getInt(1)+"-----"+rs.getString(2)+"----"+
rs.getInt(3)+"----"+rs.getInt(4)+"<br/>");
}
} catch (SQLException e) {
e.printStackTrace();
}
out.println("</body>");
}
}
InsertServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
try {
ServletContext sc =
request.getServletContext();
Connection con = (Connection)
sc.getAttribute("connection");
Statement st = con.createStatement();
int count = st.executeUpdate(
"insert into sbaj9to11
values(104,'annie',25,4000)");
out.println(count+"Record inserted......");
} catch (SQLException e) {
e.printStackTrace();
}
out.println("</body>");
}
}
UpdateServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
IOException{
response.setContentType("text/html");
out.println("<body bgcolor='yellow'>");
try {
ServletContext sc = request.getServletContext();
Statement st = con.createStatement();
int count = st.executeUpdate(
out.println(count+".record updated");
} catch (SQLException e) {
e.printStackTrace();
out.println("</body>");
DeleteServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
FilterConfig config;
@Override
public void destroy() {
System.out.println("Filter destroy()");
@Override
System.out.println("Filter doFilter()");
res.setContentType("text/html");
out.println("myname: "+myname+"</br>");
chain.doFilter(req, res);
@Override
throws ServletException {
System.out.println("Filter init()");
config = fc;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
res.setContentType("text/html");
}
<web-app>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping>
<filter>
<filter-name>mf</filter-name>
<filter-class>MyFilter</filter-class>
<init-param>
<param-name>myname</param-name>
<param-value>ramchandra</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>mf</filter-name>
<url-pattern>/ms</url-pattern>
</filter-mapping>
</web-app>
ServletContextEventHandler.java:
package com.aj.lsnr;
import javax.servlet.*;
public class ServletContextEventHandler
implements
ServletContextListener{
@Override
public void
contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed
method");
ServletContext sct =
sce.getServletContext();
sct.removeAttribute("faculty");
}
@Override
public void
contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitializedmethodm
starts");
ServletContext sct =
sce.getServletContext();
sct.setAttribute("faculty",
"ramchandra");
System.out.println("contextInitializedmethodm
ends");
}
}
ServletRequestEventHandler.java:
package com.aj.lsnr;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class ServletRequestEventHandler
implements
ServletRequestListener{
@Override
public void
requestDestroyed(ServletRequestEvent sre) {
System.out.println("RequesttDestroyed
method-requst");
ServletRequest sr =
sre.getServletRequest();
sr.removeAttribute("fage");
}
@Override
public void
requestInitialized(ServletRequestEvent sre) {
System.out.println("RequestInitializedmethodm
starts-request");
ServletRequest sr =
sre.getServletRequest();
sr.setAttribute("fage", "30");
System.out.println("RequestInitializedmethodm
ends-request");
}
}
HttpSessionEventHandler.java”:
package com.aj.lsnr;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.catalina.SessionEvent;
public class HttpSessionEventHandler implements
HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent
hse) {
System.out.println("sessioncreated
starts");
HttpSession hs = hse.getSession();
hs.setAttribute("fsal", "7000");
System.out.println("sessioncreated
ends");
}
@Override
public void
sessionDestroyed(HttpSessionEvent hse) {
System.out.println("sessiondestroyed");
HttpSession hs = hse.getSession();
hs.removeAttribute("fsal");
}
}
ReadListenerServlet.java:
/* aathor = "ram"
* version= 1.8
* insttute=nit
*/
package com.aj.lsnr;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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 ReadListenerServlet extends
HttpServlet{
@Override
public void doGet(HttpServletRequest
request,
HttpServletResponse response)throws
ServletException,
IOException{
System.out.println("doGet method");
ServletContext sct =
getServletContext();
String facultyname =
(String)sct.getAttribute("faculty");
System.out.println("facultyname:
"+facultyname);
String fage =
(String)request.getAttribute("fage");
System.out.println("fage: "+fage);
HttpSession hs = request.getSession();
String fsal =
(String)hs.getAttribute("fsal");
System.out.println("fsal: "+fsal);
}
}
Web.xml:
<web-app>
<listener>
<listener-
class>com.aj.lsnr.ServletContextEventHandler</l
istener-class>
</listener>
<listener>
<listener-
class>com.aj.lsnr.ServletRequestEventHandler</l
istener-class>
</listener>
<listener>
<listener-
class>com.aj.lsnr.HttpSessionEventHandler</list
ener-class>
</listener>
<servlet>
<servlet-name>rls</servlet-name>
<servlet-
class>com.aj.lsnr.ReadListenerServlet</servlet-
class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rls</servlet-name>
<url-pattern>/rls</url-pattern>
</servlet-mapping>
</web-app>
How to develop dynamic web project without web.xml file:
a. web.xml
b. Annotation
Example:
<form action="./ts">
<input type="submit" value="go"/>
</form>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/ts")//@WebServlet(value=”/ts”)
@Override
res.setContentType("text/html");
package com.aj.lsnr;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@WebServlet("/rls")
//@WebServlet(value="/rls")
//@WebServlet({"/as","/ms"})
//@WebServlet(value={"/as1","/ms1"})
//@WebServlet("/*")
@WebServlet(loadOnStartup=1,
urlPatterns={“/as”,”/ms”}
//@WebServlet(urlPatterns={"/as","/ms"})
@WebServlet(value = "/rls", initParams = {
@WebInitParam(name = "faculty", value
= "Ramchandra"),
@WebInitParam(name = "age", value =
"...30!")
})
public class ReadListenerServlet extends
HttpServlet{
@Override
public void doGet(HttpServletRequest
request,
HttpServletResponse response)throws
ServletException,
IOException{
System.out.println("doGet
method......");
System.out.println("1.
"+getServletConfig().getInitParameter("faculty"
));
System.out.println("2.
"+getServletConfig().getInitParameter("age"));
System.out.println("3.
"+getServletContext().getInitParameter("faculty
"));
System.out.println("4.
"+getServletContext().getInitParameter("age"));
}
}
ReadListenerServlet.java:
package com.aj.lsnr;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@WebServlet("/rls")
//@WebServlet(value="/rls")
@WebServlet(value = "/rls", initParams = {
@WebInitParam(name = "faculty", value
= "Ramchandra"),
@WebInitParam(name = "age", value =
"...30!")
})
public class ReadListenerServlet extends
HttpServlet{
@Override
public void doGet(HttpServletRequest
request,
HttpServletResponse response)throws
ServletException,
IOException{
System.out.println("doGet
method......");
System.out.println("1.
"+getServletConfig().getInitParameter("faculty"
));
System.out.println("2.
"+getServletConfig().getInitParameter("age"));
System.out.println("3.
"+getServletConfig().getServletContext().getIni
tParameter("faculty"));
System.out.println("4.
"+getServletConfig().getServletContext().getIni
tParameter("age"));
}
}
MyFilter.java:
package com.aj.lsnr;
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;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
System.out.println("username: "+username);
chain.doFilter(request,response);
}
Program @WebListener:
package com.aj.lsnr;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class ServletContextEventHandler
implements
ServletContextListener{
@Override
public void
contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed
method");
ServletContext sct =
sce.getServletContext();
sct.removeAttribute("faculty");
}
@Override
public void
contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitializedmethodm
starts");
ServletContext sct =
sce.getServletContext();
sct.setAttribute("faculty",
"ramchandra");
System.out.println("contextInitializedmethodm
ends");
System.out.println("***********"+sct.getAttribu
te("faculty"));
}
}
ReadListenerServlet.java
package com.aj.lsnr;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name= "ReadListenerServlet",
value="/rls")
public class ReadListenerServlet extends
HttpServlet{
@Override
public void doGet(HttpServletRequest
request,
HttpServletResponse response)throws
ServletException,
IOException{
System.out.println("doGet
method......");
ServletContext sct =
getServletContext();
System.out.println("1.
"+sct.getAttribute("faculty"));
}
}
DBOperations
DBOperation.html:
<html>
<body bgcolor='yellow'>
<a href='./Select.html'>SELECT</a><br/>
<a href='./Insert.html'>INSERT</a><br/>
<a href='./Delete.html'>DELETE</a><br/>
<a href='./Update.html'>UPDATE</a><br/>
</body>
</html>
Select.html:
<html>
<body bgcolor='yellow'>
<form action='./dos' method='get'>
Enter Employee Number: <input type='text'
required name='eid'/>
<input type='submit' value='SELECT'/>
</form>
</body>
</html>
Insert.html:
<html>
<body bgcolor='yellow'>
<form action='./dos' method='POST'>
Enter Employee Number: <input type='text'
required name='eid'/><br/>
Enter Employee Name : <input type='text'
required name='ename'/><br/>
Enter Employee Salary: <input type='text'
required name='esal'/><br/>
Enter Employee age : <input type='text'
required name='eage'/><br/>
<input type='submit' name='btn'
value='INSERT'/>
</form>
</body>
</html>
Delete.html:
<html>
<body bgcolor='yellow'>
<form action='./dos' method='post'>
Enter Employee Number: <input type='text' required
name='eid'/>
<input type='submit' name='btn'
value='DELETE'/>
</form>
</body>
</html>
Update.html:
<html>
<body bgcolor='yellow'>
<form action='./dos' method='post'>
Enter Employee Number: <input type='text'
required name='eid'/>
Enter Employee Update Sal: <input type='text'
required name='esal'/>
<input type='submit' name='btn'
value='UPDATE'/>
</form>
</body>
</html>
Web.xml:
<web-app>
<servlet>
<servlet-name>dos</servlet-name>
<servlet-class>DBOServletDemo</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-
value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-
value>jdbc:oracle:thin:@localhost:1521:xe</param-
value>
</init-param>
<init-param>
<param-name>user</param-name>
<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>manager</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dos</servlet-name>
<url-pattern>/dos</url-pattern>
</servlet-mapping>
</web-app>
DBOServletDemo.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Connection con=null;
@Override
System.out.println("driver :"+driver);
System.out.println("url :"+url);
System.out.println("user :"+user);
System.out.println("password:"+password);
try{
System.out.println("try of init");
Class.forName(driver);
con=DriverManager.getConnection(url,user,password);
System.out.println("con: "+con);
}catch(Exception e){
e.printStackTrace();
}
@Override
response)throws ServletException,IOException{
response.setContentType("text/html");
try{
System.out.println("try of doGet");
PreparedStatement ps = con.prepareStatement(
ps.setInt(1, eid);
ResultSet rs = ps.executeQuery();
while(rs.next()){
out.println(rs.getInt(1)+"\t"+rs.getString(2)+
"\t"+rs.getInt(3)+"\t"+rs.getInt(4));
}catch(Exception e){
e.printStackTrace();
}
@Override
response)throws ServletException,IOException{
response.setContentType("text/html");
if(operation.equalsIgnoreCase("insert")){
try {
PreparedStatement ps =
ps.setInt(1, eid);
ps.setString(2, ename);
ps.setInt(3, esal);
ps.setInt(4, eage);
int count=ps.executeUpdate();
out.println(count+".records inserted");
} catch (SQLException e) {
System.out.println("catch of dopost-insert");
e.printStackTrace();
}
else if(operation.equalsIgnoreCase("delete")){
try {
ps.setInt(1, eid);
int count=ps.executeUpdate();
System.out.println(count+".records deleted");
} catch (SQLException e) {
e.printStackTrace();
else if(operation.equalsIgnoreCase("update")){
try {
ps.setInt(1, usal);
ps.setInt(2, eid);
int count=ps.executeUpdate();
System.out.println(count+".records updated");
} catch (SQLException e) {
e.printStackTrace();
Add.html:
<html>
<body bgcolor='yellow'>
<form action='./as' method='GET'>
Enter First Number: <input type='text'
name='fno'/><br/>
Enter Second Number: <input type='text'
name='sno'/><br/>
<input type='submit' value='ADD'/>
</form>
</body>
</html>
Web.xml:
<web-app>
<servlet>
<servlet-name>as</servlet-name>
<servlet-class>AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>as</servlet-name>
<url-pattern>/as</url-pattern>
</servlet-mapping>
</web-app>
AddServlet.java:
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;
<html>
<body bgcolor='wheat'>
<form action='./ls'>
Enter Your UserName:<input type='text'
name='username'/><br/>
Enter your Password:<input type='password'
name='password'/><br/>
Supplier<input type='radio' name='radio'
value='supplier'/>
Consumer<input type='radio' name='radio'
value='consumer'/>
<input type='submit' value='submit'
</form>
</body>
</html>
LoginServlet.java:
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
RequestDispatcher rd = null;
out.println("<html>");
out.println("<body bgcolor='yellow'>");
String username =
request.getParameter("username");
String password =
request.getParameter("password");
String role = request.getParameter("radio");
out.println("</body>");
out.println("</html>");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>ls</servlet-name>
<servlet-
class>controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ls</servlet-name>
<url-pattern>/ls</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>
</web-app>
Login.jsp:
<html>
<body bgcolor='wheat'>
<form action='./ls'>
Enter Your UserName:<input type='text'
name='username'/><br/>
Enter your Password:<input type='password'
name='password'/><br/>
Supplier<input type='radio' name='radio'
value='supplier'/>
Consumer<input type='radio' name='radio'
value='consumer'/>
<input type='submit' value='submit'
</form>
</body>
</html>
LoginServlet.java:
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import Model.CheckUserModel;
response.setContentType("text/html");
RequestDispatcher rd = null;
out.println("<html>");
out.println("<body bgcolor='yellow'>");
System.out.println("role: "+role+".....");
model.setUsername(username);
model.setPassword(password);
model.setRole(role);
rd = request.getRequestDispatcher("./Login.jsp");
rd.include(request, response);
else
rd =
request.getRequestDispatcher("./Login.jsp");
rd.include(request, response);
rd = request.getRequestDispatcher("./Login.jsp");
rd.include(request, response);
else
if(result.equals("supplier")){
out.println("<h2>welcome
Supplier<br/>");
else if(result.equals("consumer")){
out.println("<h2>welcome
Consumer<br/>");
rd =
request.getRequestDispatcher("./Login.jsp");
rd.include(request, response);
rd =
request.getRequestDispatcher("./Login.jsp");
rd.include(request, response);
out.println("</body>");
out.println("</html>");
CheckUserModel.java:
package Model;
public class CheckUserModel {
private String username;
private String password;
private String role;
Web.xml:
<web-app>
<servlet>
<servlet-name>ls</servlet-name>
<servlet-
class>controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ls</servlet-name>
<url-pattern>/ls</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>
</web-app>
Cos.jar
uploadBean.jar
Struts.jar file
MultiPartFormDataRequest:
UploadBean:
UploadFile:
Upload.html:
<html>
<head>
<title>THIS IS UPLOAD FILE CONCEPT</title>
</head>
<body bgcolor='yellow'>
<h1>WELCOME TO OUR WEBSITE::UPLOAD.HTML </h1>
<form action='uplurl' method='Post'
enctype="multipart/form-data">
Choose First File: <input type='file' name='file1'/>
<br/>
Choose Second File: <input type='file' name='file2'/>
<br/>
<input type='submit' value="upload"/>
</form>
</body>
</html>
UplServlet.java:
package com.kit;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javazoom.upload.MultipartFormDataRequest;
import javazoom.upload.UploadBean;
import javazoom.upload.UploadException;
import javazoom.upload.UploadFile;
@Override
throws ServletException,IOException{
PrintWriter pw =null;
MultipartFormDataRequest nreq=null;
Hashtable ht = null;
Enumeration e = null;
pw=res.getWriter();
try {
upb.setFolderstore("C:/store");
upb.setOverwrite(false);
upb.store(nreq);
ht=nreq.getFiles();
e=ht.elements();
while(e.hasMoreElements()){
pw.println("<br/>"+file.getFileName()+"
"+file.getFileSize());
}
} catch (UploadException e1) {
e1.printStackTrace();
Web.xml:
<web-app>
<servlet>
<servlet-name>uplurl</servlet-name>
<servlet-
class>com.kit.UplServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uplurl</servlet-name>
<url-pattern>/uplurl</url-pattern>
</servlet-mapping>
</web-app>
File Downloading:
a. Resource Downloading
b. Response/output downloading.
Index.html:
<body bgcolor='yellow'>
<form action='./downloadurl'>
<input type='submit' value='download'/>
</form>
</body>
DownloadServlet.java:
package com.kit;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet{
@Override
public void doPost(HttpServletRequest
req,HttpServletResponse res)
throws ServletException,IOException{
ServletContext sc = null;
File file = null;
String path=null;
long length=0;
String mimeType=null;
ServletOutputStream sos=null;
InputStream is = null;
byte[] buffer = new byte[4096];
int bytesRead=0;
sc = getServletContext();
path=sc.getRealPath("/ram.jpeg");
file = new File(path);
length = file.length();
res.setContentLengthLong(length);
mimeType=sc.getMimeType("/ram.jpeg");
res.setContentType(mimeType);
res.setHeader("content-disposition",
"attachment;fileName=ram.jpeg");;
is=sc.getResourceAsStream("/ram.jpeg");
sos = res.getOutputStream();
while((bytesRead=is.read(buffer))!=-1){
sos.write(buffer,0,bytesRead);
}is.close();sos.close();
}
@Override
public void doGet(HttpServletRequest
req,HttpServletResponse res)
throws ServletException,IOException{
doPost(req,res);
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>downloadurl</servlet-
name>
<servlet-
class>com.kit.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>downloadurl</servlet-
name>
<url-pattern>/downloadurl</url-
pattern>
</servlet-mapping>
</web-app>
GetData.html:
<body bgcolor='yellow'>
<a href='./gd'>GETDATA</a>
</body>
Web.xml:
<web-app>
<servlet>
<servlet-name>gs</servlet-name>
<servlet-class>com.nit.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gs</servlet-name>
<url-pattern>/gd</url-pattern>
</servlet-mapping>
</web-app>
GetServlet.java:
package com.nit;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
Db.properties:
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
user=system
password=manager
Without connection pooling:
user.html:
<body bgcolor='yellow'>
<form action='./gd'>
Enter username: <input type='text' name="un"/>
Enter password: <input type='text' name='psd'/>
<input type='submit' value='submit'/>
</form>
</body>
=================
GetServlet:
package com.nit;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
} catch (Exception e) {
System.out.println("-----------------");
e.printStackTrace();
}
}
}
LoginDao:
package com.nit;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:152
1:xe",
"system","manager");
}
catch(Exception e){
System.out.println("================");
}
return con;
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>gs</servlet-name>
<servlet-class>com.nit.GetServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>gs</servlet-name>
<url-pattern>/gd</url-pattern>
</servlet-mapping>
</web-app>
</Context>
GetData.html:
<body bgcolor='yellow'>
<form action='./gd'>
Enter username: <input type='text'
name="un"/><br/>
Enter password: <input type='text'
name='psd'/><br/>
<input type='submit' value='submit'/>
</form>
</body>
GetServlet.java:
package com.nit;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
RequestDispatcher rd = null;
HttpSession session=request.getSession();
PrintWriter out =null;
try {
response.setContentType("text/html");
out = response.getWriter();
String username = request.getParameter("un");
String passwords=request.getParameter("psd");
session.setAttribute("user", username);
if(LoginDao.validate(username, passwords)){
System.out.println("user valid");
rd=request.getRequestDispatcher("./welcome.jsp");
rd.forward(request, response);
}
else {
System.out.println("invalid user");
out.println("Your username and password
are invalid");
rd=request.getRequestDispatcher("./GetData.html");
rd.include(request, response);
}
} catch (Exception e) {
System.out.println("-----------------");
e.printStackTrace();
}
}
}
LoginDao.java:
package com.nit;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
(DataSource)context.lookup("java:comp/env/jdbc/UsersD
B");
con = ds.getConnection();
}
catch(Exception e){
e.printStackTrace();
System.out.println("================");
}
return con;
}
}
Context.xml under META-INF:
<Context>
<Resource
name="jdbc/UsersDB"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="100000"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe"
username="system"
password="manager"/>
</Context>
Welcome.jsp:
<html>
<body bgcolor='yellow'>
<form>
<%String username =
(String)session.getAttribute("user"); %>
Your are Valid User mr:
<%=username %>.......
</form>
</body>
</html>
Web.xml:
<web-app>
<servlet>
<servlet-name>gs</servlet-name>
<servlet-class>com.nit.GetServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>gs</servlet-name>
<url-pattern>/gd</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>GetData.html</welcome-file>
</welcome-file-list>
</web-app>
Logintable:
Create table login(username varchar2(20),password
varchar2(20);
Commit;
Insert into login values(‘ram’,’kiran’);
Commit;
Cold Deployment:
Web.xml:
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>com.ram.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Authentication</web-
resource-name>
<url-pattern>/s1</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>clerk</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<!-- <auth-method>BASIC</auth-method> -->
<auth-method>DIGEST</auth-method>
<realm-name>myrealm</realm-name>
</login-config>
</web-app>
FORM:
</form>
</body>
</html>
Login_fail.jsp:
<html>
<body bgcolor='wheat'>
<blockquote>BOTH USERNAME AND PASSWORDS ARE NOT
MATCH</blockquote>
<a href='./login.jsp'>REENTER USERNAME AND
PASSWORD</a>
</body>
</html>
Edit.jsp:
<html>
<body bgcolor='wheat'>
<form>
<center><b>
<%
out.println("the username is:
"+request.getRemoteUser()+"<br/>");
%>
login sucessfull.....welcome to home
page</b></center>
</form>
</body>
</html>
Web.xml:
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<jsp-file>/edit.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Authentication</web-
resource-name>
<url-pattern>/test2</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>clerk</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-
page>
<form-error-page>/login_fail.jsp</form-
error-page>
</form-login-config>
<realm-name>myrealm</realm-name>
</login-config>
</web-app>
Input.html:
<html>
<head>
<script lang="javascript"
src="validation.js"></script>
</head>
<form action='voteurl' onsubmit="return
validate(this)">
person name: <input type='text'
name="pname"/>
<span id="nameErr"></span><br/>
person age : <input type='text' name="page"/>
<span id="ageErr"></span><br/>
<input type='hidden' value="no"
name="vflag"/><br/>
<input type='submit' value='check
eligibity'/>
</form>
</html>
Validation.js:
function validate(frm){
//frm.vflag.value="yes";
document.getElementById("nameErr").style="color:red";
document.getElementById("ageErr").style="color:red";
var name = frm.pname.value;
var age = frm.page.value;
if(name==""){
document.getElementById("nameErr").innerHTML="person
name is mandatory";
frm.pname.focus();
document.getElementById("ageErr").innerHTML="person
age is mandatory";
frm.page.focus();
document.getElementById("ageErr").innerHTML="person
age is must be numeric";
frm.page.focus();
return false;
}
}
return true;
}
VoterServlet.java:
package com.ram;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class VoterServlet extends GenericServlet{
@Override
public void service(ServletRequest request,
ServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String hvalue= request.getParameter("vflag");
System.out.println("hvalue: "+hvalue);
String name = request.getParameter("pname");
String age = request.getParameter("page");
System.out.println("name: "+name);
System.out.println("age: "+age);
int cage=0;
if(hvalue.equals("no")){
System.out.println("*****************");
if(name==""){
out.println("person name is mandatory");
return;
}
if(age==""){
out.println("person age is mandatory");
return;
}
else {
try{
cage=Integer.parseInt(age);
}catch(Exception e){
out.println("person age should be in numerics");
}
}
}
else{
if(age!="")
cage = Integer.parseInt(age);
}
if(cage>=18){
out.println("You hava eligibity for voting");
}
else{
out.println("You doesn't have eligibity for voting");
}
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>com.ram.VoterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/voteurl</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>
What difference between javascript and java:
Don’t compare these two languages, the reason both
are not programming language. But still if we want to
differenciate then we can give following information.
Java script is a scripting language, which is given
netscape, this is apply this language on
webapplications only,to execute javascript programs
we required java script engine.
Java is a programming language, which is given by
sunmicro systems, this is useful for developing all
type of applications, to execute the java programs we
required jvm.
Q) How many ways can able to doing validations?
A)There are four ways.
a. Only doing validation in browser or client
side:If browser supports scriprting code, validation
are happened at browser so we can improve performance
of server. If browser not supports scripting code,
then at server side, we are facing problems,
unnecessarly network calls are wasted.
b. only doing validation at server side:
If validation are valid then not a problem at
server side, if validation are failure unneccessarly
wasted network calss and server performance.
c. Doing validation at both client and server side:
Performance is going to reduce.
d.Doing validation at both client and server side
with information by using hidden form field.
1.If client side validation are successfully happen
then give the information to server for avoiding
validation at server side
2.If client side validation are failure then
provide information to server for doing
validations at server side.
<form action="loginurl">
username: <input type="text"
name="tuname"><br/>
password: <input type="text"
name="tpwd"><br/>
<input type='submit' value='login'/>
</form>
</center>
</body>LoginServlet.java:
package com.ram.servlet;
import java.io.IOException;
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;
public class LoginServlet extends HttpServlet{
public void doGet(HttpServletRequest
req,HttpServletResponse res)
throws ServletException,IOException{
HttpSession session =
req.getSession(true);
String un =
req.getParameter("tuname");//ram
String pw =
req.getParameter("tpwd");//ram
if(un != null && pw != null)
if(un.equals("admin")&&pw.equals("admin")) {
session.setAttribute("loggedin",
"ok");
RequestDispatcher rd =
req.getRequestDispatcher("./adminurl");
rd.forward(req, res);
}
else {
RequestDispatcher rd =
req.getRequestDispatcher("login.html");
rd.forward(req, res);
}
}
}
AdminServlet.java:
package com.ram.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;
</body>
</html>
FormServlet.java
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;
out.println("Qualification:
"+request.getParameter("qlfy")+"<br/>");
String crs[] =
request.getParameterValues("crs");
String hb[] =
request.getParameterValues("hb");
out.println("courses:
"+java.util.Arrays.toString(crs)+"<br/>");
out.println("hobbies:
"+java.util.Arrays.toString(hb)+"<br/>");
int age =
Integer.parseInt(request.getParameter("tage"));
String gender=request.getParameter("gen");
if(gender.equalsIgnoreCase("m")) {
if(age>12) {
out.println("you are boy");
}
if(age>=13 && age<=19) {
out.println("you are teenage boy");
}
if(age>=20) {
out.println("you are elder boy");
}
}else {
if(age>12) {
out.println("you are girl");
}
if(age>=13 && age<=19) {
out.println("you are teenage girl");
}
if(age>=20) {
out.println("you are elder girl");
}
}
out.println("</form>");
out.println("</body>");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>furl</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>furl</servlet-name>
<url-pattern>/furl</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>form.html</welcome-file>
</welcome-file-list>
</web-app>
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:152
1:xe","system",
"manager");
PreparedStatement ps =
con.prepareStatement(
"insert into sbaj11to01 values(?,?,?,?,?)");
ps.setInt(1, sbo.getSid());
ps.setString(2, sbo.getSname());
ps.setInt(3,sbo.getSage());
ps.setInt(4, sbo.getSfee());
ps.setString(5, sbo.getScourse());
int count=ps.executeUpdate();
System.out.println(count+".records
inserted");
} catch (Exception e) {
System.out.println("catch blcok in
dto");
e.printStackTrace();
}
}
}
FrontController.java:
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@Override
public void service(ServletRequest request,
ServletResponse
response) throws ServletException,
IOException {
String sid = request.getParameter("sid");
String sname = request.getParameter("sname");
String sage = request.getParameter("sage");
String sfee = request.getParameter("sfee");
String scourse =
request.getParameter("scourse");
System.out.println("111111111111111111111");
StudentVO svo = new StudentVO();
svo.setSid(sid);
svo.setSname(sname);
svo.setSage(sage);
svo.setSfee(sfee);
svo.setScourse(scourse);
System.out.println("222222222222222222222222");
ServletContext sct =
request.getServletContext();
sct.setAttribute("svo", svo);
RequestDispatcher rd =
request.getRequestDispatcher("./bs");
rd.include(request, response);
StudentBO sbo =
(StudentBO)sct.getAttribute("sbo");
StudentDTO sdt = new StudentDTO();
sdt.insert(sbo);
}
}
BusineServlet.java:
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
System.out.println("333333333333333333333333");
String ss= svo.getSid();
System.out.println("ss: "+ss);
int sid = Integer.parseInt(ss);
String sname = svo.getSname();
int sage = Integer.parseInt(svo.getSage());
int sfee = Integer.parseInt(svo.getSfee());
String scourse = svo.getScourse();
StudentBO sbo = new StudentBO();
sbo.setSid(sid);
sbo.setSname(sname);
sbo.setSage(sage);
sbo.setSfee(sfee);
sbo.setScourse(scourse);
System.out.println("sct: "+sct.hashCode());
sct.setAttribute("sbo", sbo);
}
}
Stuentinfo.html:
<html>
<body bgcolor='yellow'>
<form action='./fc'>
Enter Your Id: <input type='text'
name='sid'/><br/>
Enter Your Name: <input type='text'
name='sname'/><br/>
Enter Your Age: <input type='text'
name='sage'/><br/>
Enter Your Fee: <input type='text'
name='sfee'/><br/>
Enter Your Course: <input type='text'
name='scourse'/>
<br/>
<input type='submit' value='submit'/>
</form>
</body>
</html>
Web.xml
<web-app>
<servlet>
<servlet-name>fc</servlet-name>
<servlet-class>FrontController</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>fc</servlet-name>
<url-pattern>/fc</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>bs</servlet-name>
<servlet-class>BusinessServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>bs</servlet-name>
<url-pattern>/bs</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>studentinfo.html</welcome-file>
</welcome-file-list>
</web-app>
<html>
<body bgcolor='orange'>
<form action="loginurl"
method="post">
User name: <input type='text'
name="uname">@gmail.com<br/>
Password: <input type='password'
name="pwd"><br/>
<input type='submit' value='login'/>
</form>
</body>
</html>
Web.xml:
<web-app>
<welcome-file-list>
<welcome-file>login.html</welcome-
file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-
class>com.nt.servlet.LoginServlet</servlet
-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginurl</url-pattern>
</servlet-mapping>
<filter>
<filter-name>log</filter-name>
<filter-
class>com.nt.filter.LoginFilter</filter-
class>
</filter>
<filter-mapping>
<filter-name>log</filter-name>
<url-pattern>/loginurl</url-pattern>
</filter-mapping>
</web-app>
LoginFilter.java:
package com.nt.filter;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.nt.wrappers.MyRequest;
import com.nt.wrappers.MyResponse;
public class LoginFilter implements Filter{
@Override
public void destroy() { }
@Override
public void doFilter(ServletRequest req ,
ServletResponse res, FilterChain chain)
throws IOException, ServletException
{
MyRequest mrequest = null;
MyResponse mresponse = null;
String output=null;
PrintWriter pw = null;
mrequest = new
MyRequest((HttpServletRequest)req);
mresponse = new
MyResponse((HttpServletResponse)res);
chain.doFilter(mrequest, mresponse);
output = mresponse.toString();
output= output+"NIT,Ameerpet";
pw=res.getWriter();
pw.print(output);
}
@Override
public void init(FilterConfig arg0) throws
ServletException { }
}
LoginServlet.java:
package com.nt.servlet;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet{
@Override
public void doGet(HttpServletRequest
req,HttpServletResponse res)
throws ServletException,IOException{
//PrintWriter pw = new PrintWriter(new
CharArrayWriter());
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
String
uname=req.getParameter("uname");//[email protected]
String pwd =
req.getParameter("pwd");//sam
System.out.println(uname+"...."+pwd);
if(uname.equals("[email protected]")&&
pwd.equals("sam")){
pw.print("<h1
style='color:red'>Valid credentials</h1>");
}
else{ pw.print("<h1
style='color:red'>InValid credentials</h1>");
}
pw.print("<a
href='./login.html'>home</a>");
System.out.println("req object
classname: "+req.getClass());
System.out.println("res object
classname: "+res.getClass());
pw.close();
}
@Override
public void doPost(HttpServletRequest
req,HttpServletResponse res)
throws ServletException,IOException{
doGet(req,res);
}
}
MyRequest.java:
package com.nt.wrappers;
import javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletRequestWrapper;
public class MyRequest extends
HttpServletRequestWrapper{
private HttpServletRequest request;//un--
>ram pd -->sam
public MyRequest(HttpServletRequest
request) {
super(request);
this.request=request;
}
@Override
public String getParameter(String name){
String value =
request.getParameter(name);
if(name.equals("uname")){
if(!value.endsWith("@gmail.com")){
return value+"@gmail.com";
}
}
return value;
}
}
MyResponse.java:
package com.nt.wrappers;
import java.io.*;
import javax.servlet.http.HttpServletResponse;
import
javax.servlet.http.HttpServletResponseWrapper;
public class MyResponse extends
HttpServletResponseWrapper{
private HttpServletResponse response;
private CharArrayWriter writer;
public MyResponse(HttpServletResponse
response) {
super(response);
this.response=response;
writer = new CharArrayWriter();
}
@Override
public PrintWriter getWriter() throws
IOException{
PrintWriter pw = new
PrintWriter(writer);
return pw;
}
@Override
public String toString(){
return writer.toString();
}
}