Download as pdf or txt
Download as pdf or txt
You are on page 1of 257

MAHARASHTRA STATE

BOARD OF TECHNICAL EDUCATION


Certificate

This is to certify that Mr. / Ms. …Aniket Vijay Mane


Roll No. 142, of Fifth Semester of Diploma in Computer engineering of
Institute,
Thakur ppolytechnic
(Code: …………...) has completed the term work satisfactorily in course
Advanced Java Programming (22517) for the academic year 2021.. to 2022
as prescribed in the curriculum.

Place: …………… Enrollment No:2005220389


Date: …………… Exam. Seat No: ……………

Subject Teacher Head of the


Department Principal

Seal of
Institution
.
Advanced Java Programming (22517)

Preface

The primary focus of any engineering laboratory/field work in the technical education
system is to develop the much-needed industry relevant competencies and skills. With this in
view, MSBTE embarked on this innovative ‘I’ Scheme curricula for engineering Diploma
programmes with outcome-based education as the focus and accordingly, relatively large
amount of time is allotted for the practical work. This displays the great importance of
laboratory work making each teacher, instructor and student to realize that every minute of
the laboratory time need to be effectively utilized to develop these outcomes, rather than
doing other mundane activities. Therefore, for the successful implementation of this
outcome-based curriculum, every practical has been designed to serve as a ‘vehicle’ to
develop this industry identified competency in every student. The practical skills are difficult
to develop through ‘chalk and duster’ activity in the classroom situation. Accordingly, the ‘I’
scheme laboratory manual development team designed the practicals to focus on outcomes,
rather than the traditional age-old practice of conducting practical’s to ‘verify the theory’
(which may become a byproduct along the way).

This laboratory manual is designed to help all stakeholders, especially the students,
teachers and instructors to develop in the student the pre-determined outcomes. It is expected
from each student that at least a day in advance, they have to thoroughly read the concerned
practical procedure that they will do the next day and understand minimum theoretical
background associated with the practical. Every practical in this manual begins by identifying
the competency, industry relevant skills, course outcomes and practical outcomes which
serve as a key focal point for doing the practical. Students will then become aware about the
skills they will achieve through procedure shown there and necessary precautions to be taken,
which will help them to apply in solving real-world problems in their professional life.

This manual also provides guidelines to teachers and instructors to effectively facilitate
student-centered lab activities through each practical exercise by arranging and managing
necessary resources in order that the students follow the procedures and precautions
systematically ensuring the achievement of outcomes in the students.

Advanced Java Programming is used as mainstream programming language in


application development. This course aims to design and develop Java based applications.
Using Advanced Java programming, students will be able to develop web applications, GUI,
applications as well as network-based applications. Students will be able to write the
programs like applet, Servlets, connections to Databases using JDBC and socket
programming.

Although all care has been taken to check for mistakes in this laboratory manual, yet it
is impossible to claim perfection especially as this is the first edition. Any such errors and
suggestions for improvement can be brought to our notice and are highly welcome.
Programme Outcomes (POs) to be achieved through Practical’s of this
Course:

Maharashtra State Board of Technical Education i


Advanced Java Programming (22517)

Following programme outcomes are expected to be achieved significantly out of the ten
programme outcomes and Information Technology programme specific outcomes through
the practical’s of the course on Advanced Java Programming.

PO 1. Basic knowledge: Apply knowledge of basic mathematics, science and basic


engineering to solve the problems related to application of computers and communication
services in storing, manipulating and transmitting data, often in the context of a business or
other enterprise.

PO 2. Discipline knowledge: Apply Computer Engineering knowledge to solve broad-based


Computer Engineering related problems.

PO 3. Experiments and practice: Plan to perform experiments, practices and to use the results
to solve Computer Engineering related problems.

PO 4. Engineering tools: Apply appropriate Computer Engineering related techniques/ tools


with an understanding of the limitations.

PO 5. The engineer and society: Assess societal, health, safety and legal issues and the
consequent responsibilities relevant to practice in the field of Computer Engineering.

PO 6. Environment and sustainability: Apply Computer related engineering solutions for


sustainable development practices in environmental contexts.

PO 7. Ethics: Apply ethical principles for commitment to professional ethics, responsibilities


and norms of practice in the field of Information Technology.

PO 8. Individual and team work: Function effectively as a leader and team member in diverse/
multidisciplinary teams.

PO 9. Communication: Communicate effectively in oral and written form.

PO 10. Life-long learning: Engage in independent and life-long learning along with the
technological changes in the IT and allied industry.

Maharashtra State Board of Technical Education ii


Advanced Java Programming (22517)

Practical - Course Outcome Matrix


Course Outcome:
a. Develop program using GUI framework (AWT and Swing)
b. Handle events of AWT and Swing Components.
c. Develop programs to handle events in Java Programming.
d. Develop Java Programs using Networking Concepts.
e. Develop programs using Database.
f. Develop programs using Servlets.
CO CO CO CO CO CO
S. No. Title of the Practical
a. b. c. d. e. f
Write a program to demonstrate the use
of AWT components like Label,
*1 Textfield, TextArea, Button, Checkbox,
√ - - - - -
RadioButton etc.
*2 Write a program to design a form using
√ - - - - -
the components List and Choice.
*3 Write a program to design simple
√ - - - - -
calculator with the use of GridLayout
Write a program to create a two-level
*4 card deck that allows the user to select √ - - - - -
component of Panel using CardLayout
Write a program using AWT to create a
menubar where menubar
*5 contains menu items such as File, √ - - - - -
Edit, View and create a submenu
under the File menu: New and Open.
Write a program using swing to display
a ScrollPane and JcomboBox in an
*6 √ √ - - - -
Japplet with the items – English,
Marathi, Hindi, Sanskrit.
Write a program to create a Jtree. - √ - - - -
*7
8 Write a program to create a JTable. - √ - - - -
Write a program to launch a
9 - √ - - - -
JProgressBar
Write a program to demonstrate status
of key on Applet window such as
* 10 KeyPressed, KeyReleased, KeyUp,
√ √ √ - - -
KeyDown
Write a program to demonstrate various
* 11 mouse events using MouseListener and √ √ √ - - -
MouseMotionListener interface

Maharashtra State Board of Technical Education iii


Advanced Java Programming (22517)

Write a program to demonstrate the use


* 12 of JTextField and JPasswordField using √ √ √ - - -
Listener Interface

Write a program to demonstrate the use


13 √ √ √ - - -
of WindowAdapter class.
Write a program to demonstrate the use
14 of InetAddress class and its factory - - - √ - -
* methods.
Write a program to demonstrate the use
15 of URL and URLConnection class and - - - √ - -
* its methods
Write a program to implement chat
16 Server using Server Socket and Socket - - - √ - -
class.
Write a program to demonstrate use of
17 - - - √ - -
DataGram Socket and DataGram Packet
Write a program to insert and retrieve
* 18 - - - - √ -
the data from database using JDBC
Write a program to demonstrate the use
19 of PreparedStatement and ResultSet - - - - √ -
interface
Write a program to update and delete a
20 - - - - √ -
record from a database table.
Write a program to demonstrate the use
21 of HttpServlet as a parameterized √ - - - - √
servlet
Write a Servlet program to send
22 username and password using HTML √ - - - - √
* forms and authenticate the user
Write a program to create Session using
23 √ - - - - √
HttpSession class
Write a program to implement Session
24 √ - - - - √
tracking using Cookies.

List of Industry Relevant Skills

The following industry relevant skills of the competency “Apply advanced Java
Programming Concepts” are expected to be developed in you by performing practical’s of
this laboratory manual.
1. Create GUI Applications.
2. Handle events using event delegation model.

Maharashtra State Board of Technical Education iv


Advanced Java Programming (22517)

3. Write and execute programs for web based as well as window-based applications.
4. Write and execute programs for networking.
5. Write and execute programs to store the data in database to perform CRUD operations.
6. Write and execute programs for client server using Servlets.

Maharashtra State Board of Technical Education v


Advanced Java Programming (22517)

Brief Guidelines to Teachers

Hints regarding strategies to be used


