TCP/UDP Socket Programming Examples
TCP/UDP Socket Programming Examples
1
1) Create chat application using either TCP and UDP protocol.
[Link]:
import [Link];
import [Link].*;
import [Link].*;
class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(4444);
Socket sock=[Link](); try
{
DataInputStream din=new
DataInputStream([Link]());
DataOutputStream dout=new
DataOutputStream([Link]());
String msgsend="",msgrec="";
BufferedReader st =new BufferedReader(new
InputStreamReader([Link]));
while(true)
{
msgrec=(String)[Link]();
if([Link]("stop"))
{ [Link]("\nClosing the Connection");
break;
}
[Link]("Received Message:"+msgrec);
[Link]("Enter Message to send:");
msgsend=[Link]();
[Link](msgsend);
[Link]();
}
}
catch(Exception e){}
}
}
[Link]:
import [Link];
import [Link].*;
import [Link].*;
class Client
{
public static void main(String[] args) throws Exception
{
Socket sock=new Socket("localhost",4444);
try
{
DataInputStream din=new
DataInputStream([Link]());
DataOutputStream dout=new
DataOutputStream([Link]());
String msgrec="",msgsend="";
BufferedReader st =new BufferedReader(new
InputStreamReader([Link]));
while(true)
{
[Link]("Enter Message to
send:"); msgsend=[Link]();
[Link](msgsend);
if([Link]("stop")) {
break;
}
[Link]();
msgrec=(String)[Link]();
[Link]("Received Message:"+msgrec);
}
}
catch(Exception e)
{
}
finally{[Link]();}
}
Output:
At client side:
run:
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
[Link]:
import [Link].*;
import [Link].*;
class Myserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(6666);
Socket s=[Link]();
FileInputStream fin=new FileInputStream("[Link]");
DataOutputStream dout=new
DataOutputStream([Link]());
int r;
while((r=[Link]())!=-1)
{
[Link](r);
}
[Link]("\n Filetranfer Completed");
[Link]();
[Link]();
}
}
[Link]:
import [Link].*;
import [Link].*;
public class MyClient
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("localhost",6666);
if([Link]()) {
At server side:
run:
Filetranfer Completed
At client side:
run:
Connection Established for transfer of
file File Received
[Link]:
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.
[Link]:
import [Link].*;
import [Link].*;
//import [Link];
import [Link];
public class Server3 {
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(2345);
Socket s=[Link](); DataInputStream
din=new
DataInputStream([Link]());
DataOutputStream dout=new
DataOutputStream([Link]());
int no;
no=(int)[Link]();
int input[]=new int[no];
for(int i=0;i<no;i++)
{
input[i]=(int)[Link]();
}
[Link]("Received data for sort are:");
for(int i=0;i<no;i++)
{
[Link](input[i]);
}
[Link](input);
[Link]("Sorted Array:");
for(int i=0;i<no;i++)
{
[Link](input[i]);
}
for(int i=0;i<no;i++)
{
[Link](input[i]);
[Link]();
}
}
catch(IOException e)
{
}
}
}
[Link]:
import [Link].*;
import [Link].*;
import [Link];
public class Client3
{
public static void main(String[] args)
{
try
{
Socket s=new Socket("localhost",2345);
DataInputStream din=new
DataInputStream([Link]());
DataOutputStream dout=new
DataOutputStream([Link]());
int no;
[Link]("Enter no of elements you want to
sort:");
Scanner st=new Scanner([Link]);
no=[Link]();
int input[]=new int[no];
int output[]=new int[no];
for(int i=0;i<no;i++)
{
[Link]("\nEnter "+(i+1)+"\t"+"Element:");
input[i]=[Link]();
}
[Link](no);
for(int i=0;i<no;i++)
{
[Link](input[i]);
[Link]();
}
for(int i=0;i<no;i++)
{
output[i]=(int)[Link]();
}
[Link]("\nSorted array:");
for(int i=0;i<no;i++) {
[Link](output[i]);
}
[Link]();
}
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.
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class Server4 implements Runnable
{
Socket sock;
Server4(Socket sock)
{
[Link]=sock;
}
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(9999);
while(true)
{
Socket s=[Link]();
[Link]("Connected...");
new Thread(new Server4(s)).start();
}
}
@Override
public void run()
{
try
{
DataInputStream din=new
DataInputStream([Link]());
DataOutputStream dout=new
DataOutputStream([Link]());
Date date=new Date(); SimpleDateFormat
s1=new SimpleDateFormat("hh:mm:ss a");
String time=[Link](date);
[Link](time);
[Link]();
SimpleDateFormat s2=new
SimpleDateFormat("EEEE");
String day=[Link](date);
[Link](day);
[Link]();
}
catch(IOException e){}
}
}
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class Client4
{
public static void main(String[] args)
{
try
{
Socket s=new Socket("localhost",9999);
DataInputStream din=new
DataInputStream([Link]());
DataOutputStream dout=new
DataOutputStream([Link]());
String time,day;
time=(String)[Link]();
[Link]("Time is "+time);
day=(String)[Link]();
[Link]("Day is "+day);
[Link]();
}
catch(IOException e){}
}
}
Output:
At client side:
run:
Time is [Link] 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 [Link].*;
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 [Link].*;
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 [Link].*;
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 [Link].*;
import [Link];
import [Link];
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 [Link].*;
try {
[Link]("[Link]");
(ClassNotFoundException |
SQLException e)
{ [Link](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 [Link].*;
[Link]();
[Link](i + "
records update");
} catch
(ClassNotFoundException |
SQLException e)
{ [Link](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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link];
public class P8_a {
Connection con;
Statement s;
ResultSet rs;
P8_a() throws SQLException
{
try{
[Link]("[Link]");
}
catch(ClassNotFoundException ex){
[Link]([Link]()).log([Link],nu
ll,ex);
}
con=[Link]("jdbc:mysql://localhost:3306/mysql"
,"root","mysql");
s=[Link]();
}
public static void main(String[] args) throws
SQLException{ Tablesinmysql t=new Tablesinmysql();
[Link]();
}
void disptables()
{
try{
rs=[Link]("show tables");
while([Link]())
{
[Link]([Link](1));
}
}catch(SQLException ex){
[Link]([Link]()).log([Link],nu
ll,ex);
[Link]("cannot execute query");
}
}
private static class Tablesinmysql {
public Tablesinmysql() {
}
Output:
run:
HRM
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 [Link].*;
import [Link].*;
class Transwithoutsavepoint
{
Scanner sc;
Connection con;
Statement st;
ResultSet rs;
String fn,ln,city;
int ch;
Transwithoutsavepoint()throws
Exception {
sc = new Scanner([Link]);
[Link]("[Link]");
con =
[Link]("jdbc:mysql://localhost:3306/login","roo
t","mysql");
[Link](false);
st = [Link]();
}
[Link]("Enter Your
Choice :"); ch = [Link]();
switch(ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
update();
break;
case 4:
display();
break;
case 5:
search();
break;
case 6:
[Link]("Bye");
break;
default:
[Link]("\nWrong
Choice\n");
}
}while(ch!=6);
}
[Link]("Enter
LastName :"); ln = [Link]();
}
else
{
[Link](n+"Row is Inserted");
[Link]();
}
}
[Link]("Enter The
City :"); city = [Link]();
rs = [Link](q);
[Link]("First_name\tLast_name\tCity\n");
while([Link]()==true)
{
fn = [Link]("fname");
ln = [Link]("lname");
city = [Link]("city");
[Link](fn+"\t\t"+ln+"\t\t"+city);
}
[Link]("\n\n");
}
rs = [Link](q);
if([Link]()==true)
{
fn = [Link]("fname");
ln = [Link]("lname");
city = [Link]("city");
[Link](fn+"\t\t"+ln+"\t\t"+city);
}
else
{
[Link]("\tNot Found!!!");
[Link](0);
}
}
}
Output:
run:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
1
Enter FirstName :
sajeda
Enter LastName :
patel
Enter City :
surat
1Row is Inserted
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
1
Enter FirstName :
riddhi
Enter LastName :
vansadia
Enter City :
surat
1Row is Inserted
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
1
Enter FirstName :
shreya
Enter LastName :
bhikhadiya
Enter City :
mumbai
1Row is Inserted
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
2
Enter City :
mumbai
1rows Are Deleted
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
3
Enter The First Name:
sajeda
Enter The Last Name:
patel
Enter The City :
baroda
1Is Updated...
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
4
First_name Last_name City
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
5
Enter City Name :
surat
riddhi vansadia surat
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
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 [Link].*;
import [Link].*;
class Databasedemo
{
Scanner sc;
Connection con;
Statement st;
ResultSet rs;
String fn,ln,city;
int ch;
Databasedemo()throws Exception
{
sc = new Scanner([Link]);
[Link]("[Link]");
con =
[Link]("jdbc:mysql://localhost:3306/mydb","root
","mysql");
[Link](false);
st = [Link]();
}
[Link]("Enter Your
Choice :"); ch = [Link]();
switch(ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
update();
break;
case 4:
display();
break;
case 5:
search();
break;
case 6:
[Link]("Bbye");
break;
default:
[Link]("\nWrong
Choice\n");
}
}while(ch!=6);
}
Savepoint beforeinsert=[Link]();
int n = [Link](q);
if(n==0)
{
[Link]("Cannot execute insert
querry");
[Link](beforeinsert);
}
else
{
[Link](n+"Row is Inserted");
[Link]();
}
}
int n = [Link](q);
if(n==0)
{
[Link]("Cannot execute delete
querry");
[Link](beforedelete);
}
else
{
[Link](n+"rows Are Deleted
"); [Link]();
}
}
Savepoint beforeupdate=[Link]();
int n = [Link](q);
if(n==0)
{
[Link]("Cannot perform update
operation");
[Link](beforeupdate);
}
else
{
[Link]("\t"+n+"Is Updated...");
[Link]();
}
}
rs = [Link](q);
[Link]("First_name\tLast_name\tCity\n");
while([Link]()==true)
{
fn = [Link]("fname");
ln = [Link]("lname");
city = [Link]("city");
[Link](fn+"\t\t"+ln+"\t\t"+city);
}
[Link]("\n\n");
}
rs = [Link](q);
if([Link]()==true)
{
fn = [Link]("fname");
ln = [Link]("lname");
city = [Link]("city");
[Link](fn+"\t\t"+ln+"\t\t"+city);
}
else
{
[Link]("\tNot Found!!!");
}
}
}
Output:
run:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
1
Enter FirstName :
sajeda
Enter LastName :
patel
Enter City :
surat
1Row is Inserted
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
1
Enter FirstName :
riddhi
Enter LastName :
vansadia
Enter City :
surat
1Row is Inserted
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
1
Enter FirstName :
shreya
Enter LastName :
bhikhadiya
Enter City :
mumbai
1Row is Inserted
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
2
Enter City :
mumbai
1rows Are Deleted
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
3
Enter The First Name:
sajeda
Enter The Last Name:
patel
Enter The City :
baroda
1Is Updated...
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
4
First_name Last_name City
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice :
5
Enter City Name :
surat
riddhi vansadia surat
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Enter Your Choice:
6
Bye
Java Servlet-CO2160707.4
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
*
* @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 {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
/* TODO output your page here. You may use following sample
code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet HelloServlet</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<h1>Servlet HelloServlet at " +
[Link]() + "</h1>");
[Link]("</body>");
[Link]("</html>");
}
}
/**
* 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:
13 Create login form and perform state management using Cookies, HttpSession and URL Rewriting.
//set Cookie
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
*
* @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 {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
/* TODO output your page here. You may use following sample
code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet setCookie</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<h1>Servlet setCookie at " +
[Link]() + "</h1>");
Cookie c = new Cookie("name","sefali");
[Link](c);
[Link]("</body>");
[Link]("</html>");
}
}
/**
* 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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
*
* @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 {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
/* TODO output your page here. You may use following sample
code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet readCookie</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<h1>Servlet readCookie at " +
[Link]() + "</h1>");
Cookie[] cookies = [Link]();
for(Cookie c:cookies){
[Link]("<p>"+[Link]()+"</p>");
[Link]("<p>"+[Link]()+"</p>");
//delete cookie
[Link](null);
[Link](0);
[Link](c);
}
[Link]("</body>");
[Link]("</html>");
}
}
/**
* 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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
*
* @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 {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
/* TODO output your page here. You may use following sample
code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet SessionServlet</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<h1>Servlet SessionServlet at " +
[Link]() + "</h1>");
//set session
HttpSession s = [Link](true);
[Link]("username","sefali");
[Link]("password","sefu");
[Link]("</body>");
[Link]("</html>");
}
}
/**
* 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>
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
*
* @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 {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
/* TODO output your page here. You may use following sample
code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet ReadSessionServlet</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<h1>Servlet ReadSessionServlet at " +
[Link]() + "</h1>");
//read attribute
HttpSession s = [Link]();
[Link]([Link]("username"));
//remove attribute
[Link]("username");
[Link]();
[Link]([Link]("password"));
[Link]("</body>");
[Link]("</html>");
}
}
/**
* 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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
*
* @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 {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
/* TODO output your page here. You may use following sample
code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet formServlet</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<h1>Servlet formServlet at " +
[Link]() + "</h1>");
[Link]("</body>");
[Link]("</html>");
}
}
/**
* 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>
//[Link] code
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
*
* @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 {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
/* TODO output your page here. You may use following sample
code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet secondServlet</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<h1>Servlet secondServlet at " +
[Link]() + "</h1>");
[Link]("</body>");
[Link]("</html>");
}
}
/**
* 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
//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