AJP All PR

You might also like

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

PR:-1

import java.awt.*;

import java.util.*;

public class RadioDemo

public static void main( String args[] )

Frame f = new Frame();

f.setVisible(true);

f.setSize(400,400);

f.setLayout(new FlowLayout());

Label l1 = new Label("Select Subjects:");

Checkbox cb1 = new Checkbox("English");

Checkbox cb2 = new Checkbox("Sanskrit");

Checkbox cb3 = new Checkbox("Hindi");

Checkbox cb4 = new Checkbox("Marathi");

Label l2 = new Label("Select Gender:");

CheckboxGroup cg = new CheckboxGroup();

Checkbox c1 = new Checkbox("Male",cg,true);

Checkbox c2 = new Checkbox("Female",cg,true);

f.add(l1);

f.add(cb1);

f.add(cb2);

f.add(cb3);

f.add(cb4);

f.add(l2);

f.add(c1);

f.add(c2);

}
PR:-1.1

import java.awt.*;

public class BasicAWT

public static void main(String args[])

Frame f = new Frame();

f.setSize(400,400);

f.setVisible(true);

f.setLayout(new FlowLayout() );

Label l1 = new Label();

l1.setText("Enter Your Name ");

TextField tf = new TextField("Atharva");

Label l2 = new Label("Address");

TextArea ta = new TextArea("",3,40);

Button b = new Button("Submit");

f.add(l1); f.add(tf); f.add(l2); f.add(ta); f.add(b);

}
PR:-2

import java.awt.*;

public class ChoiceDemo

public static void main(String args[])

Frame f = new Frame();

f.setSize(400,400);

f.setVisible(true);

f.setLayout(new FlowLayout());

Choice c = new Choice();

c.add("Maths");

c.add("Physics");

c.add("Chemistry");

f.add(c);

}
PR:-2.1

import java.awt.*;

import java.applet.*;

public class ListDemo extends Applet

public void init()

List c = new List();

c.setMultipleSelections(true);

c.add("The Times of India");

c.add("Lokmat");

c.add("Divya Marathi");

c.add("Navbharat Times");

add(c);

}
PR:- 3

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(c);

l[i].setBackground(c);

l[i].setText(s);

for(int i = 0 ; i < 25;i++)

f.add(l[i]);

PR:-3.1

import java.awt.*;

public class BorderDemo

public static void main( String args[] )

Frame f = new Frame();

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

f.setLayout(new BorderLayout());

Button b1 = new Button("North");

Button b2 = new Button("South");

Button b3 = new Button("East");

Button b4 = new Button("West");

Button b5 = new Button("Center");

f.add(b1,BorderLayout.NORTH);

f.add(b2,BorderLayout.SOUTH);

f.add(b3,BorderLayout.EAST);

f.add(b4,BorderLayout.WEST);

f.add(b5,BorderLayout.CENTER);

}
PR:-4

import java.awt.*;

import java.awt.event.*;

import javax.swing.JFrame;

import javax.swing.*;

public class CardLayoutDemo extends JFrame implements ActionListener {

CardLayout card;

JButton b1, b2, b3;

Container c;

CardLayoutDemo()

c = getContentPane();

card = new CardLayout(40, 30);

c.setLayout(card);
b1 = new JButton("First Level");

b2 = new JButton("Second Level");

b1.addActionListener(this);

b2.addActionListener(this);

c.add("a", b1);

c.add("b", b2);

public void actionPerformed(ActionEvent e)

card.next(c);

public static void main(String[] args)

CardLayoutDemo cl = new CardLayoutDemo();

cl.setSize(400, 400);

cl.setVisible(true);

cl.setDefaultCloseOperation(EXIT_ON_CLOSE);

}
PR:-4(EXERCISE)1

import java.awt.Button;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import javax.swing.*;