1. Teacher shall explain prior concepts to the students before starting each experiment.
2. For practical’s requiring tools to be used, teacher should provide the demonstration of
the practical emphasizing the skills, which the student should achieve.
3. Involve students in the activities during the conduct of each experiment.
4. Teachers should give opportunity to students for hands-on after the demonstration.
5. Assess the skill achievement of the students and COs of each unit.
6. Teacher is expected to share the skills and competencies to be developed in the students.
7. Teacher should ensure that the respective skills and competencies are developed in the
students after the completion of the practical exercise.
8. Teacher may provide additional knowledge and skills to the students even though that
may not be covered in the manual but are expected from the students by the industries.
9. Teacher may suggest the students to refer additional related literature of the reference
books/websites/seminar proceedings etc.
10. During assessment teacher is expected to ask questions to the students to tap their
knowledge and skill related to that practical.

Instructions for Students

Student shall read the points given below for understanding the theoretical concepts and
practical applications.
1. Students shall listen carefully the lecture given by teacher about importance of subject,
learning structure, course outcomes.
2. Students shall organize the work in the group of two or three members and make a record
of all observations.
3. Students shall understand the purpose of experiment and its practical implementation.
4. Students shall write the answers of the questions during practical.
5. Student should feel free to discuss any difficulty faced during the conduct of practical.
6. Students shall develop web based and window-based applications as expected by the
industries.

Maharashtra State Board of Technical Education vi


Advanced Java Programming (22517)

7. Student shall attempt to develop related hands on skills and gain confidence.
8. Students shall refer technical magazines; websites related to the scope of the subjects
and update their knowledge and skills.
9. Students shall develop self-learning techniques.
10. Students should develop habit to submit the write-ups on the scheduled dates and time.

Content Page
List of Practical’s and Progressive Assessment Sheet

Date of Dated
Sr. Page Date of Assessment Remarks
Title of the practical submissi sign. of
No. No. performance Marks (50) (if any)
on teacher
Write a program to
demonstrate the use of
AWT components like
1. Label, Textfield, 1 2/09/21 09/09/21
TextArea, Button,
Checkbox, RadioButton
etc.
Write a program to
design a form using the
2. 6 3/09/21 16/09/21
components List and
Choice.
Write a program to
design simple calculator
3. 12 03/09/21 16/09/21
with the use of
GridLayout
Write a program to create
a two-level card deck that
allows the user to select
4. 19 16/09/21 23/09/21
component of Panel
using
CardLayout

Maharashtra State Board of Technical Education vii


Advanced Java Programming (22517)

Write a program using


AWT to create a menu
bar where menu bar
contains menu items such
5. 25 17/09/21 24/09/21
as File, Edit, View and
create a submenu under
the File menu: New and
Open.
Write a program using
swing to display a
ScrollPane and
6. 31 17/09/21
JcomboBox in an Japplet 24/09/21
with the items – English,
Marathi, Hindi, Sanskrit.
Write a program to create
7. 37 23/09/21 30/09/21
a Jtree.
Write a program to create
8. 42 24/09/21 07/10/21
a JTable.

Write a program to launch


9. 48 24/09/21 07/10/21
a JProgressBar
Write a program to
demonstrate status of key
on Applet window such
10. as 53 01/10/21 08/10/21
KeyPressed,
KeyReleased, KeyUp,
KeyDown
Write a program to
demonstrate various
mouse events using
11. MouseListener and 58 01/10/21 08/10/21
MouseMotionListener
interface
Write a program to
demonstrate the use of
12. JTextField and 63 08/10/21 14/10/21
JPasswordField using
Listener Interface
Write a program to
13. demonstrate the use of 69 08/10/21 14/10/21
WindowAdapter class.

Maharashtra State Board of Technical Education viii


Advanced Java Programming (22517)

Write a program to
demonstrate the use of
14. 75 14/10/21 21/10/21
InetAddress class and
its factory methods.
Write a program to
demonstrate the use of
15. 80 21/10/21 28/10/21
URL and URLConnection
class and its methods
Write a program to
implement chat Server
16. 85 22/10/21 29/10/21
using Server Socket and
Socket class.
Write a program to
demonstrate use of
17. DatagramSocket and 90 22/10/21 29/10/21
DataGram Packet
Write a program to insert
and retrieve the data
18. 95 28/10/21 19/11/21
from database using
JDBC
Write a program to
demonstrate the use of
19. PreparedStatement and 102 29/10/21 25/11/21
ResultSet interface.
Write a program to update
20. and delete a record from a 110 29/10/21 25/11/21
database table.
Write a program to
demonstrate the use of
21. HttpServlet as a 116 18/11/21 02/12/21
parameterized servlet
Write a Servlet program
to send username and
22. password using HTML 123 25/11/21 03/12/21
forms and authenticate
the user
Write a program to create
23. Session using HttpSession 130 25/11/21
03/12/21
class.
Write a program to
24. implement Session 137 02/12/21 09/12/21
tracking using Cookies.

Maharashtra State Board of Technical Education ix


Advanced Java Programming (22517)

Total Marks

To be transferred to Proforma of CIAAN-2017.

Maharashtra State Board of Technical Education x


EXPERIMENT 1

1.
import java.awt.*;

