0% found this document useful (0 votes)
150 views46 pages

Socket Programming (TCP/UDP) - 1) Create Chat Application Using Either TCP and UDP Protocol

The document describes socket programming concepts in Java using TCP and UDP protocols. It includes code examples for: 1. A chat application using TCP that allows a client and server to exchange messages. 2. A file transfer program using UDP that sends a file from a server to a client. 3. A sorting algorithm implementation using TCP where a client sends unsorted data to a server, the server sorts it and returns the sorted data. 4. A concurrent TCP server that handles multiple clients and returns the current day and time to each client.

Uploaded by

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

Socket Programming (TCP/UDP) - 1) Create Chat Application Using Either TCP and UDP Protocol

The document describes socket programming concepts in Java using TCP and UDP protocols. It includes code examples for: 1. A chat application using TCP that allows a client and server to exchange messages. 2. A file transfer program using UDP that sends a file from a server to a client. 3. A sorting algorithm implementation using TCP where a client sends unsorted data to a server, the server sorts it and returns the sorted data. 4. A concurrent TCP server that handles multiple clients and returns the current day and time to each client.

Uploaded by

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

Socket Programming(TCP/UDP)-CO2160707.

1
1) Create chat application using either TCP and UDP protocol.

Server.java:

import java.util.Scanner;
import java.io.*;
import java.net.*;
class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(4444);
Socket sock=ss.accept(); try

{
DataInputStream din=new
DataInputStream(sock.getInputStream());
DataOutputStream dout=new
DataOutputStream(sock.getOutputStream());
String msgsend="",msgrec="";
BufferedReader st =new BufferedReader(new

InputStreamReader(System.in));

while(true)
{
msgrec=(String)din.readUTF();
if(msgrec.equalsIgnoreCase("stop"))
{ System.out.println("\nClosing the Connection");

break;
}
System.out.println("Received Message:"+msgrec);
System.out.print("Enter Message to send:");
msgsend=st.readLine();
dout.writeUTF(msgsend);
dout.flush();
}
}
catch(Exception e){}
}
}

Client.java:

import java.util.Scanner;
import java.io.*;
import java.net.*;
class Client
{
public static void main(String[] args) throws Exception
{
Socket sock=new Socket("localhost",4444);
try
{
DataInputStream din=new
DataInputStream(sock.getInputStream());
DataOutputStream dout=new
DataOutputStream(sock.getOutputStream());
String msgrec="",msgsend="";
BufferedReader st =new BufferedReader(new

InputStreamReader(System.in));

System.out.println("\nEnter 'stop' to close


connection\n");

while(true)
{
System.out.print("Enter Message to
send:"); msgsend=st.readLine();
dout.writeUTF(msgsend);
if(msgsend.equalsIgnoreCase("stop")) {

break;
}
dout.flush();
msgrec=(String)din.readUTF();
System.out.println("Received Message:"+msgrec);
}
}
catch(Exception e)
{

}
finally{sock.close();}
}

Output:
At client side:

run:

Enter 'stop' to close connection

Enter Message to send:hello


Received Message:hii
Enter Message to send:how are you
Received Message:i'm fine
Enter Message to send:

At server side:

Run:
Received Message:hello
Enter Message to send:hii
Received Message:how are you
Enter Message to send:i'm fine
Socket Programming(TCP/UDP)-CO2160707.1
2) Implement UDP Server for transferring files using Socket and ServerSocket

MyServer.java:

import java.io.*;
import java.net.*;
class Myserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
FileInputStream fin=new FileInputStream("send.txt");
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
int r;
while((r=fin.read())!=-1)
{
dout.write(r);
}
System.out.println("\n Filetranfer Completed");
s.close();
ss.close();
}
}

MyClient.java:

import java.io.*;
import java.net.*;
public class MyClient
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("localhost",6666);
if(s.isConnected()) {

System.out.println("Connection Established for transfer


of file");
}
FileOutputStream fout= new FileOutputStream("receive.txt");
DataInputStream din=new
DataInputStream(s.getInputStream());
int r;
while((r=din.read())!=-1)
{
fout.write((char)r);
}
System.out.println("File Received");
s.close();
}
}
Output:

At server side:

run:

Filetranfer Completed

At client side:

run:
Connection Established for transfer of
file File Received

Receive.txt:

hi
hello
how are you

Socket Programming(TCP/UDP)-CO2160707.1
3) Implement any one sorting algorithm using TCP on Server application and Give Input
On Client side and client should sorted output from server and display sorted on input
side.

Server3.java:

import java.net.*;
import java.io.*;
//import java.util.Scanner;
import java.util.Arrays;
public class Server3 {
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(2345);
Socket s=ss.accept(); DataInputStream
din=new
DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());

int no;
no=(int)din.read();
int input[]=new int[no];
for(int i=0;i<no;i++)
{
input[i]=(int)din.read();
}
System.out.println("Received data for sort are:");
for(int i=0;i<no;i++)
{
System.out.println(input[i]);
}
Arrays.sort(input);
System.out.println("Sorted Array:");
for(int i=0;i<no;i++)
{
System.out.println(input[i]);
}
for(int i=0;i<no;i++)
{
dout.write(input[i]);
dout.flush();
}
}
catch(IOException e)
{
}
}
}

Client3.java:

import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Client3
{
public static void main(String[] args)
{
try
{
Socket s=new Socket("localhost",2345);
DataInputStream din=new
DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
int no;
System.out.print("Enter no of elements you want to
sort:");
Scanner st=new Scanner(System.in);
no=st.nextInt();
int input[]=new int[no];
int output[]=new int[no];
for(int i=0;i<no;i++)
{
System.out.print("\nEnter "+(i+1)+"\t"+"Element:");
input[i]=st.nextInt();
}
dout.write(no);
for(int i=0;i<no;i++)
{
dout.write(input[i]);
dout.flush();
}
for(int i=0;i<no;i++)
{
output[i]=(int)din.read();
}
System.out.println("\nSorted array:");
for(int i=0;i<no;i++) {

System.out.println(output[i]);
}
s.close();
}
catch(IOException e){}
}
}
Output:

Client side:

run:
Enter no of elements you want to sort:5

Enter 1 Element:12

Enter 2 Element:45

Enter 3 Element:77

Enter 4 Element:99

Enter 5 Element:1

Sorted array:
1
12
45
77
99

Server side:

run:
Received data for sort are:
12
45
77
99
1
Sorted Array:
1
12
45
77
99
Socket Programming(TCP/UDP)-CO2160707.1
4) Implement Concurrent TCP Server programming in which more than one client can connect
and get Day and time from Server.

Server4.java:

import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
public class Server4 implements Runnable
{
Socket sock;
Server4(Socket sock)
{
this.sock=sock;
}
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(9999);
while(true)
{
Socket s=ss.accept();
System.out.println("Connected...");
new Thread(new Server4(s)).start();
}
}
@Override
public void run()
{
try
{
DataInputStream din=new
DataInputStream(sock.getInputStream());
DataOutputStream dout=new
DataOutputStream(sock.getOutputStream());
Date date=new Date(); SimpleDateFormat
s1=new SimpleDateFormat("hh:mm:ss a");
String time=s1.format(date);

dout.writeUTF(time);
dout.flush();
SimpleDateFormat s2=new
SimpleDateFormat("EEEE");
String day=s2.format(date);
dout.writeUTF(day);
dout.flush();
}
catch(IOException e){}
}
}
Client4.java:

import java.io.*;
import java.util.*;
import java.time.*;
import java.text.*;
import java.net.*;
public class Client4
{
public static void main(String[] args)
{
try
{
Socket s=new Socket("localhost",9999);
DataInputStream din=new
DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
String time,day;
time=(String)din.readUTF();
System.out.println("Time is "+time);
day=(String)din.readUTF();
System.out.println("Day is "+day);
s.close();
}
catch(IOException e){}
}
}
Output:

At client side:

run:
Time is 11:03:07 AM
Day is Tuesday

At server side:

run:
Connected...
JDBC-CO2160707.2
7) User can create a new database and also create new table under that database.
Once the database has been created then user can perform database CRUD
operations using the following:
1)Statement
package javaapplication5;

import java.sql.*;

public class Pra7_a {

public static void main(String[] args) {


int p_id =123 ;
String p_name = "Jackets";
int price = 1000;
try {
String url = "jdbc:mysql://localhost:3306/mysql";
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException ex) {
System.out.println(ex);
}
Connection con = null;
Statement st = null;
try
{
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql",
"root", "mysql");
System.out.println("Database ");
st = con.createStatement();
String query = "insert into products values ('" + emp_id
+ "','" + emp_name + "','" + emp_salary + "')";
System.out.println("query" + query);
boolean execute = st.execute(query);
System.out.println("Query execution result: " +
execute);
}
catch (SQLException ex) {
System.out.println(ex);
}
finally {
try {
st.close();
con.close();
}
catch (SQLException ex) {
System.out.println(ex);
}
}
}
}
Output:
Database
queryinsert into HRM values ('4','Aashish','32000')
Query execution result: false
BUILD SUCCESSFUL (total time: 0 seconds)

mysql> select * from HRM;


+--------+----------+------------+
| emp_id | emp_name | emp_salary |
+--------+----------+------------+
| 1 | sefali | 23000 |
| 617 | sajida | 100 |
| 2 | prachi | 21000 |
| 3 | pooja | 22000 |
| 4 | Aashish | 32000 |
+--------+----------+------------+

JDBC-CO2160707.2
7 User can create a new database and also create new table under that database.
Once the database has been created then user can perform database CRUD
operations using the following:
1)Statement

package Pra7_b;

import java.sql.*;

public class Pra7_b {

public static void main(String[] args) {


boolean choice = true;
try {
String url =
"jdbc:mysql://localhost:3306/mysql";
/ TODO code application logic here
//loading the driver
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException ex) {
System.out.println(ex);
}
Connection con = null;
Statement st = null; try
{
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql",
"root", "mysql");
System.out.println("Database "); st
= con.createStatement();
String query = "update HRM set
emp_name='riddhi' where emp_id=617";
System.out.println("query" +
query);
boolean execute = st.execute(query);
System.out.println("Query execution result: " +
execute);
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
st.close();
con.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
}
}

Output:
Database
queryupdate HRM set emp_name='riddhi'where emp_id=617
Query execution result: false
BUILD SUCCESSFUL (total time: 0 seconds)
mysql> select * from HRM;
+--------+----------+------------+
| emp_id | emp_name | emp_salary |
+--------+----------+------------+
| 1 | sefali | 23000 |
| 617 | riddhi | 100 |
| 2 | prachi | 21000 |
| 3 | pooja | 22000 |
| 4 | Aashish | 32000 |
+--------+----------+------------+

JDBC-CO2160707.2
7 User can create a new database and also create new table under that database.
Once the database has been created then user can perform database CRUD
operations using the following:
1)Statement

package Pra7_c;

import java.sql.*;

public class Pra7_c {

public static void main(String[] args) {


boolean choice = false;
try {
String url =
"jdbc:mysql://localhost:3306/mysql";
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException ex) {
System.out.println(ex);
}
Connection con = null;
Statement st = null; try
{
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql",
"root", "mysql");
System.out.println("Database ");
st = con.createStatement();
String query = "DELETE FROM HRM " + "WHERE
emp_id = 617";
System.out.println("query" + query);
boolean execute = st.execute(query);
System.out.println("Query execution result: " +
execute);
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
st.close();
con.close();
} catch (SQLException ex)
{ System.out.println(ex);
}
}
}
}