public class PR4a extends JFrame {

public PR4a() {

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);

public static void main(String[] args) {

PR4a a = new PR4a();

PR:-4(EXERCISE)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();

}
PR:-5

import java.awt.*;

import java.awt.event.ActionListener;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

import java.awt.event.ActionEvent;

public class MemuDialog extends Frame implements ActionListener ,ItemListener

Dialog dialog;

Label l;

MemuDialog()

MenuBar mBar = new MenuBar();

setMenuBar(mBar);

Menu file = new Menu("File");

MenuItem new_file = new MenuItem("New");

MenuItem open_file = new MenuItem("Open");

MenuItem save_file = new MenuItem("Save");

new_file.addActionListener(this);

open_file.addActionListener(this);

save_file.addActionListener(this);

file.add(new_file);

file.add(open_file);

file.add(save_file);

mBar.add(file);

Menu edit = new Menu("Edit");

MenuItem undo_edit = new MenuItem("Undo");

CheckboxMenuItem cut_edit = new CheckboxMenuItem("Cut");

CheckboxMenuItem copy_edit = new CheckboxMenuItem("Copy");

CheckboxMenuItem edit_edit = new CheckboxMenuItem("Paste");

undo_edit.addActionListener(this);
cut_edit.addItemListener(this);

copy_edit.addItemListener(this);

edit_edit.addItemListener(this);

Menu sub = new Menu("Save Type");

MenuItem sub1_sum = new MenuItem("Direct Save");

MenuItem sub2_sum = new MenuItem("Save As");

sub.add(sub1_sum);

sub.add(sub2_sum);

edit.add(sub);

edit.add(undo_edit);

edit.add(cut_edit);

edit.add(copy_edit);

edit.add(edit_edit);

mBar.add(edit);

dialog = new Dialog(this,false);

dialog.setSize(200,200);

dialog.setTitle("Dialog Box");

Button b = new Button("Close");

b.addActionListener(this);

dialog.add(b);

dialog.setLayout(new FlowLayout());

l = new Label();

dialog.add(l);

public void actionPerformed(ActionEvent ie)

String selected_item = ie.getActionCommand();

switch(selected_item)

case "New": l.setText("New");

break;
case "Open": l.setText("Open");

break;

case "Save": l.setText("Save");

break;

case "Undo": l.setText("Undo");

break;

case "Cut": l.setText("Cut");

break;

case "Copy": l.setText("Copy");

break;

case "Paste": l.setText("Paste");

break;

default: l.setText("Invalid Input");

dialog.setVisible(true);

if(selected_item.equals("Close"))

dialog.dispose();

public void itemStateChanged(ItemEvent ie)

this.repaint();

public static void main(String[] args)

MemuDialog md = new MemuDialog();

md.setVisible(true);

md.setSize(400,400);

}
}
PR:-6(EXERCISE)

import javax.swing.*;

import java.awt.*;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

public class JComboBoxDemo extends JApplet implements ItemListener

JLabel JLabelObj ;

public void init()

setLayout(new FlowLayout());

setSize(400, 400);

setVisible(true);

JComboBox JComboBoxObj = new JComboBox();

JComboBoxObj.addItem("Solapur");

JComboBoxObj.addItem("Pune");

JComboBoxObj.addItem("Banglore");

JComboBoxObj.addItem("Mumbai");

JComboBoxObj.addItemListener(this);

JLabelObj = new JLabel();

add(JComboBoxObj);

add(JLabelObj);

public void itemStateChanged(ItemEvent ie)

String stateName = (String) ie.getItem();

JLabelObj.setText("You are in "+stateName);

}
PR:-6

import javax.swing.*;

import java.awt.*;

public class DifferentState

public static void main(String args[])

JFrame JFrameMain = new JFrame();

JFrameMain.setVisible(true);

JFrameMain.setSize(400,400);

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

String states[] = {"Solapur","Pune","Mumbai","Banglore"};

JComboBox JComboBoxStates = new JComboBox(states);

JFrameMain.add(JComboBoxStates);

PR:-6.1

import javax.swing.*;

import java.awt.*;
public class JScrollPaneDemo

public static void main(String[] args)

/* Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

*/

JFrame JFrameMain = new JFrame();

JFrameMain.setVisible(true);

JFrameMain.setSize(400,400);

JPanel JPanelButton = new JPanel();

JPanelButton.setLayout(new GridLayout(20,10));

for( int i = 1 ; i <= 200 ; i++ )

String s = "";

s = s.valueOf(i);

JPanelButton.add(new JButton( s ) );

int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ;

JScrollPane JScrollPaneObj = new JScrollPane(JPanelButton , v,h);

JFrameMain.add(JScrollPaneObj , BorderLayout.CENTER);

}
PR:-7

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);

}
PR:-8(EXERCISE)

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);

//JFrameMain.add(JTableObj);

}
PR:-8

import java.awt.BorderLayout;

import javax.swing.JApplet;

import javax.swing.JTable;

import javax.swing.ScrollPaneConstants;

import javax.swing.JScrollPane;

public class JTableStudents extends JApplet

public void init()

setVisible(true);

setSize(400,400);

//setLayout( new BorderLayout() );

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