public class AwtExample extends Frame {

AwtExample()
{

Button b = new Button("Test


Button"); b.setBounds(50,50,100,20);
add(b);

TextField tf = new TextField("Test Text


Field"); tf.setBounds(50,100,100,20); add(tf);

Label l1 = new Label("Test Label");


l1.setBounds(50,150,100,20);
add(l1);
Checkbox cb1 = new Checkbox("Test
CheckBox"); cb1.setBounds(50,200,100,20);
add(cb1);

Choice choice = new Choice();


choice.addItem("TestOption 1");
choice.addItem("Test Option 2");
choice.addItem("Test Option 3");
add(choice);
choice.setBounds(50,250,100,20);
add(choice);

setSize(500,500);
setLayout(null);
setVisible(true);

public static void main(String args[])


{
AwtExample a = new AwtExample();
}
}

Output:

2.
import javax.swing.*;

public class JLabelExample


{
JLabelExample()
{
JFrame f = new JFrame();
JLabel jl1 = new JLabel("Welcome to
JAVA"); jl1.setBounds(50,100,100,20);
f.add(jl1);

f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String args[])


{
new JLabelExample();
}
}

Output:
3.
import javax.swing.*;
import java.awt.*;

public class JCBExample


{
JCBExample()
{
JFrame f= new JFrame();

JLabel jl1 = new JLabel("Languages


Known:"); jl1.setBounds(20,100,150,150);
f.add(jl1);
JCheckBox c1 = new
JCheckBox("English");
c1.setBounds(150,100,100,20); f.add(c1);

JCheckBox c2 = new
JCheckBox("Marathi");
c2.setBounds(150,130,100,20); f.add(c2);

JCheckBox c3 = new JCheckBox("Hindi");


c3.setBounds(150,160,100,20);
f.add(c3);

JCheckBox c4 = new
JCheckBox("Sanskrit");
c4.setBounds(150,190,100,20); f.add(c4);

f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String
args[])
{
new JCBExample();
}
}

Output:

4.
import javax.swing.*;
import java.awt.*;

public class JButtonExample


{
JButtonExample()
{
JFrame f= new JFrame();

JButton btn1 = new JButton("OK");


btn1.setBounds(50,100,100,50);
f.add(btn1);

JButton btn2 = new JButton("RESET");


btn2.setBounds(50,150,100,50);
f.add(btn2);

JButton btn3 = new JButton("CANCEL");


btn3.setBounds(50,200,100,50);
f.add(btn3);

f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String
args[])
{
new JButtonExample();
}
}

Output:
Import java.awt.*;

Class Uselist

Public static void main(String args[])

Int I;

Frame f=new Frame();

f.setSize(350,300);

f.setLayout(new FlowLayout());

f.setVisible(true);

List season=new List(4,false);

Season.add(“Summer”);

Season.add(“Winter”); Season.add(“Rainy”);

f.add(season);

Output:-
1.

Import java.applet.*;

Import java.awt.*;

Import java.awt.event.*;

Public class Subjects extends Applet

Public void init()

List l1=new List(10);

L1.setBounds(50,60,100,120);

L1.add(“DSU”);

L1.add(“PIC”);

L1.add(“OOP”);

L1.add(“CGR”);

L1.add(“DTE”);

L1.add(“Microprocessor”);

L1.add(“CN”);

L1.add(“DBMS”);

L1.add(“SEN”);

L1.add(“JAVA”);

Add(l1);

setLayout(null);

}
Public void paint(Graphics g)

Repaint();

Output:-

2.

Import java.applet.*;

Import java.awt.*;

Import java.awt.event.*;

Public class News extends Applet

Public void init()

List l1=new List(10,true);


L1.setBounds(50,60,100,120);

L1.add(“Times of India”);

L1.add(“Cwiedu”);

L1.add(“NDTEV”);

L1.add(“Gadgets360”);

Add(l1);

setLayout(null);

Public void paint(Graphics g)

Repaint();

Output:-
1.

Import java.awt.*;

Public class GridDemo

Public static void main( String args[] )

Frame f = new Frame();

f.setVisible(true);

f.setSize(400,400);

f.setLayout(new GridLayout(2,2));

Font font = new Font(“TimesRoman”,Font.BOLD,25);

f.setFont(font);

Label l[] = new Label[25];

For(int I = 0 ; I < 25 ; i++)

String s = “”;

S = s.valueOf(i+1);

Color c = new Color(I,i+10,i+20);

L[i] = new Label();

System.out.println©;

L[i].setBackground©;

L[i].setText(s);

For(int I = 0 ; I < 25;i++)

{
f.add(l[i]);

Output:-

2.

Import java.awt.*;

Import java.awt.event.*;

Public class Grid

Grid()

Frame f=new Frame();

Button b1=new Button(“1”);

Button b2=new Button(“2”);

Button b3=new Button(“3”);

Button b4=new Button(“4”);


Button b5=new Button(“5”);

Button b6=new Button(“6”);


Button b7=new Button(“7”);

Button b8=new Button(“8”);

Button b9=new Button(“9”);

f.add(b1);

f.add(b2);

f.add(b3);

f.add(b4);

f.add(b5);

f.add(b6);

f.add(b7);

f.add(b8);

f.add(b9);

f.setLayout(new GridLayout(3,3));

f.setSize(500,500);

f.setVisible(true);

Public static void main(String[] args) {

New Grid();

Output:-
1.

Import java.awt.*;

Import java.applet.*;

Public class MyGridLayout

Frame f;

MyGridLayout()

F = new Frame();

Button b1 = new Button(“Button 1”);

Button b2 = new Button(“Button 2”);

Button b3 = new Button(“Button 3”);

Button b4 = new Button(“Button 4”); Button

b5 = new Button(“Button 5”);

f.add(b1);

f.add(b2);

f.add(b3);

f.add(b4);

f.add(b5);

f.setLayout(new GridLayout(3,2));

f.setVisible(true);

Public static void main(String args[])

New MyGridLayout();

Output:-
2.

Import java.awt.*;

Import java.awt.event.*;

Public class Region

Region()

Frame f=new Frame();

Button b1=new Button(“East”);

Button b2=new Button(“West”);

Button b3=new Button(“South”);

Button b4=new Button(“North”);

Button b5=new Button(“Center”);

f.add(b1,BorderLayout.EAST);

f.add(b2,BorderLayout.WEST);
f.add(b3,BorderLayout.SOUTH);

f.add(b4,BorderLayout.NORTH);

f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);

f.setVisible(true);

Public static void main(String[] args) {

New Region();

Output:-
1.

Import java.awt.Button;

Import java.awt.GridBagConstraints;

Import java.awt.GridBagLayout;

Import javax.swing.*;

Public class GridBagLayoutExample extends JFrame{

Public static void main(String[] args) {

GridBagLayoutExample a = new GridBagLayoutExample();

Public GridBagLayoutExample() {

GridBagLayout grid = new GridBagLayout();

GridBagConstraints gbc = new GridBagConstraints();

setLayout(grid);

setTitle(“GridBag Layout Example”);

GridBagLayout layout = new GridBagLayout();

This.setLayout(layout);

Gbc.fill = GridBagConstraints.HORIZONTAL;

Gbc.gridx = 0;

Gbc.gridy = 0;

This.add(new Button(“Button One”), gbc);

Gbc.gridx = 1;

Gbc.gridy = 0;

This.add(new Button(“Button two”), gbc);

Gbc.fill = GridBagConstraints.HORIZONTAL;

Gbc.ipady = 20;

Gbc.gridx = 0;

Gbc.gridy = 1;

This.add(new Button(“Button Three”), gbc);

Gbc.gridx = 1;

Gbc.gridy = 1;
This.add(new Button(“Button Four”), gbc);

Gbc.gridx = 0;

Gbc.gridy = 2;

Gbc.fill = GridBagConstraints.HORIZONTAL;

Gbc.gridwidth = 2;

This.add(new Button(“Button Five”), gbc);

setSize(300, 300);

setPreferredSize(getSize()); setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

Output:-

2.

Import java.awt.Button;

Import java.awt.GridBagConstraints;

Import java.awt.GridBagLayout;

Import javax.swing.*;

Public class PR4b extends JFrame {

Public PR4b() {
GridBagLayout grid = new GridBagLayout();

GridBagConstraints gbc = new GridBagConstraints();

setLayout(grid); setTitle(“GridBag Layout

Example”);

GridBagLayout layout = new GridBagLayout();

JLabel L1 = new JLabel(“Name”);

JLabel L2 = new JLabel(“Comments”);

JTextField T1 = new JTextField();

JTextArea T2 = new JTextArea(10, 10);

JScrollPane SP = new JScrollPane(T2);

SP.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

This.setLayout(layout);

Gbc.fill = GridBagConstraints.HORIZONTAL;

Gbc.gridx = 0;

Gbc.gridy = 0;

This.add(L1, gbc);

Gbc.gridx = 1;

Gbc.gridy = 0;

This.add(T1, gbc);

Gbc.fill = GridBagConstraints.HORIZONTAL;

Gbc.gridx = 0;

Gbc.gridy = 1;

This.add(L2, gbc);

Gbc.gridx = 1;

Gbc.gridy = 1;

This.add(T2, gbc);

This.getContentPane().add(SP);

Gbc.gridx = 0;

Gbc.gridy = 2;

Gbc.fill = GridBagConstraints.HORIZONTAL;

Gbc.gridwidth = 1;
This.add(new Button(“Submit”), gbc);

setSize(300, 300);

setPreferredSize(getSize()); setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

Public static void main(String[] args) {

PR4b a = new PR4b();

Output:-
X. Program Code.

Import java.awt.*;

Class MenuEx extends Frame

MenuEx()

MenuBar mr=new MenuBar();

setMenuBar(mr);

Menu m1=new Menu(“Colours”);

MenuItem mn1=new MenuItem(“RED”);

MenuItem mn2=new MenuItem(“YELLOW”);

MenuItem mn3=new MenuItem(“BLACK”);

Mn3.setEnabled(false);

MenuItem mn4=new MenuItem(“BLUE”);

MenuItem mn5=new MenuItem(“GREEN”);

M1.add(mn1);

M1.add(mn2);

M1.add(mn3);

M1.add(mn4);

M1.add(mn5);

Mr.add(m1);

Class MenuBarEx

Public static void main(String args[])

MenuEx m=new MenuEx();

m.setTitle(“Menu Bar”);

m.setSize(500,500);

m.setVisible(true);
}

Xl. Result:-
CODE :- import java.awt.*; import

java.awt.event.*; public class

MenuDemo1 extends Frame


{

MenuBar mb;

MenuItem m1,m2,m3,m4;

Menu mn;

MenuShortcut ms;

MenuDemo1()

ms=new MenuShortcut(KeyEvent.VK_X);

mn=new Menu("File"); mb=new

MenuBar(); setMenuBar(mb); m1=new

MenuItem("New..."); m2=new

MenuItem("Open..."); m3=new

MenuItem("Save As..."); m4=new

MenuItem("Exit",ms); mn.add(m1);

mn.add(m2); mn.add(m3);

mn.addSeparator(); mn.add(m4);

mb.add(mn);

public static void main(String args[])

MenuDemo1 md=new MenuDemo1();

md.setTitle(“MenuBar Demo”);

md.setSize(500,500); md.setVisible(true);

Output:-
Code And Output :-
1.

2.
Output:-
import javax.swing.*; import
javax.swing.tree.*; import
java.awt.*;

public class JTreeDemo


{
public static void main(String[] args) {

JFrame JFrameMain = new JFrame();


JFrameMain.setVisible(true);
JFrameMain.setSize(400,400);

DefaultMutableTreeNode rootNode = new


DefaultMutableTreeNode("India");

DefaultMutableTreeNode maharashtraNode = new


DefaultMutableTreeNode("Maharashtra");
DefaultMutableTreeNode gujrathNode = new
DefaultMutableTreeNode("Gujrath");
rootNode.add(maharashtraNode); rootNode.add(gujrathNode);

DefaultMutableTreeNode mumbaiSubNode = new


DefaultMutableTreeNode("Mumbai");
DefaultMutableTreeNode puneSubNode = new
DefaultMutableTreeNode("Pune");
DefaultMutableTreeNode nashikSubNode = new
DefaultMutableTreeNode("Nashik");
DefaultMutableTreeNode nagpurSubNode = new
DefaultMutableTreeNode("Nagpur");

maharashtraNode.add(mumbaiSubNode);
maharashtraNode.add(puneSubNode);
maharashtraNode.add(nashikSubNode);
maharashtraNode.add(nagpurSubNode); JTree tree = new
JTree(rootNode);
JFrameMain.add(tree);
}

}
import javax.swing.*;
import
javax.swing.tree.*;
import java.awt.*; public
class Tree
{
Tree()
{
JFrame f = new JFrame();
DefaultMutableTreeNode s=new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode s2=new DefaultMutableTreeNode("This PC");
DefaultMutableTreeNode s3=new DefaultMutableTreeNode("Desktop");
s.add(s2);
s.add(s3);
DefaultMutableTreeNode s4=new DefaultMutableTreeNode("Documents");
DefaultMutableTreeNode s5=new DefaultMutableTreeNode("Downloads");
DefaultMutableTreeNode s6=new DefaultMutableTreeNode("Music");
DefaultMutableTreeNode s7=new
DefaultMutableTreeNode("Pictures"); s2.add(s4); s2.add(s5);
s2.add(s6); s2.add(s7); JTree j=new JTree(s); f.add(j);
f.setSize(200,200);
f.setVisible(true); }
public static void main(String[] args)
{ new
Tree();
}
}
Output :-
Code:-
import javax.swing.*;
import java.awt.*; import
javax.swing.table.*;

public class JTableDemo


{
public static void main(String[] args) { JFrame
JFrameMain = new JFrame();
JFrameMain.setVisible(true);
JFrameMain.setSize(400,400);

String colHeads[] = {"ID","Name","Salary"};

Object data[][] = {
{101,"Amit",670000},
{102,"Jai",780000},
{101,"Sachin",700000}
};
JTable JTableObj = new JTable(data,colHeads);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(JTableObj,v,h);

JFrameMain.add(jsp,BorderLayout.CENTER);
}
}

Output :-
Code :-
import javax.swing.*;
import java.awt.*; import
javax.swing.table.*;

public class JTableStudents


{
public static void main(String[] args) {

JFrame JFrameMain = new JFrame();


JFrameMain.setVisible(true);
JFrameMain.setSize(400,400);

String colHeads[] = {"Name","Percentage","Grade"};

Object data[][] = {
{"Amit","96%","C"},
{"jai","83%","A"},
{"Sachin","69%","B"},
{"Karan","73%","B"},
{"Amit","58%","A"},
{"Aadi","67%","A"},
{"Aman","81%","C"},
{"Nur","69%","C"},
{"Kal","93%","D"},
{"Rud","52%","D"}
};
JTable JTableObj = new JTable(data,colHeads);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(JTableObj,v,h);

JFrameMain.add(jsp,BorderLayout.CENTER);
}
}
Output :-
Code :-
import javax.swing.*;
public class GenerateJProgressBar extends JFrame
{
JProgressBar jb;
int i=0,num=0;
GenerateJProgressBar()
{
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,250,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(500,600);
setLayout(null);
}
public void iterate()
{
while(i<=2000) {
jb.setValue(i);
i=i+50; try{
Thread.sleep(200);
}
catch(Exception e)
{
}
} }
public static void main(String[] args)
{
GenerateJProgressBar m=new GenerateJProgressBar();
m.setVisible(true);
m.iterate();
}
}

Output :-
Code :-
import javax.swing.*;
public class JProgressBarApplet extends JFrame
{
JProgressBar jb;
JButton JB; int
i=0,num=0;
JProgressBarApplet()
{
JB=new JButton("Click");
jb=new JProgressBar(0,2000);
JB.setBounds(150,150,150,25);
jb.setBounds(100,200,250,25);
jb.setValue(0);
jb.setStringPainted(true);
add(jb); add(JB);
setSize(500,500);
setLayout(null);
}
public void iterate()
{
while(i<=2000) {
jb.setValue(i);
i=i+50;
try{
Thread.sleep(200);
}
catch(Exception e)
{
}
} }
public static void main(String[] args)
{
JProgressBarApplet m=new JProgressBarApplet();
m.setVisible(true);
m.iterate();
}
}

Output :-
Input:
import java.awt.event.*;
import java.awt.*;

public class Exp10X_1 extends Frame implements KeyListener


{
Label l;
Exp10X_1()
{
l=new Label();
l.setBounds(30,60,110,30);
addKeyListener(this);
add(l);
setSize(500,500);
setLayout(null);
setVisible(true);
}

public void keyPressed(KeyEvent e)


{
l.setText("Key Pressed");

public void keyReleased(KeyEvent e) {}

public void keyTyped(KeyEvent e) {}

public static void main(String[] args) {


Exp10X_1 m=new Exp10X_1();
}
}

Output:
import java.awt.*;
import java.awt.event.*;
class Exp10X_2 extends Frame implements KeyListener{
Label l1,l2;
TextField tf1,tf2;
public Exp10X_2(String s){
super(s);
setVisible(true);
setLayout(null);
setSize(500,500);

l1=new Label("Key Code");


l2=new Label("Key");
l1.setBounds(50,100,100,15);
l2.setBounds(50,150,100,15);

tf1=new TextField();
tf2=new TextField();
tf1.setBounds(160,100,150,40);
tf2.setBounds(160,150,150,40);
tf1.addKeyListener(this);
tf2.addKeyListener(this);

add(l1);
add(l2);
add(tf1);
add(tf2);
}
public void keyPressed(KeyEvent e){
int keyNumber=e.getKeyCode();
switch(keyNumber){
case KeyEvent.VK_F1:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F1");
break;
case KeyEvent.VK_F2:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F2");
break;
case KeyEvent.VK_F3:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F3");
break;
case KeyEvent.VK_F4:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F4");
break;
case KeyEvent.VK_F5:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F5");
break;
case KeyEvent.VK_F6:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F6");
break;
case KeyEvent.VK_F7:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F7");
break;
case KeyEvent.VK_F8:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F8");
break;
case KeyEvent.VK_F9:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F9");
break; case KeyEvent.VK_F10:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F10");
break;
case KeyEvent.VK_F11:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F11");
break;
case KeyEvent.VK_F12:
tf1.setText(keyNumber+"");
tf2.setText("Functional Key F12");
break;
case KeyEvent.VK_UP:
tf1.setText(keyNumber+"");
tf2.setText("UP ARROW");
break;
case KeyEvent.VK_DOWN:
tf1.setText(keyNumber+"");
tf2.setText("DOWN ARROW");
break;
case KeyEvent.VK_RIGHT:
tf1.setText(keyNumber+"");
tf2.setText("RIGHT ARROW");
break;
case KeyEvent.VK_LEFT:
tf1.setText(keyNumber+"");
tf2.setText("LEFT ARROW");
break;
}

}
public void keyTyped(KeyEvent e){

}
public void keyReleased(KeyEvent e){

}
public static void main(String[] args){
}
}
Output:
Input:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exp10XIII_3 extends JFrame implements ActionListener {
JLabel l1,l2,l3;
JTextField t1,t2;
JButton b1;

public Exp10XIII_3()
{
l1=new JLabel("Enter 1st Number");
l2=new JLabel("Enter 2nd Number");

l3=new JLabel();
t1=new JTextField(10);
t2=new JTextField(10);
b1=new JButton("Multiply");
b1.addActionListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(l3);
setLayout(new FlowLayout());
setSize(500,500);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ int a,b,c;
a=Integer.parseInt(t1.getText());
b=Integer.parseInt(t2.getText());
c=a*b;
l3.setText("Multiplication of the two number is:-
"+Integer.toString(c));
}
public static void main(String[] args)
{
Exp10XIII_3 m=new Exp10XIII_3();
}
}
Output:
Line Missing:
addMouseListener(this);

Correct Code:
import java.applet.Applet;
import java.awt.*; import
java.awt.event.*;
/* <APPLET CODE ="MouseDemo.class" WIDTH=300 HEIGHT=200>
</APPLET> */

public class MouseDemo extends Applet implements MouseListener


{ Label l; public void init(){
addMouseListener(this);
setLayout(null);
setVisible(true);
setSize(500,500); l=new
Label("Hello Mouse");
l.setBounds(50,150,200,100);
add(l);
}
public void mousePressed(MouseEvent e){
System.out.println("click");
l.setText("Mouse Pressed no. of clicks:" + e.getClickCount() + "at position"
+ e.getX() + ","+ e.getY());
}

public void mouseReleased(MouseEvent e){ System.out.println("MR");


l.setText("Mouse Released; # of clicks:"+e.getClickCount()); }

public void mouseEntered(MouseEvent e){


System.out.println("Enter"); l.setText("Mouse
Entered");
}

public void mouseExited(MouseEvent e){ l.setText("Mouse


exited");
}

public void mouseClicked(MouseEvent e){


l.setText("mouse clicked(# of clicks:"+e.getClickCount()); }
}
Output:
Input:
import java.awt.event.*;
import java.awt.*;
public class Exp11XIII_1 extends Frame implements MouseListener
{
Button b;
String msg;
int x=100,y=100;
Exp11XIII_1()
{
msg="Click the above button";
FlowLayout f1=new FlowLayout();
setLayout(f1);
b=new Button("Click me !!!!!!!!!!!");
b.addMouseListener(this);
add(b);
setVisible(true); setSize(400,400);
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
public void mouseClicked(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
setBackground(Color.red);
msg="Mouse Pressed ";
}
public void mouseReleased(MouseEvent e)
{
setBackground(Color.blue);
msg="Mouse Released ";
}
public void mouseEntered(MouseEvent e)
{
setBackground(Color.yellow);
msg="Mouse Entered ";
}
public void mouseExited(MouseEvent e)
{
setBackground(Color.white);
msg="Mouse Exited ";
}
public static void main(String[] args){
Exp11XIII_1 m=new Exp11XIII_1();
}
}

Output:
Input:
import java.awt.*; import java.awt.event.*;
import javax.swing.*;

public class Exp11XIII_2 extends JFrame implements MouseListener


{
final JLabel res = new JLabel("No clicks till now..........");
int count = 0;

Exp11XIII_2()
{
res.setHorizontalAlignment(JLabel.CENTER);
add(res, BorderLayout.CENTER);
addMouseListener(this);
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void mouseClicked(MouseEvent me)


{
res.setText((++count)+" clicks!");
}

public void mouseEntered(MouseEvent me)


{
}
public void mouseExited(MouseEvent me)
{
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public static void main(String args[])
{
Exp11XIII_2 m=new Exp11XIII_2();
}
}
Output:

Input:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exp11XIII_3 extends JFrame implements MouseMotionListener
{
Exp11XIII_3()
{
addMouseMotionListener(this);
setSize(500,500);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseDragged(MouseEvent e)
{
Graphics g=getGraphics();
g.setColor(Color.YELLOW);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e)
{
Graphics g1 = getGraphics();
g1.setColor(Color.RED);
g1.fillOval(e.getX(),e.getY(),20,20);
}

public static void main(String[] args)


{
Exp11XIII_3 m=new Exp11XIII_3();
}
}

Output:
import javax.swing.*;
import java.awt.*;
public class JPasswordChange
{
public static void main(String[] args) {
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(400,400);
f.setLayout(new FlowLayout());
JPasswordField pf = new JPasswordField(20);
pf.setEchoChar('#');
f.add(pf);
}
}
Output :-
1.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class text extends JFrame implements ActionListener {
static JTextField t;
static JPasswordField pass;
static JFrame f;
static JButton b;
static JLabel l;
text()
{
}
public static void main(String[] args)
{
f = new JFrame("textfield");
l = new JLabel("nothing entered");
b = new JButton("submit");
text te = new text();
b.addActionListener(te);
t = new JTextField("enter name", 16);
pass = new JPasswordField(16);
Font fo = new Font("Serif", Font.ITALIC, 20);
t.setFont(fo);
JPanel p = new JPanel();
p.add(t);
p.add(pass);
p.add(b);
p.add(l);
f.add(p);
f.setSize(300, 300);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("submit")) {
l.setText("name = " + t.getText() + "\t Password = " +
pass.getText());
t.setText(" ");
pass.setText("");
}
}
}
Output :-

2.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JTextAdd implements ActionListener


{
JTextField tf , tf1 ;
JLabel res;
JTextAdd()
{
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(400,400);
f.setLayout(new FlowLayout());
JLabel jl = new JLabel("Enter 1st Number:");
tf = new JTextField(5);
JLabel jl1 = new JLabel("Enter 2nd Number:");
tf1 = new JTextField(5);
res = new JLabel("Addition");
tf1.addActionListener(this);
f.add(jl);
f.add(tf);
f.add(jl1);
f.add(tf1);
f.add(res);
}
public static void main(String[] args) {
JTextAdd jt = new JTextAdd();
}
public void actionPerformed(ActionEvent ae)
{
String str1 = tf.getText();
double fn = Double.parseDouble(str1);
double sn = Double.parseDouble(tf1.getText());
res.setText("Sum is " + (fn+sn));
}
}

Output :-

3.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Exp12XIII_3 extends JFrame implements ActionListener
{
JPasswordField t2;
JTextField t1;
JLabel l1,l2,l3;
JButton b;
String msg;
Exp12XIII_3()
{
setSize(350,350);
setVisible(true);
setLayout(new
FlowLayout(FlowLayout.CENTER,20,20));
l1=new JLabel("Enter Username : ");
t1=new JTextField(20);
l2=new JLabel("Enter Password : ");
t2=new JPasswordField(20);
t2.setEchoChar('*');
b=new JButton("SUBMIT");
b.addActionListener(this);
l3=new JLabel("");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(b);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{ String s=new String(t2.getPassword());
if(s.length()<6)
{
l3.setText("Password length is less than 6 characters");
t2.setText("");
}else
{
l3.setText("User = "+t1.getText()+" Accepted. WELCOME !!!");
}
}
public static void main(String[] args)
{
Exp12XIII_3 t=new Exp12XIII_3();
}
}
Output :-
Code:-
import java.awt.*;
import java.awt.event.*;
public class WindowDemo
{
Frame f;
WindowDemo()
{
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new WindowDemo();
}
}
Output:-
1.
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.WindowListener;
import java.awt.FlowLayout;
public class WindowAdapterDemo extends WindowAdapter
{
JFrame f ;
JLabel l ;
WindowAdapterDemo()
{
f = new JFrame();
f.setVisible(true);
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.addWindowListener(this);
f.addWindowFocusListener(this);
}
public void windowLostFocus(WindowEvent we)
{
l = new JLabel("Window Lost Focus");
f.remove(l);
f.add(l);
}
public void windowOpened(java.awt.event.WindowEvent we)
{
l = new JLabel("Window Opened");
f.remove(l);
f.add(l);
}
public void windowActivated(java.awt.event.WindowEvent we)
{
l = new JLabel("Window Activated");
f.remove(l);
f.add(l);
}
public void windowDeactivated(java.awt.event.WindowEvent we)
{
l = new JLabel("Window Deactivated");
f.remove(l);
f.add(l);
}
public void windowGainedFocus(java.awt.event.WindowEvent we)
{
l = new JLabel("Window Gained Focus");
f.remove(l);
f.add(l);
}
public static void main(String[] args)
{
WindowAdapterDemo wa = new WindowAdapterDemo();
}
}
Output :-

2.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class AnonymousInner extends JFrame
{
public static void main(String[] args) {
AnonymousInner ai = new AnonymousInner();

JButton jb = new JButton(" Don't Click Me ");

jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
System.out.println("Action Event:"+ae);
}
});

ai.add(jb);
ai.pack();
ai.setSize(300,350);
ai.setVisible(true);
}
}

Output :-

3.
Code :-
import java.io.*;
import java.net.*;
public class InetDemo
{
public static void main(String[] args)
{
try
{
InetAddress ip=InetAddress.getByName("localhost");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e){System.out.println(e);}
}
}
Output :-
Code :-
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
public class RetriveIP
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Host Name: ");
String host = sc.nextLine();
try
{
InetAddress ip = InetAddress.getByName(host);

System.out.println("IP Adress of Computer


is:"+ip.getHostAddress());
}
catch(UnknownHostException e)
{
System.out.print(e);
}
}
}

Output :-
Code :-
import java.net.*;
class URLDemo
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("https://www.javatpoint.com/javafx-tutorial");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());

System.out.println("Host: " + hp.getHost());


System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
}

Output :-
1.
import java.net.*;
class URLRetrive
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("http://www.msbte.org.in");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
}
Output :-
2.
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;

public class URLInfo


{
public static void main(String[] args) throws IOException ,
MalformedURLException
{
Scanner sc = new Scanner(System.in);

System.out.print("Enter any Url: ");


String ad = sc.nextLine();

URL url = new URL(ad);


URLConnection uc = url.openConnection();

System.out.println("Date:"+ new Date(uc.getDate()) );


System.out.println("Content Type: "+ uc.getContentType());
System.out.println("Content Length: "+ uc.getContentLength());

}
}
Output :-
Code:-
//ValidateServer.java import
java.net.ServerSocket; import
java.net.Socket; import
java.io.BufferedReader; import
java.io.IOException; import
java.io.OutputStream; import
java.io.PrintStream; import
java.io.InputStreamReader;

public class ValidateServer


{
public static void main(String[] args) throws IOException
{
ServerSocket s = new ServerSocket(2019);
System.out.println("Server Started, waiting for client");
Socket s1 = s.accept();
BufferedReader br = new BufferedReader(
new InputStreamReader(s1.getInputStream())
);
String user = br.readLine();
String pass = br.readLine();
OutputStream out = s1.getOutputStream();
PrintStream ps = new PrintStream(out);
if(user.equals("#Raza@") && pass.equals("98765"))
{
ps.println("Validate Successfully");
}
else {
ps.println("Validate Un-Successfull");
}
}
}

//ValidateClient.java
import java.net.Socket; import
java.io.BufferedReader; import
java.io.IOException; import
java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;

public class ValidateClient


{
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost" , 2019);
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
System.out.print("Enter Username and Password: ");
String user = br.readLine();
String pass = br.readLine();
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println(user);
ps.println(pass);
BufferedReader br1 = new BufferedReader(
new InputStreamReader(s.getInputStream())
);
String res = br1.readLine();
System.out.println(res);
}
}

Output :-
1. Code :-
//ServerSide.java import
java.net.ServerSocket; import
java.net.Socket; import
java.io.BufferedReader; import
java.io.IOException; import
java.io.OutputStream; import
java.io.PrintStream; import
java.io.InputStreamReader;

public class ServerSide


{
public static void main(String[] args) throws IOException
{
ServerSocket s = new ServerSocket(0605);
System.out.println("Server Started, waiting for client");
Socket s1 = s.accept();
// Client Send
BufferedReader br = new BufferedReader(
new InputStreamReader(s1.getInputStream())
);
OutputStream out = s1.getOutputStream();
PrintStream ps = new PrintStream(out);
BufferedReader br1 = new BufferedReader(
new InputStreamReader(System.in)
);
do{
String res = br.readLine();
System.out.println("Client Send: "+res);
System.out.print("Server: ");
String msg = br1.readLine();
System.out.print("\n\n"); ps.println(msg);
}
while(true);
}
}

//ClientSide.java import
java.net.Socket; import
java.io.BufferedReader; import
java.io.IOException; import
java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
public class ClientSide
{
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost",0605);
System.out.println("Client Started, waiting for server response..");
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
OutputStream os = s.getOutputStream();
BufferedReader br1 = new BufferedReader( new
InputStreamReader(s.getInputStream())
);
PrintStream ps = new PrintStream(os);
do{
System.out.print("Client: ");
String msg = br.readLine();
ps.println(msg);
String res = br1.readLine();
System.out.println("Server Send:"+res+"\n\n");
}
while(true);
}
}

Output:-
2. Code :-
//MyServer.java import
java.io. * ; import
java.net. * ;

public class MyServer {

public static void main(String[]args) { try


{
ServerSocket ss = new ServerSocket(0605);
Socket s = ss.accept(); //establishes connection
DataInputStream din = new DataInputStream(s.getInputStream());
System.out.println("Client IP Address: "+ s);
String num = (String)din.readUTF();
System.out.println("Number:- " + num);
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

//MyClient.java import java.io.


* ; import java.net. * ;
import java.util.*; import
java.util.regex.Matcher;
import
java.util.regex.Pattern;

public class MyClient {

static void checkPrime(String num) {


int number = Integer.parseInt(num);
int i, flag = 0; int m = number/2;
for(i = 2; i <= m; i++){ if(number
% i == 0){ flag = 1; break; } }
if(flag == 1)
System.out.println(number + " is not a Prime no."); else
System.out.println(number + " is Prime no.");
}
public static void main(String[]args) { try
{
Socket s = new Socket("localhost", 0605);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: ");
String no = sc.nextLine();
checkPrime(no); dout.writeUTF(no);
dout.flush();dout.close();s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Output :-
Code :-

//DgramRec.java

import java.net.*;

public class DgramRec


{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}

//DGramSender.java
import java.net.*;

public class DGramSender


{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
String str = "Java is Easy!!!!!";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(),
ip, 3000);
ds.send(dp);
ds.close();
}
}
Output :-
1.

Code :-

//ServerSideData.java
import java.net.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ServerSideData


{
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(2019);
byte[] receiveData = new byte[512];
byte[] sendData = new byte[512];
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
System.out.println(" UDP Server Socket is created, waiting for
client ");

do
{
DatagramPacket receiveDP = new
DatagramPacket(receiveData,receiveData.length);
ds.receive(receiveDP);
String clientMessage = new
String(receiveDP.getData(),0,receiveDP.getLength());
System.out.println("Client Message:"+clientMessage);
InetAddress ip = receiveDP.getAddress();
System.out.print("\n\nEnter Server Message:");
String serverMessage = br.readLine();
sendData = serverMessage.getBytes();
DatagramPacket sendDP = new DatagramPacket(sendData,
sendData.length, ip, receiveDP.getPort());
ds.send(sendDP);
receiveData = new byte[512];
}while(true);
}
}
//ClientSideData.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class ClientSideData
{
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket();
byte[] receiveData = new byte[512];
byte[] sendData = new byte[512];
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
System.out.println(" UDP Client Socket is created, waiting for
server ");
InetAddress ip = InetAddress.getLocalHost();
do
{
System.out.print("\nEnter Client Message:");
String clientMessage = br.readLine();
sendData = clientMessage.getBytes();
DatagramPacket sendDP = new DatagramPacket(sendData,
sendData.length, ip, 2019);
ds.send(sendDP);
DatagramPacket receiveDP = new
DatagramPacket(receiveData,receiveData.length);
ds.receive(receiveDP);
String serverMessage = new
String(receiveDP.getData(),0,receiveDP.getLength());
System.out.println("\n\nServer Message:"+serverMessage);
}while(true);
}}
Output :-
2.

Code :-

//ServerFile.java
import java.net.*;
import java.io.*;
public class ServerFile
{
public static void main(String args[])throws IOException
{
byte b[]=new byte[3072];
DatagramSocket dsoc=new DatagramSocket(2019);
FileOutputStream f=new
FileOutputStream("D:\\Hasnain.Java17\\EXPERIMENTS\\17\\ServerFile.txt")
;

DatagramPacket dp=new DatagramPacket(b,b.length);


dsoc.receive(dp);
String data = new String(dp.getData(),0,dp.getLength());
f.write(data.getBytes(), 0, data.length());

}
}

//ClientFile.java
import java.net.*;
import java.io.*;

public class ClientFile


{
public static void main(String args[])throws Exception
{
byte b[] = new byte[1024];
FileInputStream f = new
FileInputStream("D:\\Hasnain.Java17\\EXPERIMENTS\\17\\ClientFile.txt");
DatagramSocket dsoc = new DatagramSocket();
int i=0;
while(f.available() != 0)
{
b[i]=(byte)f.read();
i++;
}
f.close();
dsoc.send(new
DatagramPacket(b,i,InetAddress.getLocalHost(),2019));
}
}

Output :-
3.
Code :-

import java.sql*;

class JdbcDemo

public static void main (String args[])

try

DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());

System.out. println(" Driver loaded");


String url= "jdbc:odbc:MSBTE";

Connection cn= DriverManager.getConnection(url);

System.out.println("Connection to the database created");

Statement st= cn.createStatement();

String str= "select* from student";

ResultSet rs=st.executeQuery(str);

String text=" ";

System.out.println("Roll Number \t Name");

while(rs.next())

text= text+rs.getInt(1)+"\t"+rs.getString(2)+"\n";

System.out.print(text);

St.close();

cn.close();

catch (SQLExccpt.ion s)

{System.out.println("sql error");}

Output :-
1.

Code :-

import java.sql.*;

import java.net.InetAddress;

import java.util.*;

import java.util.Date;

public class JDBCcreateemployee{

// JDBC driver name and database URL

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL = "jdbc:mysql://localhost/Java";

// Database credentials

static final String USER = "root";

static final String PASS = "root";

public static void main(String[] args) {

Connection conn = null;

Statement stmt = null;

try{

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

System.out.println("Connecting to a selected database...");

conn = DriverManager.getConnection(DB_URL, USER, PASS);

System.out.println("Connected database successfully...");

System.out.println("Creating table in given database...");

stmt = conn.createStatement();
String sql = "CREATE TABLE EMPLOYEE " +

"(Emp_id INTEGER not NULL, " +

" Emp_name VARCHAR(255), " +

" PRIMARY KEY ( Emp_id ))";

stmt.executeUpdate(sql);

System.out.println("Created Employee table in given database...");

System.out.println("Executed by Gaurav Thombare");

System.out.println("Time : " + new Date() + " || IP Address : " +

(InetAddress.getLocalHost()).getHostAddress());

}catch(SQLException se){

//Handle errors for JDBC

se.printStackTrace();

}catch(Exception e){

//Handle errors for Class.forName

e.printStackTrace();

}finally{

//finally block used to close resources

try{

if(stmt!=null)

conn.close();

}catch(SQLException se){

}// do nothing

try{

if(conn!=null)

conn.close();

}catch(SQLException se){

se.printStackTrace();

} }}}
Output:-

2.

Code:

import java.sql.*;

import java.net.InetAddress;

import java.util.*;

import java.util.Date;

public class exp18exercise2_2{

// JDBC driver name and database URL

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL = "jdbc:mysql://localhost/vesp";

// Database credentials

static final String USER = "root";

static final String PASS = "root";

public static void main(String[] args) {

Connection conn = null;


Statement stmt = null;

try{

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

System.out.println("Connecting to a selected database...");

conn = DriverManager.getConnection(DB_URL, USER, PASS);

System.out.println("Connected database successfully...");

stmt = conn.createStatement();

String sql = "SELECT Name,Roll_No,Percentage FROM Student";

ResultSet rs = stmt.executeQuery(sql);

System.out.println("Fetching records with condition...");

System.out.println("Below the list of student how scored above 70%");

sql = "SELECT Name,Roll_No,Percentage FROM Student" +

" WHERE percentage > 70 ";

rs = stmt.executeQuery(sql);

while(rs.next()){

//Retrieve by column name

String Name = rs.getString("Name");

int Roll_No = rs.getInt("Roll_No");

int Percentage = rs.getInt("Percentage");

//Display values

System.out.println(" ");

System.out.print("Name of Student: " +Name);

System.out.print(", Roll No " +Roll_No);

System.out.print(", Percentage " +Percentage);


}

rs.close();

System.out.println("\n");

System.out.println("Executed by Gaurav Thombare");

System.out.println("Time : " + new Date() + " || IP Address : " +

(InetAddress.getLocalHost()).getHostAddress());

}catch(SQLException se){

//Handle errors for JDBC

se.printStackTrace();

}catch(Exception e){

//Handle errors for Class.forName

e.printStackTrace();

}finally{

//finally block used to close resources

try{

if(stmt!=null)

conn.close();

}catch(SQLException se){

}// do nothing

try{

if(conn!=null)

conn.close();

}catch(SQLException se){

se.printStackTrace();

}}}}

Output:-
Code:-

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.util.Scanner;

public class DynamicUpdateApp {

public static void main(String args[]) {

Connection connection = null;

PreparedStatement psmt = null;

try {

Class.forName("oracle.jdbc.OracleDriver");

connection = DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:XE", "System",

"Atharva007");

psmt = connection.prepareStatement(SqlUtils.DYNC_UPDATE_QUERY);

// Update Student set address= ? where name = ?

Scanner scan = new Scanner(System.in);

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

String address = scan.next();

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

String name = scan.next();

psmt.setString(2, name);

psmt.setString(1, address);

int count = psmt.executeUpdate();

System.out.println(count + " Record(s) Updated");

catch(SQLException e){

e.printStackTrace();
}

catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (psmt != null)

psmt.close();

if (connection != null)

connection.close();

} catch (Exception e) {

e.printStackTrace();

}}

Output:-
1. Code:

import java.sql.*; public class p20 { public static void

main(String[] args) throws Exception {

String url = "jdbc:mysql://localhost:3306/p20";

String uname = "root";

String pass = "";

String query = "delete from student where Roll_No = ";

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

Connection con =

DriverManager.getConnection(url,uname,pass); Statement

st = con.createStatement(); st.executeUpdate(query);

st.close(); con.close();

Output :
2. Code:

import java.sql.Connection; import

java.sql.DriverManager; import

java.sql.PreparedStatement; public

class UpdateQuery

public static void main(String [] args)

{ try

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

con=DriverManager.getConnection("jdbc:mysql://localhost:33

06/Ddemodatabase","root","root");

PreparedStatement st = con

.prepareStatement("update student set roll_no=3 where

name='Abhishek'"); st.executeUpdate();

catch(Exception ex)

System.out.println(ex);

}
Output :
1. Code:

import java.sql.*; public class p20ex1 { public static

void main(String[] args) throws Exception {

String url = "jdbc:mysql://localhost:3306/p20";

String uname = "root";

String pass = "";

String query = "update student set Name = 'John' where Roll_No = 1";

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

Connection con = DriverManager.getConnection(url,uname,pass);

Statement st = con.createStatement(); st.executeUpdate(query);

st.close(); con.close();

Output:

2. Code :

import java.sql.*; public class p20ex2 { public static

void main(String[] args) throws Exception {


String url = "jdbc:mysql://localhost:3306/p20";

String uname = "root";

String pass = "";

String query = "delete from sales where P_Price > 500 AND P_Id =

'P1234'";

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

Connection con = DriverManager.getConnection(url,uname,pass);

Statement st = con.createStatement(); st.executeUpdate(query);

st.close();

con.close();

Output:-
import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class WelcomeMSBTE extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head>");

out.println("<title>Hello MSBTE!</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1>Welcome At Maharashtra State Board Of Technical Education!</h1>");

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

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

}
Output:-
1.

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.net.InetAddress;

public class HelloMSBTE extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

InetAddress IP = InetAddress.getLocalHost();

out.println("<html>");

out.println("<head>");

out.println("<title>Hello MSBTE!</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1>Hello MSBTE!</h1>");

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

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

Output:-
2.

Form1.html

<html>

<body>

<center>

<form name="Form1"

method="post"action="http://localhost:8080/examples/servlets/servlet/PostParamet

ersServlet">

<table>

<tr><td><B>Employee</td>

<td><input type=textbox name="e" size="25" value=""></td></tr>

<tr><td><B>Phone</td>

<td><input type=textbox name="p" size="25" value=""></td></tr>

</table>

<input type=submit value="Submit">

</body>

</html>

PostParametersServlet.java

import java.io.*;

import java.util.*;

import javax.servlet.*;

public class PostParametersServlet extends GenericServlet{

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException


{PrintWriter pw = response.getWriter();

// Get enumeration of parameter names.

Enumeration e = request.getParameterNames();

// Display parameter names and values.

while(e.hasMoreElements()){

String pname = (String)e.nextElement();

pw.print(pname + " = ");

String pvalue = request.getParameter(pname);

pw.println(pvalue);

pw.close();

}}

Output:-
1.

HTML CODE:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<form action="http://localhost:8080/examples/servlets/servlet//ServletCode" method="post">

<h4><label>Select Gender :</label></h4>

Male:<input type ="radio" name ="sex" value="Male"> <br>

Female:<input type = "radio" name="sex" value="Female"> <br>

<h4><label for="subject">Choose a Subject :</label></h4>

<select name="subject">

<option value="AJP">AJP</option>

<option value="STE">STE</option>

<option value="OSY">OSY</option>

<option value="CSS">CSS</option>

</select>

<input type="submit" value="Enter">

</form>

</body>

</html>

JAVA CODE:

import javax.servlet.http.*;
import javax.servlet.*;

import java.io.*;

import java.util.*;

public class ServletCode extends HttpServlet{

public void doPost(HttpServletRequest req,HttpServletResponse resp)throws

ServletException,IOException{

resp.setContentType("text/html");

PrintWriter out=resp.getWriter();

String gen=req.getParameter("sex");

String sub=req.getParameter("subject");

out.println("<h2>Selected Gender is "+gen+"</h2>");

out.println("<br>");

out.println("<h2>Selected Subject is "+sub+"</h2>");

XML CODE:

<servlet>

<servlet-name>ServletCode</servlet-name>

<servlet-class>ServletCode</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ServletCode</servlet-name>

<url-pattern>/servlets/servlet/ServletCode</url-pattern>

</servlet-mapping>

Output:-
2.

HTML CODE:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<form action="http://localhost:8080/examples/servlets/servlet//ServletCode2"
method="post">

<h2>Enter Marks out of 100</h2>

<label for="sub1">Subject 1 : </label>

<input type="number" name="sub1"><br>

<label for="sub2">Subject 2 : </label>

<input type="number" name="sub2"><br>

<label for="sub3">Subject 3 : </label>

<input type="number" name="sub3"><br>

<label for="sub4">Subject 4 : </label>

<input type="number" name="sub4"><br>

<input type="submit" value="Enter">

</form>

</body>

</html>

JAVA CODE:

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

import java.util.*;

public class ServletCode2 extends HttpServlet{

public void doPost(HttpServletRequest req,HttpServletResponse resp)throws

ServletException,IOException{

resp.setContentType("text/html");

PrintWriter out=resp.getWriter();

int s1=Integer.parseInt(req.getParameter("sub1"));

int s2=Integer.parseInt(req.getParameter("sub2"));

int s3=Integer.parseInt(req.getParameter("sub3"));

int s4=Integer.parseInt(req.getParameter("sub4"));

float sum=(s1+s2+s3+s4);

out.println("<h2>Total is "+sum+"</h2>");

float perc= (sum/400)*100;


out.println("<h2>Percent is "+perc+"</h2>");

out.println("<br>");

if(perc >= 45) {

out.println("<h3>You are passed</h3>");

}else {

out.println("<h3>You are failed</h3>");

XML CODE:

<servlet>

<servlet-name>ServletCode2</servlet-name>

<servlet-class>ServletCode2</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ServletCode2</servlet-name>

<url-pattern>/servlets/servlet/ServletCode2</url-pattern>

</servlet-mapping>

Output:-
1.

HTML CODE:

<html>

<body>

<form action="http://localhost:8080/examples/servlets/servlet//SessionServlet">

Name:<input type="text" name="userName"/><br/>

<input type="submit" value="go"/>

</form>

</body>

</html>

JAVA CODE:

//SessionServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SessionServlet extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n=request.getParameter("userName");

out.print("Welcome "+n);

HttpSession session=request.getSession();

out.print("<br>Session Id:"+session.getId());

session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");

out.close();

catch (Exception e) {System.out.println(e);}

XML CODE:

<servlet>

<servlet-name>SessionServlet</servlet-name>

<servlet-class>SessionServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SessionServlet</servlet-name>

<url-pattern>/servlets/servlet/SessionServlet</url-pattern>

</servlet-mapping>

Output:-

2.

HTML CODE:

<html>
<body>

<form action="

http://localhost:8080/examples/servlets/servlet/SessionServlet1">

Name:<input type="text" name="userName" /><br />

<input type="submit" value="go" />

</form>

</body>

</html>

JAVA CODE:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.net.InetAddress;

public class SessionServlet1 extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n = request.getParameter("userName");

out.print("Welcome " + n);

HttpSession session = request.getSession();

session.setMaxInactiveInterval(300);

out.println("<br>Session ID: " + session.getId());

out.println("<br>Session created on: " + session.getCreationTime());

out.println("<br>Session last accessed on: " +

session.getLastAccessedTime());

session.setAttribute("uname", n);

out.print("<a href ='servlet2'> visit </a>");

out.println();

InetAddress IP = InetAddress.getLocalHost();

out.println("IP Address: " + IP);


out.close();

catch (Exception e) {

System.out.println(e);

XML CODE:

<servlet>

<servlet-name>SessionServlet1</servlet-name>

<servlet-class>SessionServlet1</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SessionServlet1</servlet-name>

<url-pattern>/servlets/servlet/SessionServlet1</url-pattern>

</servlet-mapping>

Output :-
Code:

HTML CODE:

<!DOCTYPE html><html>

<head><meta charset="UTF-8" /><title>Cookies Example</title></head>

<body>

<h3>Cookies Example</h3>

Your browser isn't sending any cookies

<P>Create a cookie to send to your browser<br>

<form action=" http://localhost:8080/examples/servlets/servlet/CookieExample" method=POST>

Name: <input type=text length=20 name=cookiename><br>

Value: <input type=text length=20 name=cookievalue><br>

<input type=submit></form>

</body>

</html>

JAVA CODE:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class CookieExample extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException{


response.setContentType("text/html");

PrintWriter out = response.getWriter();

Cookie[] cookies = request.getCookies();

for (int i = 0; i < cookies.length; i++) {

Cookie c = cookies[i];

String name = c.getName();

String value = c.getValue();

out.println(name + " = " + value);

String name = request.getParameter("cookieName");

if (name != null && name.length() > 0) {

String value = request.getParameter("cookieValue");

Cookie c = new Cookie(name, value);

response.addCookie(c);

}}}

XML CODE:

<servlet>

<servlet-name>CookieExample</servlet-name>

<servlet-class> CookieExample </servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>CookieExample</servlet-name>

<url-pattern>/servlets/servlet/ CookieExample </url-pattern>

</servlet-mapping>

Output:-
Code:-

HTML CODE:

<html>

<title>Cookie Program</title>

<body>

<form action=" http://localhost:8080/examples/servlets/servlet/FirstServlet" method="post">

Name:<input type="text" name="userName"/><br/>

<input type="submit" value="go"/>

</form>

</body></html>

JAVA CODE:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n=request.getParameter("userName");

out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object

response.addCookie(ck);//adding cookie in the response

out.print("<form action='SecondServlet'>");

out.print("<input type='submit' value='go'>");

out.print("</form>");

out.close();
}catch(Exception e){System.out.println(e);}

//SecondServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();

out.print("Hello "+ck[0].getValue());

out.close();

}catch(Exception e){System.out.println(e);}

}}

XML CODE:

<servlet>

<servlet-name>FirstServlet</servlet-name>

<servlet-class> FirstServlet </servlet-class>

</servlet>

<servlet>

<servlet-name>SecondServlet</servlet-name>

<servlet-class> SecondServlet </servlet-class>

</servlet>

<servlet-mapping>

<servlet-name> FirstServlet </servlet-name>

<url-pattern>/servlets/servlet/ FirstServlet </url-pattern>

</servlet-mapping>

<servlet-mapping>
<servlet-name> SecondServlet </servlet-name>

<url-pattern>/servlets/servlet/ SecondServlet </url-pattern>

</servlet-mapping>

Output:-

You might also like