Output:
Database
queryDELETE FROM HRM WHERE emp_id = 617
Query execution result: false
BUILD SUCCESSFUL (total time: 0 seconds)
+--------+----------+------------+
| emp_id | emp_name | emp_salary |
+--------+----------+------------+
| 1 | sefali | 23000 |
| 2 | prachi | 21000 |
| 3 | pooja | 22000 |
| 4 | Aashish | 32000 |
| 1 | sefali | 23000 |
+--------+----------+------------+
JDBC-CO2160707.2
7 User can create a new database and also create new table under that database.
Once the database has been created then user can perform database CRUD
operations using the following:
1)Statement

package javaapplication5;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NewClass2 {

public static void main(String[] args) {


boolean choice = true;
try {
String url =
"jdbc:mysql://localhost:3306/shruti";
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
System.out.println(ex);
}
Connection con = null;
Statement st = null; try
{
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql",
"root", "mysql");
System.out.println("Database "); st
= con.createStatement();
String query = "select * from HRM";
System.out.println("query" + query);
ResultSet rs = st.executeQuery(query);
System.out.println(" emp_id emp_name
emp_salary");
while (rs.next()) {
int emp_id = rs.getInt("emp_id");
String emp_name = rs.getString("emp_name");
int emp_salary = rs.getInt("emp_salary");
System.out.println(emp_id + " " + emp_name + "
" + emp_salary);
}
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
st.close();
con.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
}
}
Output:
Database
queryselect * from HRM
emp_id emp_name emp_salary
1 sefali 23000
2 prachi 21000
3 pooja 22000
4 Aashish 32000
1 sefali 23000
BUILD SUCCESSFUL (total time: 0 seconds)

JDBC-CO2160707.2
7 User can create a new database and also create new table under that database. Once
the database has been created then user can perform database CRUD operations
using the following:
1)PreparedStatement

package P7;

import java.sql.*;

public class P7_a {

public static void main(String[] args) {

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

try (Connection con =


DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql",
"root", "mysql")) {
PreparedStatement stmt =
con.prepareStatement("insert into HRM values(?,?,?)");
stmt.setInt(1, 5);
stmt.setString(2, "sanvi");
stmt.setInt(3, 43000);
int i = stmt.executeUpdate();
System.out.println(i + " records inserted");
}
} catch

(ClassNotFoundException |

SQLException e)

{ System.out.println(e);

Output:
1 records inserted
BUILD SUCCESSFUL (total time: 0 seconds)
+--------+----------+------------+
| emp_id | emp_name | emp_salary |
+--------+----------+------------+
| 1 | sefali | 23000 |
| 2 | prachi | 21000 |
| 3 | pooja | 22000 |
| 4 | Aashish | 32000 |
| 1 | sefali | 23000 |
| 5 | sanvi | 43000 |
+--------+----------+------------+

JDBC-CO2160707.2
7 User can create a new database and also create new table under that database.
Once the database has been created then user can perform database CRUD
operations using the following:
1)PreparedStatement

package P7;

import java.sql.*;

public class P7_b {

public static void main(String[] args) {


try { Class.forName("com.mysql.jdbc.Driver");
try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql",
"root", "mysql")) {
PreparedStatement stmt =
con.prepareStatement("update HRM set emp_name=? where
emp_id=?");
stmt.setString(1, "riya");
stmt.setInt(2, 5);
int i =

stmt.executeUpdate();

System.out.println(i + "

records update");

} catch

(ClassNotFoundException |

SQLException e)

{ System.out.println(e);

Output:

1 records update
BUILD SUCCESSFUL (total time: 0 seconds)

+--------+----------+------------+
| emp_id | emp_name | emp_salary |
+--------+----------+------------+
| 1 | sefali | 23000 |
| 2 | prachi | 21000 |
| 3 | pooja | 22000 |
| 4 | Aashish | 32000 |
| 1 | sefali | 23000 |
| 5 | riya | 43000 |
+--------+----------+------------+
6 rows in set (0.00 sec)
JDBC-CO2160707.2
8) Get the following metadata of the database using DatabaseMetaData and
ResultSetMetaData
a)List of tables
b)List of columns in a table with name and size

a)List of tables

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
importsun.util.logging.PlatformLogger;
public class P8_a {
Connection con;
Statement s;
ResultSet rs;
P8_a() throws SQLException
{
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException ex){

Logger.getLogger(Tablesinmysql.class.getName()).log(Level.SEVERE,nu
ll,ex);
}

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql"
,"root","mysql");
s=con.createStatement();
}
public static void main(String[] args) throws
SQLException{ Tablesinmysql t=new Tablesinmysql();
t.disptables();
}
void disptables()
{
try{
rs=s.executeQuery("show tables");
while(rs.next())
{
System.out.println(rs.getString(1));
}
}catch(SQLException ex){

Logger.getLogger(Tablesinmysql.class.getName()).log(Level.SEVERE,nu
ll,ex);
System.out.println("cannot execute query");
}
}
private static class Tablesinmysql {

public Tablesinmysql() {
}

private void disptables() {


throw new UnsupportedOperationException("Not supported
yet."); //To change body of generated methods, choose Tools |
Templates.
}
}
}