Object data[][]={

{"A1",98,"A"},

{"A2",90,"C"},

{"A3",88,"A"},

{"A4",99,"A"},

{"A5",59,"A"},

{"A6",94,"D"},

{"A7",92,"A"},

{"A8",42,"C"},

{"A9",85,"A"},

{"A10",98,"B"}

};

JTable JTableObj = new JTable(data,collumnHeading);

int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

JScrollPane jsp = new JScrollPane(JTableObj,v,h);

add(jsp,BorderLayout.CENTER);
}

PR:-9

import javax.swing.*;

import java.awt.*;

public class JProgresBarDemo

JProgressBar JProgressBarObj;

int i=0,num=0;

JProgresBarDemo()

JFrame JFrameMain = new JFrame();

JFrameMain.setVisible(true);

JFrameMain.setSize(400,400);

JFrameMain.setLayout(new FlowLayout());

JProgressBarObj = new JProgressBar(0,2000);

JProgressBarObj.setValue(0);

JProgressBarObj.setStringPainted(true);

JFrameMain.add(JProgressBarObj);
}

public static void main(String[] args)

JProgresBarDemo jpd = new JProgresBarDemo();

jpd.iterate();

public void iterate()

while(i<=2000){

JProgressBarObj.setValue(i);

i =i+20;

try

Thread.sleep(150);

catch(Exception e)

}
PR:-9.1

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class JProgressBarApplet extends JApplet implements ActionListener

JProgressBar JProgressBarObj;

JButton JButtonObj;

int i=0;

public void init()

setSize(400,400);

setVisible(true);

setLayout(new FlowLayout());

JButtonObj = new JButton("Click Me");

JButtonObj.addActionListener(this);

JProgressBarObj = new JProgressBar();

JProgressBarObj.setStringPainted(true);
JProgressBarObj.setValue(0);

add(JButtonObj);

add(JProgressBarObj);

public void actionPerformed(ActionEvent ie)

this.iterate();

public void iterate()

while(i<=2000)

JProgressBarObj.setValue(i);

i=i+20;

try

Thread.sleep(150);

catch(Exception e)

{}

}
PR:-10

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class KeyEventDemo extends Applet implements KeyListener

String msg = "";

public void init()

addKeyListener(this);

public void keyReleased(KeyEvent k)

showStatus("Key Released");

repaint();

public void keyTyped(KeyEvent k)

showStatus("Key Typed");

repaint();

public void keyPressed(KeyEvent k)

showStatus("Key Pressed");

repaint();

public void paint(Graphics g)

g.drawString(msg, 10, 10);

}
PR:-10.1

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class KeyEventDemo extends Applet implements KeyListener

String msg = "";

public void init()

addKeyListener(this);

public void keyPressed(KeyEvent k)

int key = k.getKeyCode();

switch(key)

case KeyEvent.VK_F1:

msg = msg + "F1 ";

break;

case KeyEvent.VK_F2:

msg = msg + "F2 ";

break;
case KeyEvent.VK_F3:

msg = msg + "F3 ";

break;

case KeyEvent.VK_F4:

msg = msg + "F4 ";

break;

case KeyEvent.VK_RIGHT:

msg = msg + "RIGHT ";

break;

case KeyEvent.VK_LEFT:

msg = msg + "LEFT ";

break;

case KeyEvent.VK_UP:

msg = msg + "UP ";

break;

case KeyEvent.VK_DOWN:

msg = msg + "DOWN ";

break;

repaint();

public void keyReleased(KeyEvent k){}

public void keyTyped(KeyEvent k){}

public void paint(Graphics g)

g.drawString(msg, 10, 10);

}
PR:-11

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class MouseColor extends Applet implements MouseMotionListener

public void init()

addMouseMotionListener(this);

public void mouseDragged(MouseEvent me)

setBackground(Color.red);

repaint();

public void mouseMoved(MouseEvent me)

setBackground(Color.green);

repaint();

}
PR:-11.1

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class MouseCount extends Applet implements MouseListener

int count = 0;

public void init()

addMouseListener(this);

public void mouseClicked(MouseEvent me)

count++;

showStatus("Number of time Clicked:"+count);

repaint();

public void mouseEntered(MouseEvent me)

public void mouseExited(MouseEvent me)

}
public void mousePressed(MouseEvent me)

public void mouseReleased(MouseEvent me)

PR:-12

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);

}
PR:-12.1

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));

PR:-13

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();

PR:-13.1

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 Bro ");

jb.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae)

System.out.println("Action Event:"+ae);

});

ai.add(jb);

ai.pack();

