Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Advanced Java for MCA II/II
-1-
STREAMS
Stream: - A stream is a path traveled by data in a program. An input stream sends data from a
source into a program and an output stream sends data out of a program to a destination. File
streams can be used to input and output data as either characters or bytes. Streams that input and
output bytes to files are known as byte-based streams, Storing data in its binary format. Streams
that input and output characters to files are known as character-based streams, Storing data as a
sequence of a characters.
1. Byte-based streams: - Byte streams carry integer values that range from 0 to 255. All the
types of data can be expressed in a byte format, including numerical data, executable programs,
internet communications and byte-code produced by JVM. It consists of InputStream and
OutputStream.
The InputStream and OutputStream are used to read and write 8 bit bytes (byte streams).
Object System.in (the standard input stream object) normally enables a program to input bytes
from the keyboard; Object System.out (the standard output stream object) enables a program to
output data to the screen. ObjectInputStream and ObjectOutputStream are used for object
serialization
Hierarchy of Streams in Java Language.
The class hierarchy for input stream in java.io.
InputStream
FileInputStream
PipedInputStream
FilterInputStream
LineNumberInputStream
DataInputStream
BufferedInputStream
PushbackInputStream
ByteArrayInputStream
SequenceInputStream
StringBufferInputStream
ObjectInputStream
The class hierarchy for Output stream in java.io.
OutputStream
FileOutputStream
PipedOutputStream
FilterOutputStream
DataOutputStream
BufferedOutputStream
PushbackOutputStream
PrintStream
ByteArrayOutputStream
ObjectOutputStream
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
-2-
DataInput / Ouput Stream can only read the string in line by line. Where as another streams
reads the string in byte-by-byte.
DataInputStream can takes only the object but not string.
PrintStream class is used to read the string in line-by-line automatically. In that one of the
method is println( ) is used.
2. Character-based streams: - Character streams are a specialized type of byte streams that
handle only textual data. They are distinguished from bytes stream, because Java’s character set
supports Unicode, a standard that includes many more characters (0 to 65535) that could be
expressed easily using bytes. It consists of Reader and Writer.
Reader and Writer are abstract super classes for character streams in java.io package.
Readers and writers provide the functionality to read 16 bit character.
The class hierarchy for Readers in java.io.
Reader
BufferedReader
CharArrayReader
InputStreamReader
FileReader
FilterReader
PushBackReader
PipedReader
StringReader
The class hierarchy for Writers in java.io.
Writer
BufferedWriter
CharArrayWriter
OutputStreamWriter
FileWriter
FilterWriter
PipedWriter
StringWriter
PrintWriter
File: - A file is a group of characters or records. Generally the output of a program is not
possible to store permanently, to store the data for a long – term preservation of large amounts of
data; we have to use the files concept. Data maintained in files are called persistent data. We can
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
-3-
store the data in the file for. Before maintaining the files in java we need to create a file object by
using File class It contains 3 constructors.
1. File(String Dir) //path of the file name
2. File(String Root, String File)
// Root :- Directory path
// File: - File name
3. File(FileObject, FileName)
The File class is used to test the nature of a file as whether a given file is readable,
writable… and so on. We can also get the information about the parent details of a given file.
File class contains the following methods.
public boolean exists( )
public boolean CanRead( )
public boolean CanWrite( )
public boolean isAbsolute( )
public int available( )
public int read( )
public String getName( )
public String getAbsolute( )
public boolean isHidden( )
public String lastModified( )
public boolean isFile( )
public boolean isDirectory( )
public int length( )
public String[] list( )
public boolean makeDir ( )
public boolean renameTo( )
There are two types of file system information in java. Those are sequential files and Random
Access Files.
Sequential files: - By using these files each successive input/ output request reads or writes the
next uninterrupted set of data in the file. These are unfortunate (unsuitable) for instant – access
application in which a particular record of information must be located immediately. Popular
instant access applications such a airline reservation systems, banking systems, ATMs and other
kinds of transaction processing system require rapid access to specific data.
Random Access Files: - To achieve instant access random – access file can be accessed directly
without searching through other records; Random- access files are also called as direct - access
files. With a random – access file, each successive input/output request may be directed to any
part of the file. It provides rapid access to specific data items in large files.
These files provide the facility of appending
You can move anywhere in the content of a file.
It can read or write at any particular point, very precisely
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
-4-
Random access files requires 2 strings
1. Path
+2. Mode. ( r --- read mode .
rw --- read write
Methods of the Random Access file
public long getFilePointer( )
public void seek( byte )
returns the current position of file pointer.
jumps the cursor to the required byte.
#1. Program to display the Name, parent, attributes and the length of a given file.
import java.io.*;
public class FileTest
{
public static void main(String args[]) throws Exception
{
File f1=new File("hello.txt");
if(f1.exists())
{
System.out.println(f1.getName());
System.out.println(f1.getParent());
System.out.println(f1.canWrite());
System.out.println(f1.canRead());
System.out.println(f1.length());
}
else
System.out.println("file not existed");
}
}
#2. Program to check whether file or directory for a given file.
import java.io.*;
public class FileStream2
{
public static void main(String args[]) throws Exception
{
File f1=new File("c:/bea");
String a[]=f1.list();
int x=a.length;
System.out.println("no of dirs and files are "+ x);
for(int i=0;i<x;i++)
{
String fname=a[i];
File f2=new File(f1,fname);
if(f2.isDirectory())
System.out.println(fname+"
"+" is Directory");
if(f2.isFile())
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
System.out.println(fname+"
-5-
"+" is File");
}
}
}
#3. program on streams by using ByteArrayInputStream
import java.io.*;
public class FileStream3
{
public static void main(String args[]) throws Exception
{
String str="welcome to Streems";
byte b[]=str.getBytes();
ByteArrayInputStream bis=new ByteArrayInputStream(b);
System.out.println(bis);
int x;
while((x=bis.read())!=-1)
{
System.out.println((char)x);
}
}
}
#4. program on streams by using ByteArrayOutputStream
import java.io.*;
public class FileStream4
{
public static void main(String args[]) throws Exception
{
ByteArrayOutputStream bos=new ByteArrayOutputStream();
String str="welcome to Streems";
byte b[]=str.getBytes();
bos.write(b);
System.out.println(bos);
}
}
import java.io.*;
#5. program to copy the file from one object to another by using
ByteArrayOutputStream
public class FileStream5
{
public static void main(String args[]) throws Exception
{
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
-6-
ByteArrayOutputStream bos1=new ByteArrayOutputStream();
ByteArrayOutputStream bos2=new ByteArrayOutputStream();
String str="welcome to Streems";
byte b[]=str.getBytes();
bos1.write(b);
bos1.writeTo(bos2);
System.out.println(bos2);
}
}
#6. program to copy the contents from one file to another by using
FileInput and FileOutputStream
import java.io.*;
public class FileStream6
{
public static void main(String args[]) throws IOException
{
System.out.println("enter path and filename");
DataInputStream dis=new DataInputStream(System.in);
String path=dis.readLine();
File f1=new File(path);
FileInputStream fis=new FileInputStream(f1);
System.out.println("enter the location");
String cpath=dis.readLine();
File f2=new File(cpath);
FileOutputStream fos=new FileOutputStream(f2);
int k;
while((k=fis.read())!=-1)
{
System.out.print((char)k);
fos.write(k);
}
}
}
#7. Program to read the contents of a given files from command-line arguments
by using FileInput and FileOutputStream
import java.io.*;
public class FileStream7
{
public static void main(String args[]) throws Exception
{
if(args.length==0)
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
-7-
System.out.println("enter atleast one file");
else
{
for(int i=0;i<args.length;i++)
{
FileInputStream fis=new
FileInputStream(args[i]);
System.out.println("-------"+args[i]+"--------");
int k;
while((k=fis.read())!=-1)
{
System.out.print((char)k);
}
}
System.out.println("end of the file");
}
}
}
#8. Program to store and read the contents from a file by using DataInput and
DataOutputStream
import java.io.*;
public class FileStream8
{
static File f=new File("friends.txt");
public static void main(String args[])
{
storenames();
dispnames();
}
public static void storenames()
{
try
{
DataInputStream dis=new DataInputStream(System.in);
FileOutputStream fos=new FileOutputStream(f);
System.out.println("enter names at end type STOP");
String name=dis.readLine();
while(!name.equalsIgnoreCase("stop"))
{
fos.write(name.getBytes());
fos.write((byte)'\n');
name=dis.readLine();
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
-8-
catch(Exception e)
{
System.out.println(e);
}
}
public static void dispnames()
{
try
{
FileInputStream fis=new FileInputStream(f);
int k;
System.out.println("------------"+"THE NAMES
ARE"+"------------");
while((k=fis.read())!=-1)
{
System.out.print((char)k);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#9. Program to read the data from keyboard and stores into the file by using
FileOutputStream
import java.io.*;
public class FileStream9
{
public static void main(String args[]) throws Exception
{
FileOutputStream fos=new FileOutputStream("pqr.txt");
System.out.println("enter data end type *");
char ch=(char)System.in.read();
while(ch!='*')
{
fos.write((byte)ch);
ch=(char)System.in.read();
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
-9-
#10. Program to read the data from keyboard and stores into the file by using
FileOutputStream
import java.io.*;
public class FileStream10
{
public static void main(String args[]) throws IOException
{
String str;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter a string");
str=dis.readLine();
System.out.println(str);
dis.close();
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 10 -
NETWORKING
Writing network programs is that communicates between a client and server in a cabled
network like LAN. To implements these applications, we need to include a special package called
“java.net”.
The java.net package includes the classes like
Socket
Readobj( )
Writeobj( )
ServerSocket
DatagramSocket
URL
URL Connection
There exist two forms of communication in networking those are.
1. Stream Socket (Connection oriented)
2. Datagram Socket (Connection less)
Socket: - With this class a client can establish connection with the server. It is a peer-to-peer
(system to system) communication end point. It must be associated with a network address and
port number. It uses TCP/IP Protocol. It provides Connection-oriented service. Sockets come
in three flavors
a) Stream band :- Here the data flows like a stream
> It uses TCP Protocol
> Network should be connected with a cable/medium
b) Datagram band :- Here the data flows in the form of packets
> It uses UDP protocol
> In security issues we prefer stream band
> In case of fastness we need to go for UDP.
> There is no need of medium (Interface)
ServerSocket: - Server sockets are on server side and listen on a given port for connection
requests when their accept( ) method is called. Once a connection has been established, the
accept( ) method returns a socket object to talk with the remote end.
DatagramSocket: - With this class we can send datagram packets of data. This class uses UDP
(User Datagram Protocol) and thereby the service is Connectionless service. It does not
guarantee the delivery of data packets. We use UDP protocols where the data delivery is needed
fast and not important.
Datagram socket is in listening mode.
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 11 -
Datagram packet is used for sending the data in packets by using send( ) method.( )
Datagram socket and Datagram packets are used only in connectionless systems
We can create the Datagram socket in client for server side.
URL:- Uniform/ Universal Resource Locators. To locate data on the Internet The simplest way to
write a java network application is to use URL class. As the name implies, URLs allows us to
locate and access any document in the Web. Simply create an URL object and it takes care of the
remaining things. Common URLs represent files (or) directories and can represent complex tasks
such as database lookups and internet searches. Java makes it easy to manipulate URLs. A URL
spe
URL contains 4 components
1.
2.
3.
4.
Protocol
Domain Name / host name
Port Number
Resource / File path
( com, edu, net, org …. Etc)
( 8080,7001….etc)
(File name Ex:- abc.aspx, mno.html)
1. Protocol: Separated from the rest of the locator by a colon (:). Common protocols are: (http,
ftp,
smtp…etc)
2. The host name (or) IP Address: - When the system is working in the network; it gives an
address that address is known as IP Address. It is delaminated on the left by double slashes, (//)
and on the right by a slash (/) (or) optionally a colon (:).
3. The port Number: -It is an optional parameter. The port number delaminated on the left from
the host name by a colon (:) and on the right by a slash (/).
4. Resource / File path : - It is the fourth part. Most http servers will append a file named index.
Html (or) index html to URLs; that refer directly a directory a directory resource.
Java’s URL class has several constructors, such as
1.
2.
3.
4.
URL(String ) The string is identical to displayed in a browser.
URL(String Protocol-name, String host-name, int port, String Path);
URL(String Protocol-name, String host-name, String Path);
URL(URL urlobject, String url-specifier);
Working with URL
import java.io.*;
import java.net..*;
public class Network1
{
public static void main(String args[]) throws Exception
{
URL u=new
URL("http://localhost:8080/servlet.hello.html");
System.out.println("The protocol is :" +
u.getProtocol());
System.out.println("The Domain name is :" +
u.getHost());
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 12 -
System.out.println("The Port is :" + u.getPort());
System.out.println("The Resource is :" + u.getFile());
}
}
Procedure at Server side: 1. Create or declare a server which listens the client request at a port no.
ServerSocket ss=new ServerSocker( );
2. Create a Socket which accepts the client request
Socket s=ss.accept( ); //To receive /listen the request of client
3. Declare IO streams either for sending or receiving data.
4. Send or reveive the data
5. Close the connections.
Procedure at Client side: 1. Create a socket by passing server address port no. The connection to the server is
established using a call to the socket constructor with two arguments. The server
internet address and the port number.
Ex: Socket s=new Socket(Server-address, Port-number);
2. Declare IO streams . Socket methods getInputStream and getOutputStream are used to
get references to the sockets associated InputStream and OutputStream respectievely,
InputStream method read() can be used to input individual bytes (or) Sets of bytes from
the Server. OutputStream method Write() can be used to output individual bytes (or)
sets of bytes to the server.
If the server values with an object outputstream, the client should read those values
with an object input stream.
Ex:ObjectInputStream
obj1=new
ObjectInputStream(Connection.getInputStream());
ObjectOutStream obj1=new ObjectOutStream(Connection.getOutStream());
3. Receive or send information. The processing phase in which the client and the server
communicate through the InputStream and OutputStream objects.
4. Close the connections. The client closes the connection by invoking the close method
on the socket.
#1. Program to display the IP address and system name
import java.net.*;
public class Ip
{
public static void main(String a[]) throws Exception
{
InetAddress ia=InetAddress.getLocalHost();
InetAddress ia1=InetAddress.getByName("system");
System.out.println(ia);
System.out.println(ia1);
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 13 -
}
}
#2. Program to display localhost name
import java.net.*;
public class Is
{
public static void main(String args[]) throws Exception
{
InetAddress is=InetAddress.getLocalHost();
System.out.println(is);
}
}
#3. Program on server to send the current date of the system by using ServerSocket
import
import
import
public
java.io.*;
java.net.*;
java.util.*;
class ServerSkt
{
public static void main(String args[])
{
try
{
ServerSocket ss = new ServerSocket(2222);
Socket s=ss.accept();
BufferedWriter bw = new
BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
Date d=new Date();
String st=d.toString();
bw.write(st,0,st.length());
bw.close();
s.close();
ss.close();
}
catch(Exception e)
{
System.out.println("The error:= " +
e.getMessage());
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 14 -
#4. Program on Client to read the date of the Server by using Socket
import java.io.*;
import java.net.*;
public class ClientSocket
{
public static void main(String args[])
{
try
{
Socket s = new
Socket("192.168.0.48",2222);
BufferedReader br = new
BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while((line = br.readLine())!=null)
{
System.out.println(line);
break;
}
br.close();
s.close();
}
catch(Exception e)
{
System.out.println("The error:= " +
e.getMessage());
}
}
}
#5. Program on server to send the current date of the system by using
DatagramSocket
import java.net.*;
public class ServerDatagram
{
public static void main(String a[]) throws Exception
{
DatagramPacket dp;
DatagramSocket ds=new DatagramSocket();
InetAddress adr=InetAddress.getLocalHost();
String str;
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 15 -
while(true)
{
Thread.sleep(500);
Date d=new Date();
byte b[];
str=d.toString();
b=str.getBytes();
dp=new DatagramPacket(b,b.length,adr,6666);
ds.send(dp);
}
}
}
#6. Program on Client to read the date of the Server by using DatagramSocket
import java.net.*;
public class ClientDatagram
{
public static void main(String a[]) throws Exception
{
DatagramSocket ds=new DatagramSocket(6666);
DatagramPacket dp;
byte b[];
while(true)
{
b=new byte[64];
dp=new DatagramPacket(b,b.length);
ds.reveive(dp);
String st=new String(dp.getData());
System.out.println(st);
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 16 -
JDBC
(Java Data Base Connectivity)
The JDBC API is a set of classes and interfaces. The package name for these classes and
interfaces is java.sql and is imported in the first line of the program.
Import java.sql.*;
The Java Database Connectivity (JDBC) API is the industry standard for database-independent
connectivity between the Java programming language and a wide range of databases – SQL
databases and other tabular data sources, such as spreadsheets or flat files. The JDBC API
provides a call-level API for SQL-based database access.
JDBC technology allows you to use the Java programming language to exploit "Write
Once, Run Anywhere" capabilities for applications that require access to enterprise data. With a
JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous
environment. The JDBC API provides a call-level API for SQL-based database access.
JDBC API Overview
The JDBC API makes it possible to do three things:
Establish a connection with a database or access any tabular data source
Send SQL statements
Process the results
JDBC Architecture
The JDBC API contains two major sets of interfaces: the first is the JDBC API for
application writers, and the second is the lower-level JDBC driver API for driver writers. JDBC
technology drivers fit into one of four categories. Applications and applets can access databases
via the JDBC API using pure Java JDBC technology-based drivers, as shown in this figure:
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 17 -
Left side, Type 4: Direct-to-Database Pure Java Driver
This style of driver converts JDBC calls into the network protocol used directly by DBMSs,
allowing a direct call from the client machine to the DBMS server and providing a practical
solution for intranet access.
Right side, Type 3: Pure Java Driver for Database Middleware
This style of driver translates JDBC calls into the middleware vendor's protocol, which is then
translated to a DBMS protocol by a middleware server. The middleware provides connectivity to
many different databases.
The graphic below illustrates JDBC connectivity using ODBC drivers and existing database client
libraries.
Left side, Type 1: JDBC-ODBC Bridge plus ODBC Driver
This combination provides JDBC access via ODBC drivers. ODBC binary code -- and in many
cases, database client code -- must be loaded on each client machine that uses a JDBC-ODBC
Bridge. Sun provides a JDBC-ODBC Bridge driver, which is appropriate for experimental use and
for situations in which no other driver is available.
Right side, Type 2: A native API partly Java technology-enabled driver
This type of driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix,
DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some
binary code be loaded on each client machine.
Partnering for Progress
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 18 -
Sun worked with an array of companies in the industry to create and rapidly establish the
JDBC API as the industry-standard, open interface for Java applications to access databases.
Industry Momentum
Leading database, middleware and tool vendors have been building support for JDBC
technology into many new products. This ensures that customers can build portable Java
applications while choosing from a wide range of competitive products for the solution best suited
to their needs. See the Industry Support page for a list of companies that are shipping products
with support for JDBC technology.
Advantages of JDBC Technology
Leverage Existing Enterprise Data
With JDBC technology, businesses are not locked in any proprietary architecture, and can
continue to use their installed databases and access information easily -- even if it is stored on
different database management systems.
Simplified Enterprise Development
The combination of the Java API and the JDBC API makes application development easy and
economical. JDBC hides the complexity of many data access tasks, doing most of the "heavy
lifting"for the programmer behind the scenes. The JDBC API is simple to learn, easy to deploy,
and inexpensive to maintain.
Zero Configuration for Network Computers
With the JDBC API, no configuration is required on the client side. With a driver written in the
Java programming language, all the information needed to make a connection is completely
defined by the JDBC URL or by a DataSource object registered with a Java Naming and
Directory Interface (JNDI) naming service. Zero configuration for clients supports the network
computing paradigm and centralizes software maintenance.
Key Features
Full Access to Metadata
The JDBC API provides metadata access that enables the development of sophisticated
applications that need to understand the underlying facilities and capabilities of a specific database
connection.
No Installation
A pure JDBC technology-based driver does not require special installation; it is automatically
downloaded as part of the applet that makes the JDBC calls.
Database Connection Identified by URL
JDBC technology exploits the advantages of Internet-standard URLs to identify database
connections. The JDBC API includes an even better way to identify and connect to a data source,
using a DataSource object, that makes code even more portable and easier to maintain.
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 19 -
In addition to this important advantage, DataSource objects can provide connection pooling and
distributed transactions, essential for enterprise database computing. This functionality is provided
transparently to the programmer.
Included in the Java Platform
As a core part of the Java 2 Platform, the JDBC API is available anywhere that the platform is.
This means that your applications can truly write database applications once and access data
anywhere. The JDBC API is included in both the Java 2 Platform, Standard Edition (J2SE) and
the Java 2 Platform, Enterprise Edition (J2EE), providing server-side functionality for industrial
strength scalability.
An example of a J2EE based architecture that includes a JDBC implementation:
Requirements
Software: The Java 2 Platform (either the Java 2 SDK, Standard Edition, or the Java 2
SDK, Enterprise Edition), an SQL database, and a JDBC technology-based driver for that
database.
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 20 -
Hardware: Same as for the Java 2 Platform.
DriverManager
getConnection();
public static Connection getConnection("url","uname","pw");
Classes and their methods & Constructors
Connection
createStatement();
prepareStatement();
prepareCall();
public Statement createStatement()
public PreparedStatement prepareStatement("sqlquery")
public CallableStatement prepareCall("query par")
Statement-interface
execute();
executeQuery(sqlquery)
executeUpdate();
public boolean execute();
public ResultSet executeQuery();
public int executeUpdate();
ResultSet
public String getString(colindex)
public String getString(colname)
public int
getInt(colindex)
public int
getInt(colname)
public Byte
getByte(colindex)
public Byte
getByte(colname)
public
getDate(colindex)
getDate(colname)
getBoolean(colindex)
getBoolean(colname)
getChar(colindex)
getChar(colname)
#1. Program on jdbc connection.
import java.io.*;
import java.sql.*;
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 21 -
import java.util.*;
public class DBConnection
{
public static void main(String args[])
{
try
{
Class
c=Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Driver d=(Driver)c.newInstance();
DriverManager.registerDriver(d);
System.out.println("driver loaded and registerd");
Properties p=new Properties();
p.put("user","scott");
p.put("password","tiger");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn",p);
System.out.println("connection has established");
Statement st=con.createStatement();
boolean a=st.execute("update emp set
sal=sal+1000");
if(a)
{
ResultSet rs=st.getResultSet();
while(rs.next())
{
System.out.println(rs.getString(1)+"
"+rs.getString(2));
}
}
else
{
int no=st.getUpdateCount();
System.out.println("no of records are updated
"+no);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#2. program to display all the tables
import java.io.*;
import java.sql.*;
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 22 -
import sun.jdbc.odbc.*;
public class DispTables
{
public static void main(String args[])
{
try
{
DriverManager.registerDriver( new JdbcOdbcDriver());
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from tab");
while(rs.next())
{
System.out.println(rs.getString(1));
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#3. program to create a table..
import java.io.*;
import java.sql.*;
public class CreateTable
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
Statement st=con.createStatement();
st.executeUpdate("create table student_details(rno
number(3), name varchar2(30), marks number(3))");
System.out.println("table is created");
con.close();
st.close();
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 23 -
catch(Exception e)
{
System.out.println(e);
}
}
}
#4. program to insert the rows
import java.io.*;
import java.sql.*;
public class Insertrows
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
Statement st=con.createStatement();
st.executeUpdate("insert into student_details
values(11,'hello',230)");
System.out.println("row is inserted");
con.close();
st.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#5. program to insert required no of rows
import java.io.*;
import java.sql.*;
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 24 -
public class Stest
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
Statement st=con.createStatement();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String res;
System.out.println("would u like to enter");
res=br.readLine();
while(res.equalsIgnoreCase("yes"))
{
System.out.println("enter the no, name and
marks");
int x=Integer.parseInt(br.readLine());
String n=br.readLine();
int m=Integer.parseInt(br.readLine());
String s="insert into student_details
values("+x+",'"+n+"',"+m+")";
st.executeUpdate(s);
System.out.println("row inserted");
System.out.println("would u like to continue");
res=br.readLine();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#6. program to display the rows
import java.io.*;
import java.sql.*;
public class Disp
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 25 -
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from
student_details");
System.out.println("roll number
"+"name
"+"marks
");
while(rs.next())
{
System.out.println(rs.getInt(1)+"
"+rs.getString(2)+"
"+rs.getInt(3));
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#7. Program to display the rows in reverse
import java.io.*;
import java.sql.*;
public class DispReverse
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs=st.executeQuery("select * from emp");
rs.afterLast();
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 26 -
while(rs.previous())
{
System.out.println(rs.getString(1)+"
"+rs.getString(2));
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#8. program to update the data
import java.io.*;
import java.sql.*;
public class TableUpdated
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
Statement st=con.createStatement();
String query="update student_details set
name='abcdedf' where rno=12";
st.executeUpdate(query);
System.out.println("row is updated");
con.close();
st.close();
}
catch(Exception e)
{
System.out.println(e+"error");
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 27 -
#9. program to insert the data by using prepared-statement
import java.io.*;
import java.sql.*;
public class PTest
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
PreparedStatement pst=con.prepareStatement("insert
into student_details values(?,?,?)");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter rollno, name and marks");
int rno=Integer.parseInt(br.readLine());
String na=br.readLine();
int marks=Integer.parseInt(br.readLine());
pst.setInt(1,rno);
pst.setString(2,na);
pst.setInt(3,marks);
pst.executeUpdate();
System.out.println("row inserted");
pst.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#10. program to update the data by using prepared statement
import java.sql.*;
import java.io.*;
public class SqlPs
{
public static void main(String ar[]) throws Exception
{
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 28 -
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:kish");
PreparedStatement ps=con.prepareStatement("update
student set marks = ? where rno = ?");
ps.setString(1, "200");
ps.setString(2, "1001");
ps.executeUpdate();
ps.setString(1, "580");
ps.setString(2, "1002");
ps.executeUpdate();
ps.close();
con.close();
}
}
#11. program to display the structure of table
//Retrieving the metadata of a table
import java.io.*;
import java.sql.*;
public class Mdata
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from emp");
ResultSetMetaData rsmd=rs.getMetaData();
int x=rsmd.getColumnCount();
System.out.println("no of columns are in emp "+x);
for(int i=1;i<=x;i++)
{
System.out.println(rsmd.getColumnName(i)+"
"+rsmd.getColumnTypeName(i)+"
"+rsmd.getColumnType(i));
}
}
catch(Exception e)
{
System.out.println(e);
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 29 -
}
}
#12. program to operate a table with menu options
import java.io.*;
import java.sql.*;
class DBoperations
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
public DBoperations()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","ti
ger");
}
catch(Exception e)
{
System.out.println(e);
}
}
public void display()
{
try
{
st=con.createStatement();
rs=st.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getString(1)+"
"+rs.getString(2)+"
"+rs.getString(3));
rs.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 30 -
public void insert()
{
try
{
st=con.createStatement();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the no, name and
marks");
int x=Integer.parseInt(br.readLine());
String n=br.readLine();
int m=Integer.parseInt(br.readLine());
String s="insert into student_details
values("+x+",'"+n+"',"+m+")";
st.executeUpdate(s);
System.out.println("ur record is inserted");
st.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public class MainTest
{
public static void main(String args[])
{
try
{
DBoperations d=new DBoperations();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("1. Insert a Row");
System.out.println("2. Delete a Row");
System.out.println("enter your choice 1..2");
int x=Integer.parseInt(dis.readLine());
switch (x)
{
case 1:
d.insert();
break;
case 2:
d.display();
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 31 -
break;
default:
System.out.println("Invalid choice..");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#13. program to delete a row
import java.io.*;
import java.sql.*;
public class RowDeletion
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
Statement st=con.createStatement();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the no to delete a row");
int x=Integer.parseInt(br.readLine());
String query="delete from student_details where
rno=" + x;
st.executeUpdate(query);
System.out.println("row is deleted");
con.close();
st.close();
}
catch(Exception e)
{
System.out.println(e+"error");
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 32 -
#14. Program to delete a row by using row number
import java.sql.*;
import java.io.*;
public class SqlP
{
public static void main(String ar[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:kish","scott","tiger")
;
Statement
s=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.C
ONCUR_UPDATABLE);
ResultSet rs=s.executeQuery("select * from st");
rs.absolute(7);
rs.deleteRow();
}
}
#15. Program on prepared statement
import java.sql.*;
class PraSta
{
public static void main(String a[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:ram","","");
PreparedStatement p=con.prepareStatement("select id,name
from emp where deptno=?");
p.setInt(1,10); //or ps.setString(1, "10");
ResultSet rs=p.executeQuery();
while(rs.next())
{
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 33 -
System.out.println(
rs.getString(2)
);
}
}
}
rs.getInt(1)+
"
"
+
#16. Program to create a stored procedure in oracle by using java program
import java.io.*;
import java.sql.*;
class SP
{
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
String ch = "y";
int no;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public void CE()
{
try
{
//Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =
DriverManager.getConnection("jdbc:odbc:hello");
}
catch(SQLException se)
{
System.out.println("The SQLException Is:= " +
se.getMessage());
}
catch(ClassNotFoundException cnfe)
{
System.out.println("The ClassNotFoundException
Is:= " + cnfe.getMessage());
}
}
public void CSP()
{
try
{
st = con.createStatement();
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 34 -
st.executeUpdate("create or replace procedure
test(n in number, snm out varchar) as " +
" begin "+
" select name into snm from stu where
rno = n; " +
" end; " +
" /");
}
catch(SQLException es)
{
System.out.println("The SQLException Is:= " +
es.getMessage());
}
}
}
public class StoredPro1
{
public static void main(String args[])
{
SP sp1 = new SP();
sp1.CE();
sp1.CSP();
}
}
#17. Program to insert the data into a table by using callable statement
import java.io.*;
import java.sql.*;
public class CallableSt1
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:hello");
CallableStatement cst=con.prepareCall("{
call inser(?,?,?)}");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Rno, name and
marks of a student");
int rn=Integer.parseInt(br.readLine());
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 35 -
String nm=br.readLine();
int mr=Integer.parseInt(br.readLine());
cst.setInt(1,rn);
cst.setString(2,nm);
cst.setInt(3,mr);
cst.executeUpdate();
System.out.println("your procedure successfully
executed");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#18. Program to add two numbers by using callable statement
import java.io.*;
import java.sql.*;
public class CallableSt2
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
CallableStatement cst=con.prepareCall("{ ?=call
ads(?,?)}");
cst.setInt(2,10);
cst.setInt(3,40);
cst.registerOutParameter(1,Types.INTEGER);
cst.executeUpdate();
int x=cst.getInt(1);
System.out.println("sum of two no from oracle"+x);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 36 -
#19. Program to read the data of a student to calculate the total by using callable
statement
import java.io.*;
import java.sql.*;
public class CallableSt3
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"
);
CallableStatement cst=con.prepareCall("{ call
getdata(?,?,?,?)}");
cst.setInt(1,10);
cst.registerOutParameter(2,Types.INTEGER);
cst.registerOutParameter(3,Types.INTEGER);
cst.registerOutParameter(4,Types.INTEGER);
cst.execute();
int a=cst.getInt(2);
int b=cst.getInt(3);
int c=cst.getInt(4);
if(a!=-1 && b!=-1 && c!=-1)
{
int tot=a+b+c;
float avg=(float)tot/3;
System.out.println("marks are"+a+"
"+b+"
"+c+"total is"+tot+"
average is"+avg);
}
else
System.out.println("sorry boss no record is found");
cst.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 37 -
RMI
(Remote Method Invocation)
It is the process of an object invoking a method of an object residing in a different JVM. This
program consist two interfaces, one is Interface Program and another one is Remote interface. So
here one interface is extended from another interface.
It raises remote exception
One class is extended from another super class
One interface is implemented by another class and we should bind the object at server
side
Naming.Rebind is used to bind the object at “rmiregistry” location with a specified object
name.
After compiling, before running the application we need to create stub & skeleton classes by
using
rmic compile
RMI Program should include 3 blocks of program
1. Interface :- Here only interfaces are created
2. Server : - Here we have to implement the interface and create the object
3. Client: - It is used to know where the object is created or located (Lookup).
Procedure to execute RMI Programs
Compile all the programs
Use the following command to get the stub and skeleton for implement program (Server side
Program) as
rmic <implementation file name>
Create the two directories for Server and Client as
md server
md client
Copy the following files to the client directory
1. interface class
2. implementation-stub class
3. client class
Copy the following files to the server directory
1. interface class
2. implementation class
3. implementation-skeleton class
4. server class
use the command at command prompt as
start rmiregistry
Then you will get a window; minimize it.
Enter into the server directory and execute the implementation file (Server program) as
java <implementation class>
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 38 -
minimize the window
Open another command window and enter into the client directory then execute the client
program as
java <client class>
Then you will find the output on client.
#1. Program to add two numbers by sending two command line arguments
a) Interface Program
import java.rmi.*;
public interface addserverintf extends Remote
{
double add(double d1,double d2) throws RemoteException;
}
b) Implementation Program
import java.rmi.*;
import java.rmi.server.*;
public class addserverimpl extends UnicastRemoteObject implements
addserverintf
{
public addserverimpl() throws RemoteException
{
}
public double add(double d1,double d2) throws
RemoteException
{
return d1+d2;
}
}
c) Server Program
import java.net.*;
import java.rmi.*;
public class addserver
{
public static void mian(String args[])
{
try
{
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 39 -
addserverimpl asi=new addserverimpl();
Naming.rebind("addserver",asi);
}
catch(Exception e)
{
System.out.println("Exception :" +
e.getMessage());
}
}
}
d) Client Program
import java.rmi.*;
public class addclient
{
public static void main(String args[])
{
try
{
String addserverurl="rmi://" + args[0] +
"/addserver";
addserverintf
addserintf=(addserverintf)Naming.lookup(addserverurl);
System.out.println("the first number is" +
args[1]);
double
d1=Double.valueOf(args[1]).doubleValue();
System.out.println(" the second number is" +
args[2]);
double
d2=Double.valueOf(args[2]).doubleValue();
System.out.println(" the sum is " +
addserintf.add(d1,d2));
}
catch(Exception e)
{
System.out.println(" the Exception is " +
e.getMessage());
}
}
}
Execute as:
C:\jdk1.2.2\bin>java client 192.168.0.1 25 45
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 40 -
#1. Program to add numbers by sending two parameters into the server from client
by using awt concept.
a) Interface program
import java.io.*;
import java.rmi.*;
public interface rmi1addintf extends Remote
{
public int add(int a,int b) throws RemoteException;
public int sub(int a,int b) throws RemoteException;
}
b) Implementation program (server program)
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class rmi1addimpl extends UnicastRemoteObject implements
rmi1addintf
{
public rmi1addimpl() throws RemoteException
{
}
public int add(int x,int y)
{
return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
public static void main(String args[])throws Exception
{
rmi1addimpl a=new rmi1addimpl();
System.out.println("object is created");
Naming.rebind("rmi://localhost:1099/b",a);
System.out.println("object is binded");
}
}
c) Client program
import
import
import
import
java.io.*;
java.awt.*;
java.rmi.*;
java.awt.event.*;
public class rmi1client extends Frame implements ActionListener
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 41 -
{
Button b1,b2;
TextField t1,t2,t3;
Label l1,l2,l3;
Panel p;
public rmi1client()
{
setLayout(new FlowLayout());
p=new Panel();
p.setLayout(new GridLayout(4,2));
t1=new TextField();
t2=new TextField();
t3=new TextField();
l1=new Label("enter a value");
l2=new Label("enter b value");
l3=new Label("r e s u l t");
b1=new Button("add");
b1.addActionListener(this);
b2=new Button("sub");
b2.addActionListener(this);
p.add(l1);p.add(t1);
p.add(l2);p.add(t2);
p.add(l3);p.add(t3);
p.add(b1);p.add(b2);
add(p);
}
public void actionPerformed(ActionEvent ae)
{
try
{
String str=ae.getActionCommand();
rmi1addintf
ab=(rmi1addintf)Naming.lookup("rmi://localhost:1099/b");
int first=Integer.parseInt(t1.getText());
int second=Integer.parseInt(t2.getText());
if(str.equals("add"))
{
int res=ab.add(first,second);
t3.setText("
"+res);
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 42 -
}
if(str.equals("sub"))
{
int res=ab.sub(first,second);
t3.setText("
"+res);
}
}
catch(Exception e)
{
}
}
public static void main(String args[]) throws Exception
{
rmi1client rc=new rmi1client();
rc.setSize(400,400);
rc.setVisible(true);
}
}
#2. Program to add numbers by sending two parameters into the server from client
by using awt concept
a) Interface program
import java.io.*;
import java.rmi.*;
public interface rmi2intf extends Remote
{
public void insert(int ad, String nm, int m) throws
Exception;
public void update(int ad, String nm, int m) throws
Exception;
}
b) Implementation program (server program)
import
import
import
import
java.io.*;
java.sql.*;
java.rmi.*;
java.rmi.server.*;
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 43 -
public class rmi2impl extends UnicastRemoteObject implements
rmi2intf
{
Connection con;
PreparedStatement pst;
public rmi2impl() throws RemoteException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:hello","scott","ti
ger");
}
catch(Exception e)
{
System.out.println(e);
}
}
public void insert(int ad,String nm, int m) throws Exception
{
String snm; int admn,mr;
admn=ad;
snm=nm;
mr=m;
pst=con.prepareStatement("insert into stu values
(?,?,?)");
pst.setInt(1,admn);
pst.setString(2,snm);
pst.setInt(3,mr);
pst.executeUpdate();
}
public void update(int ad,String nm, int m) throws Exception
{
String snm; int admn,mr;
admn=ad;
snm=nm;
mr=m;
pst=con.prepareStatement("update stu set name="+ snm +
",marks=" + mr + " where admno="+admn);
pst.executeUpdate();
}
public static void main(String args[]) throws Exception
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 44 -
{
rmi2impl ri=new rmi2impl();
System.out.println("obj is binding");
Naming.rebind("rmi://localhost:1099/dbs",ri);
System.out.println("obj is bound");
}
}
c) Client Program
import java.io.*;
import java.rmi.*;
public class rmi2client
{
public static void main(String args[]) throws Exception
{
rmi2intf
d=(rmi2intf)Naming.lookup("rmi://localhost:1099/dbs");
int x=10;
String n="Suresh";
int m=200;
d.insert(x,n,m);
//d.update(x,"ramesh",150);
System.out.println("your values are inserted");
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 45 -
SERVLETS
What is a Servlet?
Servlets are modules of Java code that run in a server application (hence the name "Servlets",
similar to "Applets" on the client side) to answer client requests. Servlets are not tied to a specific
client-server protocol but they are most commonly used with HTTP and the word "Servlet" is
often used in the meaning of "HTTP Servlet".
Servlets make use of the Java standard extension classes in the packages javax.servlet (the basic
Servlet framework) and javax.servlet.http (extensions of the Servlet framework for Servlets that
answer HTTP requests). Since Servlets are written in the highly portable Java language and follow
a standard framework, they provide a means to create sophisticated server extensions in a server
and operating system independent way.
Typical uses for HTTP Servlets include:
Processing and/or storing data submitted by an HTML form.
Providing dynamic content, e.g. returning the results of a database query to the client.
Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system
which manages shopping carts for many concurrent customers and maps every request to the right
customer.
1.2 Servlets vs CGI
The traditional way of adding functionality to a Web Server is the Common Gateway Interface
(CGI), a language-independent interface that allows a server to start an external process which
gets information about a request through environment variables, the command line and its
standard input stream and writes response data to its standard output stream. Each request is
answered in a separate process by a separate instance of the CGI program, or CGI script (as it is
often called because CGI programs are usually written in interpreted languages like Perl).
Servlets have several advantages over CGI:
A Servlet does not run in a separate process. This removes the overhead of creating a new process
for each request.
A Servlet stays in memory between requests. A CGI program (and probably also an extensive
runtime system or interpreter) needs to be loaded and started for each CGI request.
There is only a single instance which answers all requests concurrently. This saves memory and
allows a Servlet to easily manage persistent data.
A Servlet can be run by a Servlet Engine in a restrictive Sandbox (just like an Applet runs in a
Web Browser's Sandbox) which allows secure use of untrusted and potentially harmful Servlets.
The Basic Servlet Architecture
A Servlet, in its most general form, is an instance of a class which implements the
javax.servlet.Servlet interface. Most Servlets, however, extend one of the standard
implementations
of
that
interface,
namely
javax.servlet.GenericServlet
and
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 46 -
javax.servlet.http.HttpServlet. In this tutorial we'll be discussing only HTTP Servlets which
extend the javax.servlet.http.HttpServlet class.
In order to initialize a Servlet, a server application loads the Servlet class (and probably other
classes which are referenced by the Servlet) and creates an instance by calling the no-args
constructor. Then it calls the Servlet's init(ServletConfig config) method. The Servlet should
performe one-time setup procedures in this method and store the ServletConfig object so that it
can be retrieved later by calling the Servlet's getServletConfig() method. This is handled by
GenericServlet. Servlets which extend GenericServlet (or its subclass HttpServlet) should call
super.init(config) at the beginning of the init method to make use of this feature. The
ServletConfig object contains Servlet parameters and a reference to the Servlet's ServletContext.
The init method is guaranteed to be called only once during the Servlet's lifecycle. It does not
need to be thread-safe because the service method will not be called until the call to init returns.
When the Servlet is initialized, its service(ServletRequest req, ServletResponse res) method is
called for every request to the Servlet. The method is called concurrently (i.e. multiple threads
may call this method at the same time) so it should be implemented in a thread-safe manner.
Techniques for ensuring that the service method is not called concurrently, for the cases where
this is not possible.
When the Servlet needs to be unloaded (e.g. because a new version should be loaded or the server
is shutting down) the destroy() method is called. There may still be threads that execute the
service method when destroy is called, so destroy has to be thread-safe. All resources which were
allocated in init should be released in destroy. This method is guaranteed to be called only once
during the Servlet's lifecycle.
A typical Servlet lifecycle
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 47 -
HTTP
Before we can start writing the first Servlet, we need to know some basics of HTTP
("HyperText Transfer Protocol"), the protocol which is used by a WWW client (e.g. a browser) to
send a request to a Web Server.
HTTP is a request-response oriented protocol. An HTTP request consists of a request
method, a URI, header fields and a body (which can be empty). An HTTP response contains a
result code and again header fields and a body.
The service method of HttpServlet dispatches a request to different Java methods for
different HTTP request methods. It recognizes the standard HTTP/1.1 methods and should not be
overridden in subclasses unless you need to implement additional methods. The recognized
methods are GET, HEAD, PUT, POST, DELETE, OPTIONS and TRACE. Other methods are
answered with a Bad Request HTTP error. An HTTP method XXX is dispatched to a Java method
doXxx, e.g. GET -> doGet. All these methods expect the parameters "(HttpServletRequest req,
HttpServletResponse res)". The methods doOptions and doTrace have suitable default
implementations and are usually not overridden. The HEAD method (which is supposed to return
the same header lines that a GET method would return, but doesn't include a body) is performed
by calling doGet and ignoring any output that is written by this method. That leaves us with the
methods doGet, doPut, doPost and doDelete whose default implementations in HttpServlet return
a Bad Request HTTP error. A subclass of HttpServlet overrides one or more of these methods to
provide a meaningful implementation.
The request data is passed to all methods through the first argument of type
HttpServletRequest (which is a subclass of the more general ServletRequest class). The response
can be created with methods of the second argument of type HttpServletResponse (a subclass of
ServletResponse).
When you request a URL in a Web Browser, the GET method is used for the request. A
GET request does not have a body (i.e. the body is empty). The response should contain a body
with the response data and header fields which describe the body (especially Content-Type and
Content-Encoding). When you send an HTML form, either GET or POST can be used. With a
GET request the parameters are encoded in the URL, with a POST request they are transmited in
the body. HTML editors and upload tools use PUT requests to upload resources to a Web Server
and DELETE requests to delete resources.
Session Tracking allows a Servlet to associate a request with a user. A session can extend
across requests and connections of the stateless HTTP. Sessions can be maintained in two
ways:
1. By using Cookies. A Cookie is a string (in this case that string is the session ID)
which is sent to a client to start a session. If the client wants to continue the session it
sends back the Cookie with subsequent requests. This is the most common way to
implement session tracking.
2. By rewriting URLs. All links and redirections which are created by a Servlet have to
be encoded to include the session ID. This is a less elegant solution (both, for Servlet
implementors and users) because the session cannot be maintained by requesting a
well-known URL oder selecting a URL which was created in a different (or no)
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 48 -
session. It also does not allow the use of static pages. All HTML pages which are sent
within a session have to be created dynamically.
Our next Servlet manages a virtual shopping cart. Users can add various items to their shopping
cart via HTML forms. The shopping cart contents are stored on the server and each user gets his
own shopping cart which is selected automatically whenever he makes a request to the Servlet.
In the simplified version that we implement in class ShoppingCartServlet there are only two
kinds of items, named FOO and BAR. By pressing a button in an HTML form a single FOO or
BAR item can be put into the shopping cart. There's another button to see the current contents of
the shopping cart and a button to order the selected items, thus clearing the shopping cart.
The first version of the Servlet, called ShoppingCartServlet, which works with Cookie-style
sessions only, consists of the two standard methods, doGet and doPost:
A form with the buttons is created by the Servlet's doGet method.
7:
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
8:
throws ServletException, IOException
9:
{
10:
res.setContentType("text/html");
11:
PrintWriter out = res.getWriter();
12:
out.print("<HTML><HEAD><TITLE>Online Shop</TITLE>"+
13:
"</HEAD><BODY><FORM METHOD=POST>"+
14:
"<INPUT TYPE=SUBMIT NAME=foo VALUE="+
15:
"\"Put a FOO into the shopping cart\">"+
16:
"<INPUT TYPE=SUBMIT NAME=bar VALUE="+
17:
"\"Put a BAR into the shopping cart\">"+
18:
"<INPUT TYPE=SUBMIT NAME=see VALUE="+
19:
"\"See the shopping cart contents\">"+
20:
"<INPUT TYPE=SUBMIT NAME=buy VALUE="+
21:
"\"Buy the shopping cart contents\">"+
22:
"</FORM></BODY></HTML>");
23:
out.close();
24:
}
Alternatively, it could also come from a static HTML page.
The doPost method processes the form data which is sent by a client in response to
the form created by doGet.
26:
protected void doPost(HttpServletRequest req,
HttpServletResponse res)
27:
throws ServletException, IOException
28:
{
29:
String msg;
30:
31:
HttpSession session = req.getSession(true);
32:
if(session.isNew())
33:
{
34:
session.putValue("foo", new int[] { 0 });
35:
session.putValue("bar", new int[] { 0 });
36:
}
37:
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 49 -
38:
int[] foo = (int[])session.getValue("foo");
39:
int[] bar = (int[])session.getValue("bar");
40:
41:
if(req.getParameter("foo") != null)
42:
{
43:
foo[0]++;
44:
msg = "Bought a FOO. You now have "+foo[0]+".";
45:
}
46:
else if(req.getParameter("bar") != null)
47:
{
48:
bar[0]++;
49:
msg = "Bought a BAR. You now have "+bar[0]+".";
50:
}
51:
else if(req.getParameter("buy") != null)
52:
{
53:
session.invalidate();
54:
msg = "Your order for "+foo[0]+" FOOs and "+bar[0]+
55:
" BARs has been accepted. Your shopping cart is
empty now.";
56:
}
57:
else
58:
{
59:
msg = "You have "+foo[0]+" FOOs and "+bar[0]+
60:
" BARs in your shopping cart.";
61:
}
62:
63:
res.setContentType("text/html");
64:
res.setHeader("pragma", "no-cache");
65:
PrintWriter out = res.getWriter();
66:
out.print("<HTML><HEAD><TITLE>Shopping
Cart</TITLE></HEAD><BODY>");
67:
out.print(msg);
68:
out.print("<HR><A HREF=\"");
69:
out.print(req.getRequestURI());
70:
out.print("\">Back to the shop</A></BODY></HTML>");
71:
out.close();
72:
}
First we get the HttpSession object which is associated with the request by calling
req.getSession. The argument true forces the creation of a new session if the request
doesn't contain a valid session key.
Note: Although getSession is a method of HttpServletRequest and not of
HttpServletResponse it may modify the response header and therefore needs to be
called before a ServletOutputStream or PrintWriter is requested.
If the session is indeed new (determined by calling HttpSession's isNew() method)
we add some custom data to the session: Two counters, one for the FOOs and one for the
BARs in the shopping cart. The session object can be used like a Dictionary. That means
we can only add Objects, not instances of primitive types like int. We could use an instance
of java.lang.Integer for each counter, but these objects are immutable which makes
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 50 -
incrementing inefficient and difficult to implement. Instead we use an array of int (int[])
with only one element as a mutable wrapper object. The element is initialized to 0.
Next we retrieve the values for "foo" and "bar" from the session, no matter if they were just
added or carried over from a previous request.
In the ListManagerServlet both buttons had the same name but different values so
we could use getParameter to retrieve the value from the request and then do a string
compare to the possible values. This time we use a different approach which can be
implemented more efficiently. All buttons have different names and we can find out which
button was used to submit the form by checking which name has a non-null value.
A new FOO or BAR item can be put into the shopping cart by simply incrementing
the counter in the array. Note that the array does not need to be put back into the session
because it has not changed itself, only the contents have been modified.
When the user chooses to buy the contents of the shopping cart we call
session.invalidate() to delete the session on the server side and tell the client to remove
the session ID Cookie. The session data is lost and when a new POST request is made to
the Servlet, a new session will be created.
The rest of the doPost method is basically the same as in the ListManagerServlet.
Here is the full source code of the ShoppingCartServlet:
ShoppingCartServlet.java
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShoppingCartServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<HTML><HEAD><TITLE>Online Shop</TITLE>"+
"</HEAD><BODY><FORM METHOD=POST>"+
"<INPUT TYPE=SUBMIT NAME=foo VALUE="+
"\"Put a FOO into the shopping cart\">"+
"<INPUT TYPE=SUBMIT NAME=bar VALUE="+
"\"Put a BAR into the shopping cart\">"+
"<INPUT TYPE=SUBMIT NAME=see VALUE="+
"\"See the shopping cart contents\">"+
"<INPUT TYPE=SUBMIT NAME=buy VALUE="+
"\"Buy the shopping cart contents\">"+
"</FORM></BODY></HTML>");
out.close();
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
- 51 -
throws ServletException, IOException
{
String msg;
HttpSession session = req.getSession(true);
if(session.isNew())
{
session.putValue("foo", new int[] { 0 });
session.putValue("bar", new int[] { 0 });
}
int[] foo = (int[])session.getValue("foo");
int[] bar = (int[])session.getValue("bar");
if(req.getParameter("foo") != null)
{
foo[0]++;
msg = "Bought a FOO. You now have "+foo[0]+".";
}
else if(req.getParameter("bar") != null)
{
bar[0]++;
msg = "Bought a BAR. You now have "+bar[0]+".";
}
else if(req.getParameter("buy") != null)
{
session.invalidate();
msg = "Your order for "+foo[0]+" FOOs and "+bar[0]+
" BARs has been accepted. Your shopping cart is empty now.";
}
else
{
msg = "You have "+foo[0]+" FOOs and "+bar[0]+
" BARs in your shopping cart.";
}
res.setContentType("text/html");
res.setHeader("pragma", "no-cache");
PrintWriter out = res.getWriter();
out.print("<HTML><HEAD><TITLE>Shopping Cart</TITLE></HEAD><BODY>");
out.print(msg);
out.print("<HR><A HREF=\"");
out.print(req.getRequestURI());
out.print("\">Back to the shop</A></BODY></HTML>");
out.close();
}
public String getServletInfo()
{
return "ShoppingCartServlet 1.0 by Stefan Zeiger";
}
}
Note that req.getSession is called for every POST request. It is important that the session
object is requested on a regular basis because the Web Server may set a session timeout.
Requesting the session ensures that the session's time-to-live is reset. The only reason for not
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 52 -
calling req.getSession in the doGet method of this version of the Servlet is to make the response
to doGet cachable.
Adding Support for URL Rewriting
To make the Servlet usable with URL rewriting (for clients without Cookie support or with
Cookie support turned off) we have to make some modifications.
The formerly static "Online Shop" page which is created by doGet needs to be modified to
include an ACTION URL which contains an encoded session ID in the HTML form. This is done
with the encodeUrl method of HttpServletResponse. We also need to call req.getSession to
keep the session alive. The additional code to check for a new session can be avoided by using
getSession(false). If there is no session or an invalid session we do not force the creation of a
new session. This is deferred until the doPost method is called. Finally, the response has to be
marked as not cachable by calling res.setHeader("pragma", "no-cache"), as usual.
These changes lead us to the following revised implementation of doGet:
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
HttpSession session = req.getSession(false);
res.setContentType("text/html");
res.setHeader("pragma", "no-cache");
PrintWriter out = res.getWriter();
out.print("<HTML><HEAD><TITLE>Online Shop</TITLE>"+
"</HEAD><BODY><FORM METHOD=POST ACTION="+
out.print(res.encodeUrl(req.getRequestURI()));
out.print("><INPUT TYPE=SUBMIT NAME=foo VALUE="+
"\"Put a FOO into the shopping cart\">"+
"<INPUT TYPE=SUBMIT NAME=bar VALUE="+
"\"Put a BAR into the shopping cart\">"+
"<INPUT TYPE=SUBMIT NAME=see VALUE="+
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 53 -
"\"See the shopping cart contents\">"+
"<INPUT TYPE=SUBMIT NAME=buy VALUE="+
"\"Buy the shopping cart contents\">"+
"</FORM></BODY></HTML>");
out.close();
}
The doPost method requires only a minor change. The Servlet's URI which is used to link back
to the "Online Shop" page needs to be encoded with res.encodeUrl, as in the doGet method.
Client-Side Data with Cookies
API 2.0
We've already used Cookies indirectly through Sessions. While session data is stored on the
server side and only an index to the server-side data (the session ID) is transmitted to the
client, Cookies can also be used directly to store data on the client side.
The Servlet API provides the class javax.servlet.http.Cookie for a convenient object-oriented
representation of Cookies so you don't need to compose and decompose Cookie and Set-Cookie
HTTP headers yourself.
Even if you don't care where the data is stored it is sometimes useful to manipulate Cookies
directly via the Cookie class to get more control over Cookie parameters like Domain and Path,
e.g. to share Cookies between different Servlets or even servers.
Example. Imagine an authentication Servlet which receives a username and password from a
login form via doPost and verifies them against a central authentication database. It then
computes an authentiation string (e.g. a Base64-encoded "user:password" combination, as used
by HTTP Basic Authentication). This string is now put into a Cookie and sent back to the client:
Cookie authCookie = new Cookie("xyz-Auth", credentials);
authCookie.setVersion(1);
authCookie.setDomain(".xyz.com");
res.addCookie(authCookie);
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 54 -
The Cookie's domain is set to ".xyz.com" so it will be sent to all hosts in domain "xyz.com" like
"a.xyz.com" and "foo.xyz.com" (but not "c.d.xyz.com"). Note that the Domain attribute is
supported by RFC2109-style Cookies (version 1) but not by old Netscape Cookies (version 0, the
default for newly created Cookie objects).
All Web Servers on hosts in xyz.com are running an instance of another Servlet which serves
protected data after verifying the authentication credentials:
boolean verified = false;
Cookie[] cookies = req.getCookies();
for(int i=0; i<cookies.length; i++)
{
String n = cookies[i].getName(),
d = cookies[i].getDomain();
if(n != null && n.equals("xyz-Auth") &&
d != null && d.equals(".xyz.com"))
{
String credentials = cookies[i].getValue();
verfied = verifyCredentials(credentials);
break;
}
}
if(!verified)
{
res.sendRedirect(...);
return;
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 55 -
}
The credentials are retrieved from the Cookie and verified by the authentication database. If the
credentials are invalid or missing the client is redirected to the login page on the authentication
server, otherwise the protected content is returned
4.5 User Authentication via Sessions
We've already seen sessions that were created implicitly in the ShoppingCartServlet. The
sessions were created as needed and only used to identify an anonymous user.
Sessions can also be used for authentication. In contrast to HTTP Basic Authentication a session
can be invalidated which enables users to log out without quitting the Web Browser (which is
required with Basic Authentication because there is no way to force a browser to delete the
authentication credentials).
The following SessionAuthServlet shows how to do authentication with a Servlet. The doPost
method processes requests to log in or out. sendPage is called by both, doGet and doPost.
SessionAuthServlet.java
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public final class SessionAuthServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
sendPage(req, res, req.getSession(false));
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
if(req.getParameter("login") != null)
{
HttpSession session = req.getSession(true);
String name = req.getParameter("name");
if(name == null || name.length()==0) name = "Anonymous";
session.putValue("name", name);
sendPage(req, res, session);
}
else
{
HttpSession session = req.getSession(false);
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 56 -
27:
if(session != null) session.invalidate();
28:
sendPage(req, res, null);
29:
}
30:
}
31:
32:
private void sendPage(HttpServletRequest req, HttpServletResponse res,
33:
HttpSession session)
34:
throws ServletException, IOException
35:
{
36:
res.setContentType("text/html");
37:
res.setHeader("pragma", "no-cache");
38:
PrintWriter o = res.getWriter();
39:
o.print("<HTML><HEAD><TITLE>SessionAuthServlet</TITLE></HEAD><BODY>");
40:
if(session == null)
41:
o.print("<FORM METHOD=POST>Please enter your name: "+
42:
"<INPUT TYPE=TEXT NAME=\"name\">"+
43:
"<INPUT TYPE=SUBMIT NAME=\"login\" VALUE=\"Log in\">"+
44:
"</FORM></BODY></HTML>");
45:
else
46:
o.print("Hi " + session.getValue("name") +
47:
"<P><FORM METHOD=POST><INPUT TYPE=SUBMIT NAME=\"logout\"
"+
48:
"VALUE=\"Log out\"></FORM></BODY></HTML>");
49:
o.close();
50:
}
51: }
4.6 Relative URLs
When a Servlet creates a response which contains a relative URL, e.g. a hyperlink in an HTML
document, you have to make sure that the URL points to the right directory.
Example. The following document is mounted on a server as /shop/preview/form.html:
<HTML><HEAD><TITLE>Form</TITLE></HEAD><BODY>
<FORM ACTION="/servlet/PreviewServlet" METHOD=GET>
...
</FORM>
</BODY></HTML>
There are also product images in the same directory, e.g. /shop/preview/foo.gif,
/shop/preview/bar.gif, ...
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 57 -
The Servlet which is mounted as /servlet/PreviewServlet evaluates the form data and creates
an HTML page with IMG tags to the appropriate product images, e.g. <IMG SRC="foo.gif">. But
this naive approach does not work. The images are in the same directory as the form but the
page is created by the Servlet, so the client sees it as /servlet/PreviewServlet. The base
name of this URL is /servlet/, thus the image foo.gif from the above image tag is expected at
/servlet/foo.gif and not /shop/preview/foo.gif. If /servlet/ is a pure Servlet directory it
can only contain Servlets and no other data (like GIF images). It is therefore not possible to
move the images to the Servlet directory (/servlet/). Instead the image tags need to be
modified to include the full path to the images, relative to the server root, i.e.
<IMG SRC="/shop/preview/foo.gif"> for the foo.gif image.
4.7 Logging
A Web Server is usually running as a background process without connected stdio streams. Even
if the server is running in a console, a Servlet can not expect to access that console with the
System.in, System.out and System.err streams. Instead all messages should be sent to a
server log file with one of ServletContext's log methods:
writes the specified message to the log file.
public void log(String msg, Throwable t) API 2.1 writes the specified message
and a stack trace of the Throwable object to the log file. The message will usually
be an explanation of an error and the Throwable an exception that caused the error.
public void log(Exception exception, String msg) does the same as the
previous method. It is available in earlier API versions and deprecated in version
2.1.
public void log(String msg)
Two convenience methods are implemented in GenericServlet. They automatically prefix the
messages with the right Servlet name and then call the appropriate ServletContext method:
public void log(String msg)
public void log(String msg, Throwable cause) API 2.1
Interface javax.servlet.SingleThreadModel
Interface javax.servlet.http.HttpSession
Interface javax.servlet.http.HttpSessionBindingListener
Interface javax.servlet.http.HttpSessionContext
Class javax.servlet.http.Cookie
Class javax.servlet.http.HttpSessionBindingEvent
New Methods, Constructors and Fields
Method javax.servlet.ServletContext.getServletNames()
Method javax.servlet.ServletContext.log(Exception, String)
Method javax.servlet.ServletRequest.getCharacterEncoding()
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 58 -
Method javax.servlet.ServletRequest.getReader()
Method javax.servlet.ServletResponse.getCharacterEncoding()
Method javax.servlet.ServletResponse.getWriter()
Constructor javax.servlet.ServletException.ServletException()
Method javax.servlet.http.HttpServletRequest.getCookies()
Method javax.servlet.http.HttpServletRequest.getRequestedSessionId()
Method javax.servlet.http.HttpServletRequest.getSession(boolean)
Method
javax.servlet.http.HttpServletRequest.isRequestedSessionIdFromCookie()
Method javax.servlet.http.HttpServletRequest.isRequestedSessionIdFromUrl()
Method javax.servlet.http.HttpServletRequest.isRequestedSessionIdValid()
Field javax.servlet.http.HttpServletResponse.SC_CONFLICT
Field javax.servlet.http.HttpServletResponse.SC_CONTINUE
Field javax.servlet.http.HttpServletResponse.SC_GATEWAY_TIMEOUT
Field javax.servlet.http.HttpServletResponse.SC_GONE
Field javax.servlet.http.HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED
Field javax.servlet.http.HttpServletResponse.SC_LENGTH_REQUIRED
Field javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED
Field javax.servlet.http.HttpServletResponse.SC_MULTIPLE_CHOICES
Field
javax.servlet.http.HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION
Field
Field
Field
Field
Field
javax.servlet.http.HttpServletResponse.SC_NOT_ACCEPTABLE
javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT
javax.servlet.http.HttpServletResponse.SC_PAYMENT_REQUIRED
javax.servlet.http.HttpServletResponse.SC_PRECONDITION_FAILED
javax.servlet.http.HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED
Field javax.servlet.http.HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
Field javax.servlet.http.HttpServletResponse.SC_REQUEST_TIMEOUT
Field javax.servlet.http.HttpServletResponse.SC_REQUEST_URI_TOO_LONG
Field javax.servlet.http.HttpServletResponse.SC_RESET_CONTENT
Field javax.servlet.http.HttpServletResponse.SC_SEE_OTHER
Field javax.servlet.http.HttpServletResponse.SC_SWITCHING_PROTOCOLS
Field javax.servlet.http.HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE
Field javax.servlet.http.HttpServletResponse.SC_USE_PROXY
Method javax.servlet.http.HttpServletResponse.addCookie(Cookie)
Method javax.servlet.http.HttpServletResponse.encodeRedirectUrl(String)
Method javax.servlet.http.HttpServletResponse.encodeUrl(String)
Method javax.servlet.http.HttpServlet.doDelete(HttpServletRequest,
HttpServletResponse)
Method javax.servlet.http.HttpServlet.doOptions(HttpServletRequest,
HttpServletResponse)
Method javax.servlet.http.HttpServlet.doPut(HttpServletRequest,
HttpServletResponse)
Method javax.servlet.http.HttpServlet.doTrace(HttpServletRequest,
HttpServletResponse)
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 59 -
Deprecated Methods
Method javax.servlet.ServletContext.getServlets()
(use getServletNames in conjunction with getServlet instead)
Changes from Version 2.0 to Version 2.1
Version 2.1 introduced the new model for inter-servlet communication and request delegation.
There are some new minor features like nested Exceptions. Several inconsistencies in the API
have been corrected.
New Interfaces
Interface javax.servlet.RequestDispatcher
Deprecated Interfaces
Interface javax.servlet.http.HttpSessionContext
(removed for security reasons)
New Methods and Constructors
Method javax.servlet.ServletContext.getAttributeNames()
Method javax.servlet.ServletContext.getContext(String)
Method javax.servlet.ServletContext.getMajorVersion()
Method javax.servlet.ServletContext.getMinorVersion()
Method javax.servlet.ServletContext.getRequestDispatcher(String)
Method javax.servlet.ServletContext.getResource(String)
Method javax.servlet.ServletContext.getResourceAsStream(String)
Method javax.servlet.ServletContext.log(String, Throwable)
Method javax.servlet.ServletContext.removeAttribute(String)
Method javax.servlet.ServletContext.setAttribute(String, Object)
Method javax.servlet.ServletRequest.getAttributeNames()
Method javax.servlet.ServletRequest.setAttribute(String, Object)
Method javax.servlet.GenericServlet.init()
Method javax.servlet.GenericServlet.log(String, Throwable)
Constructor javax.servlet.ServletException.ServletException(String,
Throwable)
Constructor javax.servlet.ServletException.ServletException(Throwable)
Method javax.servlet.ServletException.getRootCause()
Method javax.servlet.http.HttpServletRequest.getSession()
Method javax.servlet.http.HttpServletRequest.isRequestedSessionIdFromURL()
Method javax.servlet.http.HttpServletResponse.encodeRedirectURL(String)
Method javax.servlet.http.HttpServletResponse.encodeURL(String)
Method javax.servlet.http.HttpSession.getMaxInactiveInterval()
Method javax.servlet.http.HttpSession.setMaxInactiveInterval(int)
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 60 -
Java Servlet technology provides Web developers with a simple, consistent mechanism for
extending the functionality of a Web server and for accessing existing business systems. A servlet
can almost be thought of as an applet that runs on the server side--without a face. Java servlets
make many Web applications possible
Servlets are the Java platform technology of choice for extending and enhancing Web servers.
Servlets provide a component-based, platform-independent method for building Web-based
applications, without the performance limitations of CGI programs. And unlike proprietary server
extension mechanisms (such as the Netscape Server API or Apache modules), servlets are serverand platform-independent. This leaves you free to select a "best of breed" strategy for your
servers,
platforms,
and
tools.
Servlets have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases. Servlets can also access a library of HTTP-specific calls and receive all the
benefits of the mature Java language, including portability, performance, reusability, and crash
protection.
Today servlets are a popular choice for building interactive Web applications. Third-party servlet
containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are
usually a component of Web and application servers, such as BEA WebLogic Application Server,
IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server, and others.
You might want to check out the latest information on JavaServer Pages (JSP) technology. JSP
technology is an extension of the servlet technology created to support authoring of HTML and
XML pages. It makes it easier to combine fixed or static template data with dynamic content.
Even if you're comfortable writing servlets, there are several compelling reasons to investigate
JSP technology as a complement to your existing work.
Servlets are not the only mechanism that can interact in this way with a user. CGI scripts can
perform similar operations -- and indeed, until servlets came along, CGI scripts were the standard
mechanism for creating and displaying HTML pages dynamically. But servlets have many
advantages over CGI scripts, and are quickly replacing them in the world of enterprise computing.
One way in which a CGI script is inferior to a servlet that a CGI script spawns a new process
every time it is executed, consuming more and more processing time -- and more and more server
resources -- every time it is invoked. Also, CGI scripts are platform-dependent and cannot take
advantages of many of a server's capabilities because they run in processes that are separate from
the server's process. For example, a CGI program cannot write to a server's log file.
Servlets do not have any of these liabilities. They are efficient and scalable because they don't
create new processes every time they execute; instead, servlets are handled by separate threads
within the Web server process. They can write to server log files and can take advantages of other
server capabilities because they run in the server's own process. And, because they are designed to
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 61 -
fulfill the "Write Once, Run AnywhereTM" promise inherent in the Java programming language,
servlets can be executed without modification on any platform.
Using a Servlet
Figure shows one of the most common ways of using a servlet. A user (1) requests some
information by filling out a form containing a link to a servlet and clicking the Submit button (2).
The server (3) locates the requested servlet (4). The servlet then gathers the information needed to
satisfy the user's request and constructs a Web page (5) containing the information. That Web
page is then displayed on the user's browser (6).
The doPost() Method
When the Guestbook servlet has executed its init() function, it overrides the HttpServlet class's
doPost() method. At first glance, Guestbook's doPost() routine looks quite complex. Actually,
though, the first half of the routine is nothing but a series of statements that define the variables
used for each of the servlet's parameters. These variable definitions are so cut-and-dried that the
code initiating them can actually be generated automatically. In fact, this part of the Guestbook's
source file was automatically generated, using IBM's WebSphere Studio IDE (see box).
Here's the initial part of the Guestbook servlet's doPost() method:
The printErrorPage() and printData() Methods
The printErrorPage() and printData() functions are the first functions we have examined that are
not overrides of HttpServlet methods. Instead, they are custom routines unique to the Guestbook
servlet. The printErrorPage() method is particularly worth studying because it shows quite clearly
how a servlet can generate a complete HTML page. In this case, printErrorPage() constructs a
Web page containing an error message if it has been determined that the user has left one or more
required fields blank. Then the error page is sent back to the user and displayed in the user's
browser:
The response.setContentType() method -- in the first line of the preceding code fragment --
informs the servlet object we are creating that the next thing it will see is some data that should be
treated as HTML text.
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 62 -
The second line in the code fragment instantiates an object called a PrintWriter, which is defined
in the Servlet API. A servlet can use a PrintWriter or a number of things, one of which is to write
text to Web pages.
Next come three lines of code that actually do create some text which will shortly be displayed on
a Web page. The first statement creates a data stream that will print a blank line when it is sent to
the user's Web browser. The second line sets up a data stream that will print a title on the Web
page that the servlet generates. The third statement creates a stream that will print another blank
line.
Life cycle functions in servlets: 1. Public void init()
2. public void service()
3. public void destroy()
JAVA-SERVERS
Stepts for servlet runner through jsdk2.0
1. create a java file
2. set the class path to javax
Ex:- set classpath=%classpath%;d:\jsdk2.0\src;
3. compile the java file
4. Copy the class file into
jsdk2.0\examples
5. Open jsdk2.0\bin\
double click on
servletrunner and minimize the window
6. Open Browser and give the url as
http://localhost:8080/servlet/filename
Java Web-Server
1). Copy the class file in c:\javawebserver2.0\servlets
2). Start the web-server as follows
Start->run->c:\javawebserver2.0\bin\httpd.exe
3). Open Internet Explorer types the URL as
http://localhost:8080/servlet/servlet-class-name
Tomcat 4.1
1). Create the root directory
+WEB-INF
.xml files
+srl
+lib
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 63 -
+classes
.class files
+META-INF
.html files
.jsp files
1). Copy the class file in to the class folder
2). Create jar file as
c:\rootdirectory> jar –cvf filename.war
3). Set classpath=c:\tomcat4.1\common\lib\servlet.jar;%classpath%;
3). Open Internet Explorer types the URL as
http://localhost:8080/servlet/servlet-class-name
Java Bea Web-Logic
1). Create a domain root directory
+WEB-INF
.xml files
.html files
.jsp files
+lib
+classes
.class files
1). Create jar file as
c:\rootdirectory> jar –cvf filename.war /WEB-INF/
3). Open Internet Explorer types the URL as
http://localhost:8080/servlet/servlet-class-name
Servlets#1. //Program to Display a message on a web page by using HTTP Servlets
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv1 extends HttpServlet
{
private int counter;
public Serv1()
{
super();
System.out.println("HelloServlet Initantiated");
}
public void init()
{
System.out.println("HelloServlet Initialized");
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 64 -
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<html><head>");
pw.println("<title>HelloServlet Example</title></head>");
pw.println("<body><center><h1>Welcome To The Servlets World</h1>");
pw.println("</center></body></html>");
}
public void destroy()
{
System.out.println("HelloServlet Derstroyed...");
}
}
Servlets #2 //Program to send the parameter form html to HTTP Servlet
<html>
<body><center>
<form method=post action="http://localhost:8080/servlet/Serv2">
Name: <input type =text name=nm>
<input type=submit value="Click Here">
</form>
</center></body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv2 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String name = req.getParameter("nm");
pw.println("<html><head>");
pw.println("<body bgcolor = #ccff66#> <center>");
pw.println("<font face = arial color = blue>");
pw.println("<h1>Welcome To " + name + "</h1>");
pw.println("</font></center></body></html>");
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 65 -
}
Servlets #3 //Program to send 3 sub marks to HTTP Servlets for getting the total
<html>
<body><center>
<form method=post action="http://localhost:8080/servlet/Serv3">
Enter marks for M1: <input type =text name=s1><br>
Enter marks for M2: <input type =text name=s2><br>
Enter marks for M3: <input type =text name=s3><br>
<input type=submit value="Click Here">
</form>
</center></body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv3 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
int m1 = Integer.parseInt(req.getParameter("s1"));
int m2 = Integer.parseInt(req.getParameter("s2"));
int m3 = Integer.parseInt(req.getParameter("s3"));
int tot=m1+m2+m3;
pw.println("<html><head>");
pw.println("<body bgcolor = #ccff66#> <center>");
pw.println("<font face = arial color = blue>");
pw.println("<h1>The total marks are " + tot + "</h1>");
pw.println("</font></center></body></html>");
}
}
Servlets #4 //Program to create a table in database by using HTTP Servlets
<html>
<body><center>
<form method=post action="http://localhost:8080/servlet/Serv4">
Enter a query to create a table: <input type =text name=tabcr size=100>
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 66 -
<input type=submit value="Create">
</form>
</center></body>
</html>
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv4 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String str = req.getParameter("tabcr");
pw.println("<html><head>");
pw.println("<title>Table Creation Form</title></head>");
pw.println("<body bgcolor = #ccff66#><center>");
pw.println("<h1>Table Creation</h1>");
pw.println("<hr color = blue>");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection
("jdbc:odbc:hello","scott","tiger");
Statement st = con.createStatement();
st.executeUpdate(str);
pw.println("<h2>Successfully created</h2>");
pw.println("</body></html>");
}
catch(Exception e)
{
pw.println("<strong>The Error:= " + e.getMessage() + "</strong>");
}
}
}
Servlets #5 //Program to insert the data into a table by using HTTP Servlets
<html>
<body><center>
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 67 -
<form method=post action="http://localhost:8080/servlet/Serv5">
Enter HTNO: <input type =text name=no><br>
Enter Name: <input type =text name=nm><br>
<input type=submit value="Insert">
</form>
</center></body>
</html>
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv5 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
int htno = Integer.parseInt(req.getParameter("no"));
String name = req.getParameter("nm");
pw.println("<html><head>");
pw.println("<title>Rows Insertion</title></head>");
pw.println("<body bgcolor = #ccff66#><center>");
pw.println("<h1>Inserting a row</h1>");
pw.println("<hr color = blue>");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection
("jdbc:odbc:hello","scott","tiger");
Statement st = con.createStatement();
st.executeUpdate("insert into stu values(" + htno +",'" + name + "')");
pw.println("<h2>Successfully inserted</h2>");
pw.println("</body></html>");
}
catch(Exception e)
{
pw.println("<strong>The Error:= " + e.getMessage() + "</strong>");
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 68 -
}
Servlets #6 //Program to select the data from a table by using HTTP Servlets
<html>
<body><center>
<form method=post action="http://localhost:8080/servlet/Serv6">
<input type=submit value="Click Here">
</form>
</center></body>
</html>
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv6 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<html><head>");
pw.println("<title>All Students Information</title></head>");
pw.println("<body bgcolor = #ccff66#><center>");
pw.println("<font face = arial color = blue>");
pw.println("<h1>All Students Information</h1><br>");
pw.println("<hr color = blue>");
pw.println("<table border=2 bordercolor=red>");
pw.println("<tr> <th> HTNO </th> <th> NAME </th> </tr>");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:hello","scott","tiger");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from stu");
while(rs.next())
{
pw.println("<tr><td>"+rs.getInt("htno")+"</td><td>"+rs.getString("name")+"</td></tr>");
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 69 -
}
pw.println("</table><font>");
pw.println("<br><hr color = blue>");
pw.println("</center></body></html>");
}
catch(Exception e)
{
pw.println("<strong>The Error:= " + e.getMessage() + "</strong>");
}
}
}
Servlets #7 //Program to find a record by using HTTP Servlets
<html>
<body><center>
<form method=post action="http://localhost:8080/servlet/Serv7">
Enter HTNO: <input type =text name=id>
<input type=submit value="Search">
</form>
</center></body>
</html>
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv7 extends HttpServlet
{
int sid;
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<html><head>");
pw.println("<title>Searching Form</title></head>");
pw.println("<body bgcolor = #ccff66#><center>");
pw.println("<font face = arial color = blue>");
pw.println("<h1>Student Information</h1>");
pw.println("<hr color = blue>");
try
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 70 -
{
sid = Integer.parseInt(req.getParameter("id"));
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:hello","scott","tiger");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from stu where htno = " + sid);
if(rs.next())
{
pw.println("<p><strong> ID: " + rs.getInt("htno") + "</strong></p>");
pw.println("<p><strong> Name: " + rs.getString("name") + "</strong></p>");
}
else
pw.println("<strong> The Specified ID Number Record Is Not Entered! </stromg>");
rs.close();
con.close();
pw.println("<hr color = blue>");
pw.println("</font></center></body></html>");
}
catch(Exception e)
{
pw.println("<strong>The Error:= " + e.getMessage() + "</strong>");
}
}
}
Servlets #8 //Program to navigate Servlets by using HTTP Servlets
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv8 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<html><head>");
pw.println("<title>HelloServlet Example</title></head>");
pw.println("<body><form method=post action='Serv7'>");
pw.println("<center><h1>Welcome To The Servlets World</h1>");
pw.println("<input type=submit value=Serv1>");
pw.println("</center></form></body></html>");
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 71 -
}
}
Servlets #9 //Program to calculate the total for a given three sub marks by using HTTP
Servlets
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv9 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<html><head>");
pw.println("<title>HelloServlet Example</title></head>");
pw.println("<body><form method=post action='Serv1'>");
pw.println("<center><h1>Welcome To The Servlets World</h1>");
pw.println("Enter m1: <input type=text name=t1><br>");
pw.println("Enter m2: <input type=text name=t2><br>");
pw.println("Total: <input type=text name=t3 readonly><br>");
pw.println("<input type=button value=Total
onClick='t3.value=parseInt(t1.value)+parseInt(t2.value)'>");
pw.println("</center></form></body></html>");
}
}
Servlets #10 //Program to send the color codes from html to Servlets by using HTTP
Servlets
<html>
<body>
<form method="GET" action="http://localhost:8080/servlet/Serv10">
<b>Color : </b>
<select name="nerolac">
<option value="cc0000">Red
<option value="00ff00">Green
<option value="0000ff">Blue
</select>
<br><br><br>
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 72 -
<input type=submit value="Choose please">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv10 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
String clr=req.getParameter("nerolac");
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<b>The selected color is " + clr);
pw.close();
}
}
Servlets #11 //Program to display a message on to Servlet by using Generic Servlets
import javax.servlet.*;
public class Serv12Generic extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)
{
try
{
ServletOutputStream sos=res.getOutputStream();
sos.println("<html><center><font color=BLUE><h1>This is my first
servlet</h1></font></center></html>");
sos.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Servlets #12 //Program to send the parameter form html to Generic Servlets
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 73 -
<html><body>
<center>
<form name=f method=post action="http://localhost:8080/servlet/Serv12Generic">
Enter empno:<input type=text name=t1><br>
Enter ename:<input type=text name=t2><br>
<input type=submit value="Click here">
</form>
</center>
</body>
</html>
import java.io.*;
import javax.servlet.*;
public class Serv12Generic extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)
{
try
{
String eno=req.getParameter("t1");
String ename=req.getParameter("t2");
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body><center><font color=BLUE>
<h1>Employee No is " + eno);
pw.println("<br>Employee Name is " + ename);
pw.println("</h1></font></center></body></html>");
pw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Servlets #13 //Program to check the user name and password in database through the
HTTP
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 74 -
Servlets
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class Serv13Login1 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
{
try
{
PrintWriter pw=res.getWriter();
pw.println("<html><body><form
action='http://localhost:8080/servlet/Serv13Check2' method=post>");
pw.println("Login
: <input type=text name=t1><br>");
pw.println("Password : <input type=password name=p1><br>");
pw.println("<input type=submit value=Click><br>");
pw.println("</form></body></html>");
pw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class Serv13Check2 extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res)
{
try
{
PrintWriter pw=res.getWriter();
String l=req.getParameter("t1");
String p=req.getParameter("p1");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:dsn","scott","tiger");
PreparedStatement ps=con.prepareStatement("select * from yahoo where
login=? and password=?");
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 75 -
ps.setString(1,l);
ps.setString(2,p);
ResultSet rs=ps.executeQuery();
if(rs.next())
res.sendRedirect("http://localhost:8080/servlet/Serv13Welcome3");
else
res.sendRedirect("http://localhost:8080/servlet/Serv13Error4");
pw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class Serv13Welcome3 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
{
try
{
PrintWriter pw=res.getWriter();
pw.println("<html><body><h1>welcome to The Servlet World</h1>");
pw.println("</h1></body></html>");
pw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class Serv13Error4 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
{
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 76 -
try
{
PrintWriter pw=res.getWriter();
pw.println("<html><body><form
action='http://localhost:8080/servlet/Serv14Login1'>");
pw.println("<h1>Invalid User Name/Password</h1>");
pw.println("<input type=submit value='Return to Home Page'>");
pw.println("</form></body></html>");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 77 -
Cookies and Sessions
Cookies are a way for a server to send information to client to store and for the server to later
retrieve its data from that client. A cookie can be defined as a small amount of memory used by
web server within client system. A server can provide one or more cookies to a client. Multiple
cookies can have the same name. Client software such as a web browser is expected to support 20
cookies per host, of at least 4KB each. Cookies are return to a server, Servlets running within a
server shares cookies.
To send a cookie we have to do the following steps
1. Instantiate a cookie object.
2. Set any attributes.
3. Send the cookie
To get the information from a cookie
1. Retrieve all the cookies from the user’s request
2. Find the required cookie / cookies by using their names
3. Get the values of cookie.
There are two types of cookies
a). In-memory cookie
b). Persistent cookie
a). In-memory cookie:- When the cookie is maintained within browser application process
memory is called as in-memory cookie. (Temporary cookie)
b). Persistent cookie:- When the cookie is maintained in the hard disk memory with a particular
life time then it is called as Persistent cookie. (Permanent cookie)
Sessions:- To maintain state about a series of request from the same user across a period of time.
Sessions are shared among the Servlets a client accesses. This sharing scheme is convenient for
applications made up of multiple Servlets.
When the client makes a first request to the application, web server will allocate a unique
memory to the client on server machine; this memory is called as session memory.
Steps to use Session Tracking
1. Obtain a session (an HTTP session object) for a user
2. Store or get data from the HTTP session object
3. Invalidate the session (Optional)
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 78 -
Servlets #14 //Programs to create and read a cookie through the HTTP Servlet
<html>
<body>
<form action="http://localhost:8080/servlet/Serv14Cookie1">
Enter Name :<input type=text name=t1><br>
Enter Marks :<input type=text name=t2><br>
<input type=submit value=Click>
</form>
</body>
</html>
import java.io.*;
import javax.servlet.http.*;
public class Serv14Cookie1 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
{
try
{
String s1=req.getParameter("t1");
String s2=req.getParameter("t2");
Cookie c=new Cookie(s1,s2);
res.addCookie(c);
PrintWriter pw=res.getWriter();
pw.println("<html><body><form action =
'http://localhost:8080/servlet/Serv14CookieRead'>");
pw.println("<h1>Cookie Created.....</h1>");
pw.println("<input type=submit value=click>");
pw.println("</form></body></html>");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import java.io.*;
import javax.servlet.http.*;
public class Serv14CookieRead extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 79 -
{
try
{
PrintWriter pw=res.getWriter();
Cookie c[]=req.getCookies();
for(int i=0;i<c.length;i++)
pw.println(c[i].getName() + " " + c[i].getValue());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Servlets #15 //Programs to create and read a session through the HTTP Servlet
<html>
<body>
<center>
<form name=f method=post action="http://localhost:8080/servlet/Serv16Session1">
Enter Name:<input type=text name=t1><br>
Enter Marks:<input type=text name=t2><br>
<input type=submit value="Click here">
</form>
</center>
</body>
</html>
import java.io.*;
import javax.servlet.http.*;
public class Serv15Session1 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
{
try
{
String s1=req.getParameter("t1");
String s2=req.getParameter("t2");
HttpSession hs=req.getSession(true);
hs.putValue(s1,s2);
res.sendRedirect("http://localhost:8080/servlet/Serv15SessionRead2");
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 80 -
catch(Exception e)
{
System.out.println(e);
}
}
}
import java.io.*;
import javax.servlet.http.*;
public class Serv15SessionRead2 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
{
try
{
HttpSession hs=req.getSession(true);
PrintWriter pw=res.getWriter();
pw.println("The Session values is " + hs.getValue("hello"));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 81 -
BEANS
A bean is a reusable software component. Beans allow developers to gather the benefits of
rapid application development in java, by assembling pre-defined software components to create
powerful applications and applets. A graphical programming and design environment (builder
tools) that supports beans provide programmers to re-use and integrate existing components.
These components can be linked together to create applets, applications or new beans for recess
by others.
Categories of software components: There are two categories under the software components
a. Visual components: - The components which have the visible property as true
b. Non-Visual components: - The components which have the visible property as false
Components of Beans Development Environment: There are 4 components in BDE such as
1. ToolBox: - This window contains sample beans for practicing
java beans. These can also be used to interact with
any new beans.
2. BeanBox: - It is used to test a bean. This box acts
like a container (where we can execute
all the jar files.
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 82 -
3. Properties: - This window allow the
programmers to customize the currently
selected bean. i.e. Currently selected bean
properties can be known through this
window.
4. Method Tracer: - This window displays simple
debugging messages
Programs on Beans
#1. A Simple javaBean apllication to set the background color of the canvas of
specified size
import java.io.*;
import java.awt.*;
public class BeanTest1 extends Canvas implements Serializable
{
public BeanTest1()
{
setBackground(Color.green);
setSize(50,50);
}
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 83 -
Steps for loading the Program into BeanBox
Compile the above program to get BeanTest1.class
Create a Manifest file for the above Program
It must be written in separate notepad as
Name: BeanTest1.class
Java-Bean: True
(the space between the Name and the BeanTest1 is compulsory)
(the space between the java-Bean and the True is compulsory)
Save the file as BeanTest1.mft
(mft is the extension of the manifest file.)
Create a jar file as follows
c:\beans>jar -cvfm BeanTest1.jar BeanTest1.mft BeanTest1.class
Then you will get a message as follows (when the jar file creates as successfully)
added manifest
adding: BeanTest1.class<in = 403> <out= 293><deflated 27%>
Note: - If the above message is didn’t get you have to create the jar file again
Open BDK by double clicking run.bat file from c:\BDK\beanbox (where available)
For loading the jar file into the bean box Open bean box and select the
File menu load jar then select your jar file (which you are created)
Now it will appear in the tool box
To execute the bean, Select the bean from tool box and drop it on to the BeanBox
#2. Adding property to a bean
import java.io.*;
import java.awt.*;
import java.beans.*;
public class BeanTest extends Canvas implements Serializable
{
color col=color.green;
public BeanTest()
{
setBackground(color.green);
setSize(50,50);
}
public void setColor(color c)
{
col=c;
repaint();
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 84 -
public color getcolor()
{
return col;
}
public void paint(Graphics g)
{
g.setColor(col);
g.fillRect(10,10,20,20);
}
}
#3) Writing property change support class (circle and Square)
import java.io.*;
import java.awt.*;
import java.beans.*;
public class circle extends Canvas implements Serializable
{
private color col=color.green;
private PropertyChangeSupport pcs;
public circle( )
{
setSize(50,50);
pcs=new propertyChangeSupport(this);
}
public void paint(Graphics g)
{
Dimension d= getSize();
g.setColor(col);
g.fillOval(0,0,d.width-1,d.height-1);
}
public color getColor()
{
return col;
}
public void setColor(color new color)
{
color oldcolor=col;
col=new color;
pcs.firePropertyChange("color",oldcolor,newcolor);
repaint();
}
public void addPropertyChangeListener(PropertyChangeListener
pcl)
{
pcs.addPropertyChangeListener(pcl);
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 85 -
public void removePropertyChangeListener
(PropertyChangeListener pcl)
{
pcs.removePropertyChangeListener(pcl);
}
}
import java.io.*;
import java.awt.*;
import java.beans.*;
public class square extends Canvas implements Serializable
{
private color col=color.red;
public square( )
{
setSize(50,50);
}
public void paint(Graphics g)
{
Dimension d= getSize();
g.setColor(col);
g.fillRect(0,0,d.width-1,d.height-1);
}
public color getColor()
{
return col;
}
public void setColor(color new color)
{
col=newcolor;
repaint();
}
public void PropertyChange(PropertyChangeEvent pce)
{
setColor((color)pce.getNewValue());
}
}
#4) Program to change the color property
import java.beans.*;
public class BeanTestBeanInfo extends SimpleBeanInfo
{
public property Descriptor[]getPropertyDescriptors
{
try
{
PropertyDescriptor pd=new PropertyDescriptor
("color",BeanTest.class);
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 86 -
PropertyDescriptor pd[]={pd};
return pds;
}
catch(Exception e)
{
}
return null;
}
}
#5) Program to read the data on to bean box from a database using jdbc
import java.io.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
public class JdbcBean extends panel implements serializable
{
string ds,us,ps;
TextField txt1;
button b1;
textarea ta;
public JdbcBean()
{
setLayout(new.BorderLayout());
ds=" ";
us=" ";
ps=" ";
txt1=newTextFeild(60);
b1=new Button("query");
ta=new TextArea(10,60);
b1.addActionListener(this);
add(txt1,BorderLayout.NORTH);
add(ta,BorderLayout.CENTER);
add(b1,BorderLayout.SOUTH);
}
public void setDsn(string str);
{
ds=str;
}
public string getDsn()
{
return ds;
}
public void setUser()
{
us.str;
}
By R. Thirupathi, MCA KCCS, Warangal.
Advanced Java for MCA II/II
- 87 -
public string getUser()
{
return us;
}
public void setPassword()
{
ps.str;
}
public string getPassword()
{
return ps;
}
public void actionPerformed(ActionEvent ae)
{
try
{
class c=class,.forName
("sun.jdbc.odbc.JdbOdbcDriver");
Driver d=(Driver)c.new Instance();
DriverManager.registerDriver(d);
Connection con=DriverManager.getConnection
("jdbc:odbc"+ds,us,ps);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery
(txt1.getText().trim());
String str=" ";
while(rs.next())
{
String str1=rs.getInt(1)+" "rs.getString(2)+"
"+rs.get String(3)+"\n";
str=ste1+str;
}
ta.append(str)
}
catch(Exception e)
{
}
}
}
By R. Thirupathi, MCA KCCS, Warangal.