Output:

run:
HRM

b)List of columns in a table with name and size.


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

public class P8_b {


private static final String DRIVER = "com.mysql.jdbc.Driver";

private static final String URL =


"jdbc:mysql://localhost:3306/mysql";

private static final String USERNAME = "root";

private static final String PASSWORD = "mysql";

public static void main(String[] args) throws Exception


{ Class.forName(DRIVER);
Connection connection = DriverManager.getConnection(URL,
USERNAME, PASSWORD);

DatabaseMetaData metadata = connection.getMetaData();


ResultSet resultSet = metadata.getColumns(null, null,
"HRM", null);
while (resultSet.next()) {
String name = resultSet.getString("COLUMN_NAME");
String type = resultSet.getString("TYPE_NAME");
int size = resultSet.getInt("COLUMN_SIZE");

System.out.println("Column name: [" + name + "]; type: [" +


type + "]; size: [" + size + "]");
}
connection.close();
}
}
Output:
run:
Column name: [emp_id]; type: [varchar]; size: [10]
Column name: [emp_name]; type: [varchar]; size: [10]
Column name: [emp_salary]; type: [varchar]; size: [10]

JDBC-CO2160707.2
9) Implement the transaction using JDBC commit and rollback.

/*
* To change this license header, choose License Headers in
Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//databse connection string ="jdbc:mysql://localhost:3306/mydb
package transwithoutsavepoint;

import java.util.*;
import java.sql.*;
class Transwithoutsavepoint
{
Scanner sc;
Connection con;
Statement st;
ResultSet rs;
String fn,ln,city;
int ch;

Transwithoutsavepoint()throws
Exception {
sc = new Scanner(System.in);

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

con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/login","roo
t","mysql");
con.setAutoCommit(false);

st = con.createStatement();
}

public static void main(String [] args)throws Exception


{
Transwithoutsavepoint d = new Transwithoutsavepoint();
d.menu();
}

void menu()throws Exception


{
do
{
System.out.println("1.Insert");
System.out.println("2.Delete");
System.out.println("3.Update");
System.out.println("4.Display");
System.out.println("5.Search");
System.out.println("6.Exit");

System.out.println("Enter Your
Choice :"); ch = sc.nextInt();

switch(ch)
{
case 1:
insert();
break;

case 2:
delete();
break;

case 3:
update();
break;

case 4:
display();
break;

case 5:
search();
break;
case 6:
System.out.println("Bye");
break;
default:
System.out.println("\nWrong
Choice\n");
}
}while(ch!=6);
}

void insert()throws Exception


{
System.out.println("Enter FirstName :");
fn = sc.next();

System.out.println("Enter
LastName :"); ln = sc.next();

System.out.println("Enter City :");


city = sc.next();

String q = "insert into login1 (fname,lname,city)


values ('"+fn+"','"+ln+"','"+city+"')";
int n = st.executeUpdate(q);
if(n==0)
{
System.out.println("Cannot execute insert
querry");
con.rollback();
System.exit(n);

}
else
{
System.out.println(n+"Row is Inserted");
con.commit();
}
}

void delete()throws Exception


{
System.out.println("Enter City :");
city = sc.next();

String q = "delete from login1 where


city='"+city+"'"; int n = st.executeUpdate(q);
if(n==0)
{
System.out.println("Cannot execute delete
querry");
con.rollback();
System.exit(n);
}
else
{
System.out.println(n+"rows Are Deleted
"); con.commit();
}
}

void update()throws Exception


{
System.out.println("Enter The First
Name:"); fn = sc.next();

System.out.println("Enter The Last


Name:"); ln = sc.next();

System.out.println("Enter The
City :"); city = sc.next();

String q = "update login1 set


lname='"+ln+"',city='"+city+"' where fname='"+fn+"'";
int n = st.executeUpdate(q);
if(n==0)
{
System.out.println("Cannot perform update
operation");
con.rollback();
System.exit(n);
}
else
{
System.out.println("\t"+n+"Is Updated...");
con.commit();
}
}
void display()throws Exception
{
String q ="select * from login1";

rs = st.executeQuery(q);
System.out.println("First_name\tLast_name\tCity\n");
while(rs.next()==true)
{
fn = rs.getString("fname");
ln = rs.getString("lname");
city = rs.getString("city");

System.out.println(fn+"\t\t"+ln+"\t\t"+city);
}
System.out.println("\n\n");
}

void search()throws Exception


{
System.out.println("Enter City Name :");
city = sc.next();

String q = "select * from login1 where city='"+city+"'";

rs = st.executeQuery(q);

if(rs.next()==true)
{
fn = rs.getString("fname");
ln = rs.getString("lname");
city = rs.getString("city");

System.out.println(fn+"\t\t"+ln+"\t\t"+city);
}
else
{
System.out.println("\tNot Found!!!");
System.exit(0);
}
}
}
Output:
run:
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
1
Enter FirstName :
sajeda
Enter LastName :
patel
Enter City :
surat
1Row is Inserted
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
1
Enter FirstName :
riddhi
Enter LastName :
vansadia
Enter City :
surat
1Row is Inserted
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
1
Enter FirstName :
shreya
Enter LastName :
bhikhadiya
Enter City :
mumbai
1Row is Inserted
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
2
Enter City :
mumbai
1rows Are Deleted
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
3
Enter The First Name:
sajeda
Enter The Last Name:
patel
Enter The City :
baroda
1Is Updated...
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
4
First_name Last_name City

sajeda patel baroda


riddhi vansadia surat

1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
5
Enter City Name :
surat
riddhi vansadia surat
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
6
Bye
JDBC-CO2160707.2
10) Implement the transaction using SavePoint of JDBC and rollback to a particular
SavePoint in Transaction.
//databse connection string
="jdbc:mysql://localhost:3306/mydb package databasedemo;

import java.util.*;
import java.sql.*;
class Databasedemo
{
Scanner sc;
Connection con;
Statement st;
ResultSet rs;
String fn,ln,city;
int ch;

Databasedemo()throws Exception
{
sc = new Scanner(System.in);

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

con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root
","mysql");
con.setAutoCommit(false);

st = con.createStatement();
}

public static void main(String [] args)throws Exception


{
Databasedemo d = new Databasedemo();
d.menu();
}

void menu()throws Exception


{
do
{
System.out.println("1.Insert");
System.out.println("2.Delete");
System.out.println("3.Update");
System.out.println("4.Display");
System.out.println("5.Search");
System.out.println("6.Exit");

System.out.println("Enter Your
Choice :"); ch = sc.nextInt();

switch(ch)
{
case 1:
insert();
break;

case 2:
delete();
break;

case 3:
update();
break;

case 4:
display();
break;

case 5:
search();
break;
case 6:
System.out.println("Bbye");
break;
default:
System.out.println("\nWrong
Choice\n");
}
}while(ch!=6);
}

void insert()throws Exception


{
System.out.println("Enter FirstName :");
fn = sc.next();

System.out.println("Enter LastName :");


ln = sc.next();

System.out.println("Enter City :");


city = sc.next();

String q = "insert into student


(fname,lname,city) values ('"+fn+"','"+ln+"','"+city+"')";

Savepoint beforeinsert=con.setSavepoint();

int n = st.executeUpdate(q);
if(n==0)
{
System.out.println("Cannot execute insert
querry");
con.rollback(beforeinsert);

}
else
{
System.out.println(n+"Row is Inserted");
con.commit();
}
}

void delete()throws Exception


{
System.out.println("Enter City :");
city = sc.next();

String q = "delete from student


where city='"+city+"'";
Savepoint beforedelete=con.setSavepoint();

int n = st.executeUpdate(q);
if(n==0)
{
System.out.println("Cannot execute delete
querry");
con.rollback(beforedelete);
}
else
{
System.out.println(n+"rows Are Deleted
"); con.commit();
}
}

void update()throws Exception


{
System.out.println("Enter The First Name:");
fn = sc.next();

System.out.println("Enter The Last Name:");


ln = sc.next();

System.out.println("Enter The City :");


city = sc.next();

String q = "update student set


lname='"+ln+"',city='"+city+"' where fname='"+fn+"'";

Savepoint beforeupdate=con.setSavepoint();

int n = st.executeUpdate(q);
if(n==0)
{
System.out.println("Cannot perform update
operation");
con.rollback(beforeupdate);
}
else
{
System.out.println("\t"+n+"Is Updated...");
con.commit();
}
}

void display()throws Exception


{
String q ="select * from student";

rs = st.executeQuery(q);
System.out.println("First_name\tLast_name\tCity\n");
while(rs.next()==true)
{
fn = rs.getString("fname");
ln = rs.getString("lname");
city = rs.getString("city");

System.out.println(fn+"\t\t"+ln+"\t\t"+city);
}
System.out.println("\n\n");
}

void search()throws Exception


{
System.out.println("Enter City Name :");
city = sc.next();

String q = "select * from student where


city='"+city+"'";

rs = st.executeQuery(q);

if(rs.next()==true)
{
fn = rs.getString("fname");
ln = rs.getString("lname");
city = rs.getString("city");

System.out.println(fn+"\t\t"+ln+"\t\t"+city);
}
else
{
System.out.println("\tNot Found!!!");
}
}
}
Output:
run:
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
1
Enter FirstName :
sajeda
Enter LastName :
patel
Enter City :
surat
1Row is Inserted
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
1
Enter FirstName :
riddhi
Enter LastName :
vansadia
Enter City :
surat
1Row is Inserted
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
1
Enter FirstName :
shreya
Enter LastName :
bhikhadiya
Enter City :
mumbai
1Row is Inserted
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
2
Enter City :
mumbai
1rows Are Deleted
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
3
Enter The First Name:
sajeda
Enter The Last Name:
patel
Enter The City :
baroda
1Is Updated...
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
4
First_name Last_name City

sajeda patel baroda


riddhi vansadia surat

1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice :
5
Enter City Name :
surat
riddhi vansadia surat
1.Insert
2.Delete
3.Update
4.Display
5.Search
6.Exit
Enter Your Choice:
6
Bye
Java Servlet-CO2160707.4

11  Create Servlet file and study web descriptor file. 

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author ACER
*/
@WebServlet(urlPatterns = {"/HelloServlet"})
public class HelloServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and
<code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample
code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet HelloServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet HelloServlet at " +
request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.


Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Output:

Servlet HelloServlet at /WebApplication1

Starting GlassFish Server


GlassFish Server is running.
Incrementally deploying WebApplication1
Completed incremental distribution of WebApplication1
run-deploy:
Browsing: http://localhost:8080/WebApplication1/HelloServlet
run-display-browser:
run:
BUILD SUCCESSFUL (total time: 13 seconds)
Cookies, session, URL Rewriting CO2160707.3

13 Create login form and perform state management using Cookies, HttpSession and URL Rewriting.
//set Cookie

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;

/**
*
* @author sefali
*/
@WebServlet(urlPatterns = {"/setCookie"})
public class setCookie extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and
<code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample
code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet setCookie</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet setCookie at " +
request.getContextPath() + "</h1>");
Cookie c = new Cookie("name","sefali");
response.addCookie(c);
out.println("</body>");
out.println("</html>");
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.


Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

//read Cookie

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author ACER
*/
@WebServlet(urlPatterns = {"/readCookie"})
public class readCookie extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and
<code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample
code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet readCookie</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet readCookie at " +
request.getContextPath() + "</h1>");
Cookie[] cookies = request.getCookies();
for(Cookie c:cookies){
out.println("<p>"+c.getName()+"</p>");
out.println("<p>"+c.getValue()+"</p>");
//delete cookie
c.setValue(null);
c.setMaxAge(0);
response.addCookie(c);
}
out.println("</body>");
out.println("</html>");
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.


Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