ai.setVisible(true);

PR:-13.2

import java.awt.event.MouseMotionAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.MouseMotionListener;

import java.applet.Applet;

public class AdapterMouseDrag extends Applet

public void init()


{

addMouseMotionListener(new MouseDrag(this));

class MouseDrag extends MouseMotionAdapter

AdapterMouseDrag ad;

public MouseDrag(AdapterMouseDrag ad)

this.ad = ad;

public void mouseDragged(MouseEvent me)

ad.showStatus("Mouse Dragged");

PR:-14

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);

PR:-15

import java.net.URL;

import java.net.MalformedURLException;

public class URLRetrive

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

URL url = new URL("https://msbte.org.in/");

System.out.println("Authority: "+ url.getAuthority());

System.out.println("Default Port: "+ url.getDefaultPort());

System.out.println("File: "+ url.getFile());

System.out.println("Path: "+ url.getPath());


System.out.println("Protocol: "+ url.getProtocol());

System.out.println("Reference: "+ url.getRef());

PR:-15.1

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());

}
}

PR:-16

SERVER:- 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("abc") && pass.equals("1234"))

ps.println("Validate Successfully");

else

ps.println("Validate Un-Successfull");

CLIENT:- 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);

PR:16.1

SERVER:- 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(2019);

System.out.println("Server Started, waiting for client");

Socket s1 = s.accept();

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);

CLIENT:- 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 ClientSice

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

Socket s = new Socket("localhost",2019);

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);

PR:-17

SERVER:- 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);

CLIENT:- 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);

}
PR:-17.1

SERVER:- 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("F:\\Project\\Java\\Advanced Java\\4


Networking Basics\\File\\SFile.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());

CLIENT:- 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("F:\\Project\\Java\\Advanced Java\\4


Networking Basics\\File\\CFile.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));

PR:-18(EXERSICE3)

javac /tmp/6diYI4wqH0/JdbcDemo.java

/tmp/6diYI4wqH0/JdbcDemo.java:1: error: ';'

expected import java.sql*;

^ /tmp/6diYI4wqH0/JdbcDemo.java:2: error: '{' expected class JdbcDemo

^ /tmp/6diYI4wqH0/JdbcDemo.java:27:

error: reached end of file while parsing } ^ 3 errors

PR:-18.1

import java.sql.*;
import java.sql.Statement.*;

import java.io.*;

public class StudentDb {

public static void main(String args[])

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

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

String url="jdbc:odbc:TYCM";

Connection con=DriverManager.getConnection(url);

System.out.println("connected");

Statement s=con.createStatement();

Statement si = con.createStatement();

Statement st=con.createStatement();

s.executeUpdate("create table student1(Name varchar(20), Rollno integer, Percentage integer)");

System.out.println("Table created");

si.executeUpdate("insert into student1 values('abc',1,78)");

si.executeUpdate("insert into student1 values('xyz',2,34)");

si.executeUpdate("insert into student1 values('pqr',3,89)");

si.executeUpdate("insert into student1 values('hij',4,60)");

System.out.println("Data inserted");

String s1; s1="select * from student1 where Percentage > 70";

ResultSet rs=st.executeQuery(s1);

rs=st.getResultSet();

System.out.println("Students having percentage > 70 :");

while(rs.next())

System.out.println(rs.getString("Name")+" "+rs.getInt("Rollno")+" "+rs.getInt("Percentage"));

con.close();
}

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

}}}

PR:-19

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class UpdateRecordExample2 {

public static void main(String[] args)

{ String jdbcUrl = "jdbc:mysql://localhost:3306/MSBTE";

String username = "root";

String password = "Kadam@123";

String sql = "update student set Sname=? where Sid=?";

try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);

PreparedStatement stmt = conn.prepareStatement(sql);

{ stmt.setString(1,"Henry Ellenson"); stmt.setInt(2, 101);

stmt.executeUpdate();

System.out.println("Database updated successfully ");

catch (SQLException e) { e.printStackTrace();

}}}
Pr:-20

import java.sql.*;

public class Main {

public static void main(String[] args) {

String username = "shantanu";

String password = "shantanu";

try{ System.out.println("Driver Registration Started");

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

System.out.println("Driver Registered Successfully");

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/MSBTE


",username,password);

Statement statement = connection.createStatement();

String query = "DELETE FROM products_table WHERE id='1234' AND price>500";

int result = statement.executeUpdate(query);

if(result == 1)

{ System.out.println("Data deleted successfully");

} else {

System.out.println("Data not deleted");

}}
catch (Exception e){ e.printStackTrace();

}}}

PR:-21

File: index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-


8859-1"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Practical No. 21</title>

</head>

<body>

<center>

<h1>You Will Get One From Servlet Here</h1>

<form action="MyServlet">

<button type="submit">Click Me To Get Message</button>

</form>

</center>

</body>

</html>

File: MyServlet.java
import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/MyServlet")

public class MyServlet extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

PrintWriter outPrintWriter = response.getWriter();

outPrintWriter.println("Hello MSBTE");

}}

PR:-22

HTML Code:

<html>

<body>
<form action = "http://localhost:8080/P2/u" method="post">

User Name: <input type="text" name="username">

<br>

<input type="submit">

</form>

</body>

</html>

SERVLET:-

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.*;

import javax.servlet.http.*;

public class Username extends HttpServlet {

protected void doPost(HttpServletRequest request,HttpServletResponse response)

throws ServletException,IOException

{ response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

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

if(username.length()==0)

{ out.println("Please Enter Username");

} else {

out.println("Length of " + username + " = " + username.length() +"");

}}}

WEB.xml Code:

<web-app>

<servlet>

<servlet-name>User</servlet-name>

<servlet-class>Username</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>User</servlet-name>
<url-pattern>/u</url-pattern>

</servlet-mapping>

</web-app>

PR:-23

Index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-


8859-1"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Practical No. 23</title>

<%@ include file="cdn_links.jsp" %>

<style> .bg-custom { background: #8e24aa; } </style>

</head>
<body>

<div class="container-fluid">

<div class="row">

<div class="col-md-4 offset-md-4">

<div class="card mt-5">

<div class="card-header text-center text- white bg-custom">

<h4 class="mt-3">Practical No. 23</h4>

</div> <div class="card-body">

<form action="HttpSessionDemo" method="post">

<h4 class="text-center font-weight- bold mt-3 mb-5"> Click the button to activate / start the HTTP
Session! </h4>

<div class="container">

<div class="row">

<div class="col text- center">

<button type="submit" class="btn btn-primary mt-3">Activate Session Now</button>

</div> </div> </div>

</form> </div> </div>

<% String sessionLastAccessTime = (String)session.getAttribute("sessionLastAccessTime"); String


sessionTimeOut = (String)session.getAttribute("sessionTimeOut"); if(sessionLastAccessTime != null){
%>

<div class="card mt-5">

<div class="card-body">

<form action="HttpSessionDemo" method="post">

<h6 class="text-center mt-3 mb-2"> Session Last Access Time: <%=sessionLastAccessTime %> </h6>

<h6 class="text-center mt-3 mb-2"> Session Will Expire In: <%=sessionTimeOut %> Seconds of Your
Inactivity </h6>

</form>

</div> </div> <% } %> </div> </div> </div>

</body>

</html>

HttpSessionDemo.java;

import java.io.IOException;
import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

@SuppressWarnings("serial") @WebServlet("/HttpSessionDemo")

public class HttpSessionDemo extends HttpServlet {

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws

ServletException, IOException { HttpSession session = request.getSession();

String sessionLastAccessTime = String.valueOf(session.getLastAccessedTime());

session.setAttribute("sessionLastAccessTime",

sessionLastAccessTime);

session.setMaxInactiveInterval(100);

session.setAttribute("sessionTimeOut", "100");

response.sendRedirect("index.jsp");

}}
PR:-24

CookiesDemo.java

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Enumeration;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/CookiesDemo")

public class CookiesDemo extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException { Cookie c1 = new Cookie("username", "Shantanu");

Cookie c2 = new Cookie("password", "shantanu");

response.addCookie(c1);

response.addCookie(c2);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Cookies Demo | Practical No. 24</TITLE>");

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

out.println("<BODY>");

out.println("Please click the button to see the cookies sent to you.");

out.println("<BR>");

out.println("<FORM METHOD=POST>");

out.println("<INPUT TYPE=SUBMIT VALUE=Submit>");

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

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

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

} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException { response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Cookies Demo | Practical No. 24</TITLE>");

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

out.println("<BODY>");

out.println("<H2>Here Are All The Cookies :</H2>");

Cookie[] cookies = request.getCookies();

int length = cookies.length;

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


Cookie cookie = cookies[i];

out.println("<B>Cookie Name : </B> " + cookie.getName() + "<BR>");

out.println("<B>Cookie Value : </B> " + cookie.getValue() + "<BR>");

} out.println("</BODY>");

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

}}

You might also like