//set Session

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
*
* @author stu_third
*/
public class SessionServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and
<code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample
code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SessionServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet SessionServlet at " +
request.getContextPath() + "</h1>");
//set session

HttpSession s = request.getSession(true);
s.setAttribute("username","sefali");
s.setAttribute("password","sefu");

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

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.


Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

//read and delete Session

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
*
* @author sefali
*/
@WebServlet(urlPatterns = {"/ReadSessionServlet"})
public class ReadSessionServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and
<code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample
code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ReadSessionServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet ReadSessionServlet at " +
request.getContextPath() + "</h1>");
//read attribute
HttpSession s = request.getSession();
out.println(s.getAttribute("username"));

//remove attribute

s.removeAttribute("username");
s.invalidate();
out.println(s.getAttribute("password"));

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

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.


Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

//URLRewritting

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author stu_third
*/
@WebServlet(urlPatterns = {"/formServlet"})
public class formServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and
<code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample
code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet formServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet formServlet at " +
request.getContextPath() + "</h1>");

String username = request.getParameter("username");


String password = request.getParameter("password");
String url=
"http://localhost:8080/URLRewrittingWebApplication2/secondServlet?
username=" +username+ "&password=" +password;
out.println("<a href = \""+url+"\">ClickHere </a>");

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

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.


Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

//secondServlet.java code

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author stu_third
*/
@WebServlet(urlPatterns = {"/secondServlet"})
public class secondServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and
<code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample
code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet secondServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet secondServlet at " +
request.getContextPath() + "</h1>");

String username = request.getParameter("username");


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

out.println("username:" +username+ "<br />password:"


+password);

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

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.


Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}
Output:
//set Cookie
Servlet setCookie at /CookieSessionWebApplication2

//read Cookie

Servlet readCookie at
/CookieSessionWebApplication2
username

sefali

//delete Cookie

Servlet readCookie at /CookieSessionWebApplication2

//set Session
Servlet SessionServlet at
/WebApplication1
JSESSIONI 23f321fb36d1b668937e001 localho / Sessio 38 ✓
D 42230 st WebApplicatio n
n1

//read Session

Servlet ReadSessionServlet at
/WebApplication1
sefali
//delete Session

Servlet ReadSessionServlet at
/WebApplication1
null

//URLrewritting

Servlet formServlet at
/URLRewrittingWebApplication2
ClickHere

Servlet secondServlet at
/URLRewrittingWebApplication2
username:sefali
password:sefu

You might also like