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

A

LAB REPORT

ON

Java Programming II

By

Aashutosh Kayastha

TU Symbol No: 9182/18

BIM 5th Semester, Java Programming II

Submitted to:
Mr. Niraj Khadka
Department of Management

Nepal Commerce Campus

In partial fulfillment of the requirements for the Course

Java Programming II

Minbhawan, Kathmandu

December, 2021
TABLE OF CONTENTS

1. WRITE AN APPLET PROGRAM: TO DISPLAY YOUR NAME, ROLL NO., SECTION AND COLLEGE
NAME, TO DEMONSTRATE PASSING PARAMETERS FROM HTML TO APPLET ..............................4
2. WRITE A PROGRAM USING AWT: DEMONSTRATING CREATION OF FRAME WINDOW BY
EXTENDING (INHERITING) FRAME CLASS AND DISPLAY YOUR NAME, SECTION AND ROLL NO, TO
ILLUSTRATE CREATION OF FRAME WINDOW BY INSTATING FRAME CLASS AND DISPLAY YOUR
NAME AND ADDRESS. .....................................................................................................5
3. WRITE A JAVA PROGRAM TO DEMONSTRATE: FLOW LAYOUT MANAGER, BORDER LAYOUT
MANAGER, GRID LAYOUT MANAGER, GRID BAG LAYOUT MANAGER ......................................7
4. WRITE A PROGRAM TO DESIGN A AWT FRAME WINDOW THAT CONTAINS THE CONTROLS LIKE
LABEL, TEXT BOX, CHECK BOXES. ..................................................................................12
5. WRITE A JAVA PROGRAM USING AWT : TO ILLUSTRATE THE USE OF CHECK BOX GROUP, TO
DESIGN AND DISPLAY CHOICE CONTROL, TO CREATE AND DISPLAY LIST CONTROL, TO CREATE
AND DISPLAY TEXT BOX AND TEXT AREA ........................................................................13

6. WRITE A PROGRAM USING AWT TO CREATE MENUS. ...................................................17


7. WAP TO DEMONSTRATE EVENT HANDLING IN JAVA BY PLACING EVENT HANDLING CODE:
WITHIN THE SAME CLASS WHERE EVENT SOURCE IS PRESENT, IN OTHER CLASS THAN THE CLASS
WHERE EVENT SOURCE IS PRESENT. ................................................................................18
8. WAP: TO COMPUTE THE LENGTH OF THE STRING ENTERED IN AN APPLET, TO DEMONSTRATE
KEY EVENT HANDLING SHOWING WORD COUNTS, TO ILLUSTRATE MOUSE EVENT HANDLING
USING ADAPTER CLASS. ................................................................................................20

9. WAP TO ILLUSTRATE TOGGLE BUTTON IN SWING. ......................................................23


10. WRITE GUI PROGRAM USING SWING AND EVENT HANDLING: TO SHOW THE CHECK BOXES, TO
SHOW RADIO BUTTONS. ................................................................................................24

11. DESIGN A GUI THAT CONTAINS: TABBED PANES USING SWING, LIST USING SWING. .........27

12. CREATE A GUI USING SWING TO DEMONSTRATE: COMBO BOX, TABLE. ..........................29
13. WAP IN JAVA TO READ AND DISPLAY ALL THE DATA STORED IN A TABLE OF SOME DATABASE
USING JDBC. ................................................................................................................31

14. WRITE A PROGRAM USING JDBC TO INSERT A ROW INTO A TABLE OF SOME DATABASE. ...32
15. WRITE A JAVA PROGRAM THAT ALLOWS A USER TO INSERT VALUES TO A TABLE OF
PARTICULAR DATABASE (SUPPOSE DATABASE IS IN MYSQL SERVER ). THE PROGRAM SHOULD
TAKE THE VALUES TO INSERT FROM CONSOLE..................................................................33
16. WAP USING JDBC TO DISPLAY THE RECORDS FROM A TABLE OF GIVEN DATABASE (SUPPOSE
DATABASE IS IN MYSQL SERVER ). ASSUME THE FOLLOWING TABLE : RESULT(ROLL_NO ,
COURSE_NAME ,MARKS_OBTAINED). THE PROGRAM SHOULD READ THE ROLL NUMBER VALUE
FROM CONSOLE AND DISPLAY THE CORRESPONDING RECORD. ...........................................34
17. WAP USING JDBC TO: INSERT A RECORD INTO TABLE USING PREPAREDSTATEMENT,
RETRIEVE AND DISPLAY THE RECORDS OF TABLE USING PREPAREDSTATEMENT, DELETE A
RECORD OF A TABLE USING PREPAREDSTATEMENT, THAT UPDATE THE RECORD OF TABLE USING
PREPAREDSTATEMENT. .................................................................................................35
18. WRITE A JAVA PROGRAM USING PREPAREDSTATEMENT THAT ALLOWS A USER TO INSERT
VALUES TO A TABLE OF PARTICULAR DATABASE (SUPPOSE DATABASE IS IN MYSQL SERVER). THE
PROGRAM SHOULD TAKE THE VALUES TO INSERT FROM CONSOLE AS LONG AS USER WANT TO
ADD NEW RECORD. .......................................................................................................37
19. WAP USING PREPAREDSTATEMENT TO DISPLAY THE RECORDS FROM A TABLE OF GIVEN
DATABASE (SUPPOSE DATABASE IS IN MYSQL SERVER ). ASSUME THE FOLLOWING TABLE :
SALARY(EMP_ID , EMP_NAME ,EMP_SALARY) THE PROGRAM SHOULD READ THE EMPLOYEE ID
VALUE FROM CONSOLE AND DISPLAY THE CORRESPONDING RECORD. .................................38
20. DEVELOP A CRUD APPLICATION USING SWING AND JDBC. YOUR UI MUST CONTAIN TEXT
FIELD, RADIO BUTTON AND COMBO BOX (USE OTHER COMPONENTS AS REQUIRED). [SOURCE CODE
CAN BE PRINTED FOR THIS TASK] .....................................................................................40
21. CREATE A DTD FILE WITH SOME ELEMENT AND ATTRIBUTE. NOW CREATE AN XML FILE AND
VALIDATE THE XML AGAINST THE DTD. ..........................................................................44
22. CREATE A XSD FILE WITH SOME ELEMENT AND ATTRIBUTE. NOW CREATE AN XML FILE AND
VALIDATE THE XML AGAINST THE XSD. ...........................................................................45
23. WRITE A SERVLET THAT TAKES A NUMBER FROM A HTML FORM AND DISPLAYS THE
MULTIPLICATION TABLE OF THAT NUMBER. (ALSO WRITE THE CONTENTS OF HTML AND WEB.XML
FILES L) ......................................................................................................................45

24. WAP IN JSP TO DEMONSTRATE: PAGE DIRECTIVE, INCLUDE DIRECTIVE. .........................47


25. WAP: TO DEMONSTRATE JSP DECLARATION, JSP EXPRESSION AND JSP SCRIPTLET, TO PRINT
“BIM FIFTH ROCKS” 10 TIMES USING JSP, THAT TAKES PRINCIPAL, RATE AND TIME VALUES AND
DISPLAYS THE SIMPLE INTEREST VALUE USING JSP............................................................47
26. WAP TO ILLUSTRATE THE USE OF <JSP: USEBEAN> <JSP: SETPROPERTY> AND <JSP:
GETPROPERTY> (ALSO WRITE THE CONTENTS OF BEAN CLASS) ...........................................48
27. WRITE A SERVLET PROGRAM THAT TAKES VALUES FROM A SIGNUP FORM AND STORE THEM
IN A DATABASE TABLE. . (ALSO WRITE THE CONTENTS OF HTML AND WEB.XML FILES. SHOW THE
CONTENTS OF DATABASE TABLE AFTER INSERTING THE VALUES) .......................................49

28. WAP TO DEMONSTRATE INCLUDE AND FORWARD METHODS IN SERVLET. ......................53


29. WRITE A PROGRAM TO DEMONSTRATE SESSION CREATION, SETTING AND RETRIEVING
VALUES FORM SESSION AND DESTRUCTION OF SESSION IN SERVLET. (WRITE THE CONTENTS OF
HTML AND WEB.XML FILES ............................................................................................55
1. Write an applet program: to display your Name, Roll No., Section and College Name, to
demonstrate passing parameters from HTML to Applet
Theory:
Applet is a of program that is embedded in the webpage to generate the dynamic content. It runs
inside the browser and works at client side. An applet is a Java class that extends the
java.applet.Applet class. A JVM is required to view an applet. The JVM can be either a plug-in of
the Web browser or a separate runtime environment.

a. Source Codes:
package com.aasu.aasutosh_a_12;
import java.awt.*;
import java.applet.*;
public class a extends Applet {
@Override
public void paint(Graphics g) {
g.drawString("Name: Bishnu Bohara", 20, 20);
g.drawString("Roll No: 16",20,40);
g.drawString("Section: A",20,60);
g.drawString("College Name: Nepal Commerce Campus",20,80);
} }

<applet code="a" width=400 height=100></applet>


b. Source Codes:
package com.aasu.aasutosh_a_12;
import java.applet.Applet;
public class b extends Applet {
@Override
public void init(){
String pos1, pos2, msg;
msg = getParameter("message");
pos1= getParameter("param1");
pos2 = getParameter("param2"); }}

<APPLET code = "ParamApplet.class" WIDTH = 300 HEIGHT = 100>


<PARAM NAME = "message" VALUE = "Hello!!!">
<PARAM NAME = "param1" VALUE = "50">
<PARAM NAME = "param2" VALUE = “60">
</APPLET>

2. Write a program using AWT: demonstrating creation of frame window by extending


(inheriting) Frame class and display your Name, Section and Roll No, to illustrate creation
of frame window by instating Frame class and display your Name and Address.

Theory: AWT was the first Java’s GUI framework. AWT contains large number of classes and
methods. It can create components like buttons, frames, panels, etc. It is defined in the AWT
class.

package com.aasu.aasutosh_a_12;
import java.awt.Frame;
import java.awt.FlowLayout;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AWTa implements ActionListener {
TextField tf; Frame f;
public AWTa(){
f= new Frame("My Frame");
tf = new TextField(); tf.setSize(100,200);
f.setSize(600,600); f.setVisible(true);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.add(tf);
tf.addActionListener(this);
}
public static void main(String[]args){
new AWTa();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Text typed is:"+tf.getText()); }}
package com.aasu.aasutosh_a_12;
import java.awt.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AWTb implements ActionListener {
Frame f; Button b;
Label l; TextField tf;
AWTb(){
f= new Frame("Name");
b= new Button("Show");
l = new Label("Name and Address:");
tf= new TextField("Bishnu,Shankhamul");
f.setSize(500,500);
f.setVisible(true);
f.add(l); f.add(tf);f.add(b);
l.setBounds(30,100,100,50);
tf.setBounds(140,100,200,200);}
public static void main(String[] args){
new AWTb();}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("The Name and address is"+tf.getText());
}}

3. Write a java program to demonstrate: Flow Layout Manager, Border Layout Manager,
Grid Layout Manager, Grid Bag Layout Manager
Theory:

The layout manager automatically positions all the components within the container. If we do
not use layout manager then also the components are positioned by the default layout
manager.

FlowLayout
• It is the default layout manager. FlowLayout implements a simple layout style, which is
similar to how words flow in a text editor.
BorderLayout

• The BorderLayout class implements a common layout style for top-level windows. It has
four narrow, fixed-width components at the edges and one large area in the center. The four
sides are referred to as north, south, east, and west. The middle area is called the center.

GridLayout

• GridLayout lays out components in a two-dimensional grid. When you instantiate a


GridLayout, you define the number of rows and columns.
GridBagLayout
This provides more control over how the components are arranged.
• What makes the grid bag useful is that you can specify the relative placement of components
by specifying their positions within cells inside a grid. The key to the grid bag is that each
component can be a different size, and each row in the grid can have a different number of
columns. This is why the layout is called a grid bag. It’s a collection of small grids joined
together. The location and size of each component in a grid bag are determined by a set of
constraints linked to it. The constraints are contained in an object of type
GridBagConstraints. Constraints include the height and width of a cell, and the placement
of a component, its alignment, and its anchor point within the cell.
package com.aasu.aasutosh_a_12;
import java.awt.*;
public class Borderlayoutex{
Frame f; Button b1, b2, b3, b4, b5;
public Borderlayoutex(){
f = new Frame("Border Layout Example");
f.setSize(400, 350);
f.setLayout(new BorderLayout());
b1 =new Button("Center"); b2 =new Button("East");
b3 =new Button("South"); b4 =new Button("North");
b5 =new Button("West"); f.add(b1, BorderLayout.CENTER);
f.add(b2, BorderLayout.EAST); f.add(b3, BorderLayout.SOUTH);
f.add(b4, BorderLayout.NORTH); f.add(b5, BorderLayout.WEST);
f.setVisible(true);}
public static void main(String[] args){
new Borderlayoutex();
}}
package com.bish.bim;
import java.awt.*;
public class Flowlayouteg{
Frame f; Button b1, b2, b3;
public Flowlayouteg(){
f = new Frame("Flow Layout Example");
b1 = new Button("Button 1"); b2 = new Button("Button 2");
b3 = new Button("Button 3"); f.setSize(400, 300);
f.setLayout(new FlowLayout(FlowLayout.CENTER));
f.add(b1);f.add(b2);f.add(b3);
f.setVisible(true);
}
public static void main(String[] args){
new Flowlayouteg();
}}
package com.aasu.aasutosh_a_12;
import java.awt.*;
public class gridlayoutsoln {
Frame f; Button b1,b2,b3,b4,b5;
gridlayoutsoln(){
f=new Frame("Grid Layout");
b1= new Button("Grid 1");
b2= new Button("Grid 2"); b3= new Button("Grid 3");
b4= new Button("Grid 4"); b5= new Button("Grid 5");
f.add(b1); f.add(b2); f.add(b3);
f.add(b5); f.add(b4);
f.setSize(400,400); f.setVisible(true);
f.setLayout(new GridLayout(3,2));}
public static void main(String args[]) {
new gridlayoutsoln();}}

package com.aasu.aasutosh_a_12;
import java.awt.*;
import javax.swing.*;
public class gridbaglayoutsoln extends JFrame{
GridBagLayout gbl;
GridBagConstraints gbc;
public gridbaglayoutsoln(){
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
this.setLayout(gbl);
this.setTitle("Grid Bag Layout");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0; gbc.gridy = 0;
this.add(new JButton("Button 1"), gbc);
gbc.gridx = 1; gbc.gridy = 0;
this.add(new JButton("Button 2"), gbc);
gbc.gridx = 2; gbc.gridy = 0;
this.add(new JButton("Button 3"), gbc);
gbc.gridx = 3; gbc.gridy = 0;
this.add(new JButton("Button 4"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2;
this.add(new JButton("Button 5"), gbc);
gbc.gridx = 2; gbc.gridy = 1;
gbc.gridwidth = 2;
this.add(new JButton("Button 6"), gbc);
this.setSize(300, 300); this.setVisible(true);}
public static void main(String[] args){
new gridbaglayoutsoln();
} }
4. Write a program to design a AWT frame window that contains the controls like label, text
box, check boxes.
package com.aasu.aasutosh_a_12;
import java.awt.*;
import java.awt.FlowLayout;
public class awtcomponents {
Frame f; Button b; Label l;
TextField tf; Checkbox cb1,cb2,cb3;
public awtcomponents(){
f =new Frame("Different Elements in AWT");
b = new Button("Click Me");
b.setBounds(20,20,60,80);
l =new Label("I m Label");
l.setBounds(20,20,400,500);
cb1= new Checkbox("Option 1");
cb2 = new Checkbox("Option 2");
cb3 = new Checkbox("Option 3");
f.setSize(250,300);
f.setVisible(true); l.setText("I m Label !!!");
f.add(b); f.add(l);
f.add(cb1); f.add(cb2); f.add(cb3);
f.setLayout(new FlowLayout(FlowLayout.LEFT));}
public static void main(String args[]) {
new awtcomponents();
}}
5. Write a java program using AWT : to illustrate the use of Check Box Group, to design and
display choice control, to create and display list control, to create and display text box and
text area
package com.aasu.aasutosh_a_12;
import java.awt.Checkbox; import java.awt.FlowLayout;
import java.awt.CheckboxGroup;
import java.awt.Frame; import java.awt.Label;
public class checkboxgrp {
Frame f ; CheckboxGroup cbg;
Checkbox cb1,cb2,cb3; Label l1;
public checkboxgrp(){
f= new Frame("Checkbox Group");
f.setSize(400,300);
l1= new Label("Please select your gender");
cbg=new CheckboxGroup();
cb1 = new Checkbox("Male",true,cbg);
cb2 = new Checkbox("Female",false,cbg);
cb3 = new Checkbox("Unspecified",false,cbg);
f.add(l1); f.add(cb1); f.add(cb2); f.add(cb3);
f.setLayout(new FlowLayout(FlowLayout.LEFT));//
f.setVisible(true);}
public static void main (String[] args){
new checkboxgrp();
}}

package com.aasu.aasutosh_a_12;
import java.awt.*;
import java.awt.event.*;
public class choicecontrol implements ActionListener{
Frame f; Choice c;
Button b;
choicecontrol(){
f= new Frame("Choice Control");
f.setSize(400, 300);
b = new Button("Click me");
b.setBounds(50,200,60,30);
b.addActionListener(this);
c= new Choice();
c.setBounds(50,50,100,250);
c.add("A"); c.add("B"); c.add("C");
c.add("D"); c.add("E"); c.add("F");
f.add(c); f.add(b);
f.setLayout(null); f.setVisible(true); }
public static void main(String[]args){
new choicecontrol(); }
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("The selected choice is
:"+c.getSelectedItem()); }}

package com.aasu.aasutosh_a_12;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class listcontrol implements ItemListener{
Frame f; List l; Button b;
listcontrol(){
f= new Frame("List Control Example");
b= new Button("Click me!!!");
f.setSize(400,300); l=new List();
l.add("Nepal"); l.add("India");
l.add("China"); l.add("Pakistan");
l.setBounds(50,50,50,50); f.add(l);
f.setVisible(true); f.setLayout(null);
l.addItemListener(this);}
public static void main(String[]args){
new listcontrol();}
@Override
public void itemStateChanged(ItemEvent e) {
System.out.println("Item selected is :"+l.getSelectedItem());
}}

package com.aasu.aasutosh_a_12;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class textarea implements ActionListener {
Frame f; TextArea ta;
Label l; Button b;
textarea(){
f= new Frame("Text Area Example");
f.setSize(400,300);
l= new Label("Type here...");
l.setBounds(20, 50, 100, 20);
ta = new TextArea();
ta.setBounds(30,80,300,100);
b=new Button("Submit");
b.setBounds(20, 200, 70, 20);
b.addActionListener(this);
f.add(l); f.add(ta);
f.add(b); f.setLayout(null);
f.setVisible(true);}
public static void main(String[]args){
new textarea();}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Text typed is:"+ta.getText());
}}
6. Write a program using AWT to create Menus.
package com.bish.bim;
import java.awt.*;
import java.awt.event.*;
public class menuex implements ActionListener{
Frame f; MenuBar mb;
Menu File, Edit, About;
MenuIte _new,open,close,exit,undo,redo,find,replace,
developer,system;
menuex(){
f=new Frame("Menu Example");
f.setSize(400,300);
mb= new MenuBar();
File= new Menu("File");
Edit= new Menu("Edit"); About= new Menu("About");

_new= new MenuItem("New");


open= new MenuItem("Open");
open.setActionCommand("OPEN");
open.addActionListener(this);
close= new MenuItem("Close");
exit= new MenuItem("Exit");
exit.setActionCommand("EXIT");
exit.addActionListener(this);
undo= new MenuItem("Undo");
redo= new MenuItem("Redo");
find= new MenuItem("Find");
replace= new MenuItem("Replace");
developer= new MenuItem("About Developers");
developer.setActionCommand("Dev");
developer.addActionListener(this);
system= new MenuItem("About System");
File.add(_new); File.add(open); File.add(close);File.add(exit);
Edit.add(undo);Edit.add(redo);Edit.add(find);Edit.add(replace);
About.add(developer);About.add(system);
mb.add(File); mb.add(Edit); mb.add(About);
f.setMenuBar(mb); f.setVisible(true);
f.setLayout(null); }
public static void main(String[]args){
new menuex(); }
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("EXIT")){
System.out.println("Exiting");
f.dispose(); }
else if (e.getActionCommand().equals("OPEN")){
System.out.println("Opening command"); }
else if (e.getActionCommand().equals("Dev")){
System.out.println("About Developer");}
else{ System.out.println("Nothing");}
}}

7. WAP to demonstrate event handling in Java by placing event handling code: within the
same class where event source is present, in other class than the class where event source
is present.
package com.aasu.aasutosh_a_12;
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class AEhandlea extends JFrame implements ActionListener {
JTextField name;
public AEhandlea(){
name = new JTextField("Hello");
name.setSize(200, 30);
this.setTitle("AE Handling");
this.setSize(400, 300);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
name.setText("Any text here...");
name.addActionListener(this);
this.add(name); this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}
public static void main(String[] args) {
AEhandlea ae = new AEhandlea();}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Text in textbox is:
"+this.name.getText());}}

package com.aasu.aasutosh_a_12;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AEouter extends Frame {
TextField tf;
AEouter(){
tf = new TextField();
tf.setBounds(60,50,170,20);
Button b= new Button("Click Me!!!");
b.setBounds(100,120,80,30);
Outer o = new Outer(this);
b.addActionListener((ActionListener) o);
add(b); add(tf);
setSize(300,300); setLayout(null);
setVisible(true);}
public static void main(String args[]) {
new AEouter();}
class Outer implements ActionListener {
AEouter ob;
Outer(AEouter ob){
this.ob=ob;}
public void actionPerformed(ActionEvent e){
ob.tf.setText("Outer Class laa");
}}}

8. WAP: to compute the length of the string entered in an applet, to demonstrate key event
handling showing word counts, to illustrate mouse event handling using adapter class.
import java.applet.Applet;
import java.awt.Graphics;
public class CharCountParam extends Applet{
String uname="", msg; int length;
public void init(){
uname = getParameter("Username");
length = uname.length();
uname = "Hello " + uname;
msg = "Length = " + length; }
public void paint(Graphics g){
g.drawString(uname,50,50);
g.drawString(msg, 50, 90);
}}
/*
<applet code="CharCountParam" width=200 height=200>
<param name="Username" value="RAHUL">
</applet>*/

package com.aasu.aasutosh_a_12;
import java.awt.event.*;
import javax.swing.*;
public class WCC extends JFrame implements ActionListener{
JTextArea ta;
JButton b1;
WCC(){
super("Word Counter");
ta=new JTextArea();
ta.setBounds(50,50,300,200);
b1=new JButton("Word");
b1.setBounds(50,300,100,30);
b1.addActionListener(this);
add(b1);add(ta); setSize(400,400);
setLayout(null); setVisible(true);}
public void actionPerformed(ActionEvent e){
String text=ta.getText();
if(e.getSource()==b1){
String words[]=text.split("\\s");
JOptionPane.showMessageDialog(this,"Total words:
"+words.length);}}
public static void main(String[] args) {
new WCC(); }}
package com.aasu.aasutosh_a_12;
import java.awt.event.*;
import javax.swing.*;
public class mouseadpater extends MouseAdapter{
JFrame frame;
JButton btn;
mouseadpater(){
frame = new JFrame("Window");
btn =new JButton("Click me");
frame.setBounds(20, 20, 400, 300);
frame.setLayout(null);
btn.setBounds(30, 30, 80, 40);
btn.addMouseListener(this);
frame.add(btn); btn.setVisible(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
public static void main(String[] args) {
new mouseadpater();}
@Override
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(frame, "Mouse has been
clicked.", "Mouse clicked Event", JOptionPane.INFORMATION_MESSAGE);
}}
9. WAP to illustrate toggle button in swing.
package com.aasu.aasutosh_a_12;
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class JToggleButtonExamp {
public static void main(String args[]){
JFrame frame = new JFrame("Selecting Toggle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToggleButton toggleButton = new JToggleButton("Toggle
Button");
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent){
int state = itemEvent.getStateChange();
if (state == ItemEvent.SELECTED) {
System.out.println("Selected");}
else {
System.out.println("Deselected");}}};
toggleButton.addItemListener(itemListener);
frame.add(toggleButton, BorderLayout.NORTH);
frame.setSize(300, 125);
frame.setVisible(true);
}}

10. Write GUI program using swing and event handling: to show the check boxes, to show
radio buttons.
package com.aasu.aasutosh_a_12;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class checkboxWithEvent {
public static JCheckBox checkbox1 = new JCheckBox("Anil");
public static JCheckBox checkbox2 = new JCheckBox("Sita");
public static JCheckBox checkbox3 = new JCheckBox("Samyog");
public static JCheckBox checkbox4 = new JCheckBox("Sitaram");
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Checkbox with event listener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JLabel msg = new JLabel("", JLabel.CENTER);
panel1.setBorder(BorderFactory.createTitledBorder("Name"));
panel2.setBorder(BorderFactory.createTitledBorder("Output"));
panel1.add(checkbox1);
panel1.add(checkbox2);
panel1.add(checkbox3);
panel1.add(checkbox4);
panel2.add(msg);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == 1) {
msg.setText("Anil is selected");
} else {
msg.setText("Anil is unselected");}}});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == 1) {
msg.setText("Sita is selected");
} else {
msg.setText("Sita is unselected");}}});
checkbox3.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == 1) {
msg.setText("Samyog is selected");
} else {
msg.setText("Samyog is unselected");
}}});
checkbox4.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == 1) {
msg.setText("Sitaram is selected");
} else {
msg.setText("Sitaram is unselected");
}}});
frame.setLayout(new GridLayout(2, 1));
frame.add(panel1);
frame.add(panel2);
frame.pack();
frame.setVisible(true);}}

package com.aasu.aasutosh_a_12;
import javax.swing.*;
import java.awt.event.*;
class radiowithevent extends JFrame implements ActionListener{
JRadioButton rb1,rb2; JButton b;
radiowithevent(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2); b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300); setLayout(null);
setVisible(true); }
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female."); }}
public static void main(String args[]){
new radiowithevent(); }}

11. Design a GUI that contains: tabbed panes using swing, list using swing.
package com.bish.bim;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class tabbedpane {
public static void main(String[] args) {
createWindow();}
private static void createWindow() {
JFrame frame = new JFrame("tabbed Pane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);}
private static void createUI(final JFrame frame){
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel1 = new JPanel(false);
JLabel filler = new JLabel("Tab 1");
filler.setHorizontalAlignment(JLabel.CENTER);
panel1.setLayout(new GridLayout(1, 1));
panel1.add(filler);
tabbedPane.addTab("Tab 1", null, panel1,"Tab 1 tooltip");
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JPanel panel2 = new JPanel(false);
JLabel filler2 = new JLabel("Tab 2");
filler2.setHorizontalAlignment(JLabel.CENTER);
panel2.setLayout(new GridLayout(1, 1));
panel2.add(filler2);
tabbedPane.addTab("Tab 2", null, panel2,"Tab 2 tooltip");
tabbedPane.setMnemonicAt(0, KeyEvent.VK_2);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
}}

package com.aasu.aasutosh_a_12;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class listbyswing extends JFrame{
static JFrame f; static JList b;
public static void main(String[] args){
f = new JFrame("Frame");
listbyswing s=new listbyswing();
JPanel p =new JPanel();
JLabel l= new JLabel("select the day of the week");
String week[]= { "Monday","Tuesday","Wednesday",

"Thursday","Friday","Saturday","Sunday"};
b= new JList(week);
b.setSelectedIndex(2);
p.add(b); f.add(p);
f.setSize(400,400);
f.show();}}

12. Create a GUI using swing to demonstrate: combo box, table.


package com.aasu.aasutosh_a_12;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class jcombobox extends JFrame implements ItemListener {
static JFrame f;
static JLabel l, l1;
static JComboBox c1;
public static void main(String[] args){
f = new JFrame("frame");
solve s = new solve();
f.setLayout(new FlowLayout());
String s1[] = { "Jalpaiguri", "Mumbai", "Noida", "Kolkata",
"New Delhi" };
c1 = new JComboBox(s1);
c1.addItemListener(s);
l = new JLabel("select your city ");
l1 = new JLabel("Jalpaiguri selected");
l.setForeground(Color.red);
l1.setForeground(Color.blue);
JPanel p = new JPanel();
p.add(l); p.add(c1);
p.add(l1); f.add(p);
f.setSize(400, 300);
f.show();}
public void itemStateChanged(ItemEvent e){
if (e.getSource() == c1) {
l1.setText(c1.getSelectedItem() + " selected");}}}

package com.aasu.aasutosh_a_12;
import javax.swing.*;
public class table {
JFrame f;
table(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp); f.setSize(300,400);
f.setVisible(true);}
public static void main(String[] args) {
new table(); }}

13. WAP in Java to read and display all the data stored in a table of some database using
JDBC.
import java.sql.*;
public class Q14{
String url="jdbc:mysql://localhost:3306/student";
String usr="root";
String password="";
static Connection conn;
static Statement st;
public Q14(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,usr,password);
}catch(ClassNotFoundException | SQLException e)
{e.printStackTrace();}}
public static void main(String args[])
{
Q14 obj = new Q14();
String query="SELECT * FROM students;";
try{
st=conn.createStatement();
ResultSet rs=st.executeQuery(query);
while(rs.next()){
System.out.println("ID: "+rs.getInt("id")+"
Name: "+rs.getString("name")+" Roll: "+rs.getInt("rollno")+" Address:
"+rs.getString("address")+" Faculty: "+rs.getString("faculty"));}

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

14. Write a program using JDBC to insert a row into a table of some database.
import java.sql.*;
public class Q15{
String url="jdbc:mysql://localhost:3306/student";
String usr="root";
String password="";
static Connection conn;
static Statement st;
public Q15(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,usr,password);
}catch(ClassNotFoundException | SQLException e){
e.printStackTrace();}}
public static void main(String args[]){
Q15 obj = new Q15();
String query="insert into students values
(15,'BishnuBohara',77,'Kalopul','BIM');";
try{
st=conn.createStatement();
int rs=st.executeUpdate(query);
if(rs>0){

System.out.println("Insertion Successful");}}catch(SQLException e){

e.printStackTrace();}}}
15. Write a java program that allows a user to insert values to a table of particular database
(Suppose database is in MySql server ). The program should take the values to insert from
console.
import java.sql.*;
import java.util.Scanner;
public class Q16{
String url="jdbc:mysql://localhost:3306/student";
String usr="root"; String password="";
static Connection conn;
static Statement st;
static String name="BishnuBohara";
static String address="Kalopul";
static String faculty="BIM";
public Q16(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,usr,password);
}catch(ClassNotFoundException | SQLException e){
e.printStackTrace();}}
public static void main(String args[]){
Q16 obj = new Q16();
Scanner sc=new Scanner(System.in);
System.out.println("Enter ID: ");
int id= sc.nextInt();
System.out.println("Enter Roll: ");
int roll= sc.nextInt();
System.out.println("Enter Name: ");
name= sc.nextLine();
System.out.println("Enter Address: ");
address= sc.nextLine();
System.out.println("Enter Faculty: ");
faculty= sc.nextLine();
String query="insert into students values
('"+id+"','"+name+"','"+roll+"','"+address+"','"+faculty+"');";
try{
st=conn.createStatement();
int rs=st.executeUpdate(query);
if(rs>0){
System.out.println("Insertion Successful");}}
catch(SQLException e){
e.printStackTrace();}}}

16. WAP using JDBC to display the records from a table of given database (Suppose database
is in MySql server ). Assume the following table : result(roll_no , course_name
,marks_obtained). The program should read the roll number value from console and
display the corresponding record.
import java.sql.*;
import java.util.Scanner;
public class Q17{
String url="jdbc:mysql://localhost:3306/student";
String usr="root"; String password="";
static Connection conn; static Statement st;
public Q17(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,usr,password);
}catch(ClassNotFoundException | SQLException e){
e.printStackTrace();}}
public static void main(String args[]){
Q17 obj = new Q17();
Scanner sc=new Scanner(System.in);
System.out.println("Enter Roll: ");
int id= sc.nextInt();
String query="SELECT * FROM result where roll_no="+id;
try{
st=conn.createStatement();
ResultSet rs=st.executeQuery(query);
while(rs.next()){
System.out.println("Roll:
"+rs.getInt("roll_no")+" Course: "+rs.getString("course_name")+"
Marks: "+rs.getFloat("marks_obtained"));}
}catch(SQLException e){
e.printStackTrace(); }}}

17. WAP using JDBC to: insert a record into table using PreparedStatement, retrieve and
display the records of table using PreparedStatement, delete a record of a table using
PreparedStatement, that update the record of table using PreparedStatement.
import java.sql.*;
public class Q18{
String url="jdbc:mysql://localhost:3306/student";
String usr="root";
String password="";
static Connection conn;
static PreparedStatement st;
public Q18(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,usr,password);}
catch(ClassNotFoundException | SQLException e){
e.printStackTrace();}}
public static void main(String args[]){
Q18 obj = new Q18();
String query1="insert into students values (?,?,?,?,?);";
String query2="select * from students where id=?";
String query3="delete from students where id=?";
String query4="update students set name=? where id=?";
try{
st=conn.prepareStatement(query1);
st.setInt(1, 58);
st.setString(2, "BishnuBohara");
st.setInt(3, 101);
st.setString(4, "Kalopul");
st.setString(5, "BIM");
int res=st.executeUpdate();
if(res>0){
System.out.println("Insertion Successful!");}
st=conn.prepareStatement(query2);
st.setInt(1, 3);
ResultSet rs=st.executeQuery();
while(rs.next()){
System.out.println("ID: "+rs.getInt("id")+"
Name: "+rs.getString("name")+" Roll: "+rs.getInt("rollno")+" Address:
"+rs.getString("address")+" Faculty: "+rs.getString("faculty"));
}
st=conn.prepareStatement(query3);
st.setInt(1, 58);
int result=st.executeUpdate();
if(result>0){
System.out.println("Deletion Successful!");}
st=conn.prepareStatement(query4);
st.setString(1,"BishnuKumar Bohara");
st.setInt(2,1);
int resultt=st.executeUpdate();
if(resultt>0)
{
System.out.println("Updation Successful!"); }
}catch(SQLException e) {
e.printStackTrace();}}}
18. Write a java program using PreparedStatement that allows a user to insert values to a
table of particular database (Suppose database is in MySql server). The program should
take the values to insert from console as long as user want to add new record.
import java.sql.*;
import java.util.Scanner;
public class Q19{
String url="jdbc:mysql://localhost:3306/student";
String usr="root"; String password="";
static Connection conn; static PreparedStatement st;
public Q19(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,usr,password);
}catch(ClassNotFoundException | SQLException e) {
e.printStackTrace();}}
public static void main(String args[]){
Q19 obj = new Q19();
String query1="insert into students values (?,?,?,?,?);";
Scanner sc=new Scanner(System.in);
String name="Manoj";
String address="Kalopul";
String faculty="BIM"; String cont="y";
int id=1; int roll=43;
while(cont.equals("y") || cont.equals("Y")){
System.out.println("Enter ID: ");
id= sc.nextInt();
System.out.println("Enter Roll: ");
roll= sc.nextInt();
System.out.println("Enter Name: ");
name= sc.nextLine();
System.out.println("Enter Address: ");
address= sc.nextLine();
System.out.println("Enter Faculty: ");
faculty= sc.nextLine();
System.out.println("Do You Want To Continue? (y/n)");
cont=sc.nextLine();}
try{
st=conn.prepareStatement(query1);
st.setInt(1, id);
st.setString(2, name);
st.setInt(3, roll);
st.setString(4, address);
st.setString(5, faculty);
int res=st.executeUpdate();
if(res>0){
System.out.println("Insertion Successful!");
}}catch(SQLException e){
e.printStackTrace();}}}

19. WAP using PreparedStatement to display the records from a table of given database
(Suppose database is in MySql server ). Assume the following table : salary(emp_id ,
emp_name ,emp_salary) The program should read the employee id value from console
and display the corresponding record.
import java.sql.*;
import java.util.Scanner;
public class Q20{
String url="jdbc:mysql://localhost:3306/student";
String usr="root"; String password="";
static Connection conn; static PreparedStatement st;
public Q20(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,usr,password);
}catch(ClassNotFoundException | SQLException e) {
e.printStackTrace();}}
public static void main(String args[]){
Q20 obj = new Q20();
String query1="insert into salary values (?,?,?);";
String query2="select * from salary where emp_id=?";
Scanner sc=new Scanner(System.in);
String name="BIM"; Float salary=1500f;
int id=1;
System.out.println("Enter Emp Name: ");
name= sc.nextLine();
System.out.println("Enter Emp ID: ");
id= sc.nextInt();
System.out.println("Enter Emp Salary: ");
salary= sc.nextFloat();
try{
st=conn.prepareStatement(query1);
st.setInt(1, id);
st.setString(2, name);
st.setFloat(3, salary);
int res=st.executeUpdate();
if(res>0) {
System.out.println("Insertion Successful!"); }
st=conn.prepareStatement(query2);
st.setInt(1, id);
ResultSet rs=st.executeQuery();
rs.next();
System.out.println("ID:
"+rs.getInt("emp_id")+" Name: "+rs.getString("emp_name")+" Salary:
"+rs.getFloat("emp_salary"));
}catch(SQLException e) {
e.printStackTrace(); }}}
20. Develop a CRUD application using swing and JDBC. Your UI must contain text field, radio
button and combo box (use other components as required). [source code can be printed for
this task]
dbConnector.java
import java.sql.*;
public class dbConnector{
String url="jdbc:mysql://localhost:3306/student";
String user="root";
String password="";
static Connection conn;
Statement statement;
public dbConnector(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,user,password);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException se){
se.printStackTrace();}}
public int iud(String query){
try{
statement=conn.createStatement();
return statement.executeUpdate(query);
}catch(SQLException se){
se.printStackTrace();}
return -1; }
public ResultSet select(String query){
try{
statement=conn.createStatement();
return statement.executeQuery(query);
}catch(SQLException se) {
se.printStackTrace();}
return null; }}

MainProgram.java

import javax.swing.*;
import java.awt.event.*;
public class MainProgram extends JFrame implements ActionListener{
JLabel lblStdId,lblName,lblAddress,lblRollNo,lblFaculty;
JTextField txtStdId, txtName, txtAddress, txtRollNo;
JComboBox cmbFaculty;
JButton btnSubmit, btnClear;
static dbConnector dbConn;
public MainProgram(){
dbConn=new dbConnector();
initializeGUI();}
public void clearFields(){
this.txtStdId.setText("");
this.txtName.setText("");
this.txtAddress.setText("");
this.txtRollNo.setText("");}
public void initializeGUI(){
this.setTitle("Student Record Program");
this.setSize(600,400);
this.setLayout(null);
lblStdId=new JLabel("Student ID: ");
lblStdId.setBounds(10,10,100,25);
lblName=new JLabel("Name: ");
lblName.setBounds(10,45,100,25);
lblAddress=new JLabel("Address: ");
lblAddress.setBounds(10,80,100,25);
lblRollNo=new JLabel("Roll No: ");
lblRollNo.setBounds(10,115,100,25);
lblFaculty=new JLabel("Faculty: ");
lblFaculty.setBounds(10,150,100,25);
txtStdId=new JTextField();
txtStdId.setBounds(120,10,100,25);
txtName=new JTextField();
txtName.setBounds(120,45,100,25);
txtAddress=new JTextField();
txtAddress.setBounds(120,80,100,25);
txtRollNo=new JTextField();
txtRollNo.setBounds(120,115,100,25);
cmbFaculty=new JComboBox();
cmbFaculty.addItem("BBA");
cmbFaculty.addItem("BIM");
cmbFaculty.addItem("BBS");
cmbFaculty.setBounds(120,150,150,25);
btnSubmit=new JButton("Submit");
btnSubmit.setBounds(10,190,100,25);
btnSubmit.addActionListener(this);
btnSubmit.setActionCommand("submit");
btnClear=new JButton("Clear");
btnClear.addActionListener(this);
btnClear.setActionCommand("clear");
btnClear.setBounds(150,190,100,25);
this.add(lblStdId);
this.add(lblName);
this.add(lblAddress);
this.add(lblRollNo);
this.add(lblFaculty);
this.add(txtStdId);
this.add(txtName);
this.add(txtAddress);
this.add(txtRollNo);
this.add(cmbFaculty);
this.add(btnSubmit);
this.add(btnClear);

this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
public static void main(String args[]){
new MainProgram();}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("clear")){
this.clearFields();}
if(ae.getActionCommand().equals("submit")){
StudentJDBC std=new
StudentJDBC(Integer.parseInt(txtStdId.getText()),txtName.getText(),
txtAddress.getText(),Integer.parseInt(txtRollNo.getText()),cmbFacult
y.getSelectedItem().toString());
int stdId=std.getStudentId();
String stdName=std.getName();
String stdFaculty=std.getFaculty();
String stdAddress=std.getAddress();
int stdRollNo=std.getRollNo();
String query="INSERT INTO students
VALUES("+stdId+","+stdName+","+stdRollNo+","+stdAddress+"."+stdFacul
ty+")";
int result=dbConn.iud(query);
if(result>0) {
System.out.println("Record Insertion
Successful!");
clearFields();}
else{
System.out.println("Record Insertion Failed!");
}}}}

StudentJDBC.java

public class StudentJDBC{


private int studentId;
private String name;
private String address;
private int rollNo;
private String faculty;
public StudentJDBC(int studentId, String name,String address, int
rollNo, String faculty) {
this.studentId=studentId;
this.name=name;
this.address=address;
this.rollNo=rollNo;
this.faculty=faculty; }
public int getStudentId(){
return studentId; }
public String getName(){
return name;}
public String getAddress(){
return address; }
public int getRollNo(){
return rollNo;}
public String getFaculty(){
return faculty; }}

21. Create a DTD file with some element and attribute. Now create an XML file and validate
the XML against the DTD.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE customer [
<!ELEMENT customer (firstname, lastname, companyname, email, message)>
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT companyname (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ELEMENT message (#PCDATA)>]>
<customer>
<firstname>John</firstname>
<lastname>Doe</lastname>
<companyname>Section</companyname>
<email>johndoe@section.io</email>
<message>Welcome message</message>
</customer>
22. Create a XSD file with some element and attribute. Now create an XML file and validate
the XML against the XSD.

23. Write a servlet that takes a number from a html form and displays the multiplication table
of that number. (Also write the contents of html and web.xml files l)
index.html
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
</head>
<body>
<form method="post" action="multiplicationtable">
<label>Number: </label>
<input type="text" name="num"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
MultiplicationTable.java
package com.aasu.aasutosh_a_12;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MultiplicationTable extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int num=Integer.parseInt(request.getParameter("num"));
for(int i=1;i<=10;i++){
out.println(num+" x "+i+" = "+(num*i)+"<br>");}}}

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>MultiplicationTable</servlet-name>
<servlet-
class>com.mycompany.q24.MultiplicationTable</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MultiplicationTable</servlet-name>
<url-pattern>/multiplicationtable</url-pattern>
</servlet-mapping>
</web-app>
24. WAP in JSP to demonstrate: Page directive, Include directive.
a.

<html> <body>

<%@ page import="java.util.Date" %>

Today is: <%= new Date() %>


</body> </html>
b.
<html> <body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body> </html>

25. WAP: to demonstrate JSP declaration, JSP expression and JSP scriptlet, to print “BIM
fifth Rocks” 10 times using JSP, that takes principal, rate and time values and displays the
simple interest value using JSP.
Expression tag: This tag contains a scripting language expression that is converted to a String
and inserted where the expression appears in the JSP file. Because the value of an expression
is converted to a String, you can use an expression within text in a JSP file. You cannot use a
semicolon to end an expression.
Declaration tag: This declares one or more variables or methods for use later in the JSP source
file. It must contain at least one complete statement. You can declare any number of variables
or methods within one declaration tag, but you have to separate them by semicolons. The
declaration must be valid in the scripting language used in the JSP file.You can add method to
the declaration part.
Scriptlet tag: You can declare variables in the script-let and can do any processing. All the
Scriptlet go to the inside service() method of the convert servlet.
a.
<html>
<body>
<%!
int factorial(int n)
{
if (n == 0)
return 1;
return n*factorial(n-1);
}
%>
<%= "Factorial of 5 is:"+factorial(5) %>
</body>
</html>
b.
<html>
<body>
<%? String str=”BIM fifth Rocks”;%>
<% for(int i=1; i<=10; i++){%>
<%= str%><%}%>
</body></html>
c.
<html>
<body>
<%!
int SI(double P, double T, double R)
{
if (P==0 || T==0 || R==0 )
return 0;
return P*T*R;
}
%>
<%= "Simple Interest is:"+SI(50,1,.5) %>
</body></html>

26. WAP to illustrate the use of <jsp: useBean> <jsp: setProperty> and <jsp: getProperty>
(Also write the contents of Bean class)

index.html

<form action="process.jsp" method="post">


Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form>

User.java
package org.sssit;
public class User {
private String name,password,email; }

process.jsp

<jsp:useBean id="u" class="org.sssit.User" scope="session"></jsp:use


Bean>
<jsp:setProperty property="*" name="u"/>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
<a href="second.jsp">Visit Page</a>

second.jsp

<jsp:useBean id="u" class="org.sssit.User" scope="session"></jsp:use


Bean>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>

27. Write a servlet program that takes values from a signup form and store them in a database
table. . (Also write the contents of html and web.xml files. Show the contents of database
table after inserting the values)
index.html
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
</head>
<body>
<form method="post" action="dbservlet">
<label>ID: </label>
<input type="text" name="id"><br>
<label>Name: </label>
<input type="text" name="name"><br>
<label>Roll No.: </label>
<input type="text" name="roll"><br>
<label>Address: </label>
<input type="text" name="address"><br>
<select name="faculty">
<option value="BIM">BIM</option>
<option value="BBA">BBA</option>
<option value="BBM">BBM</option>
</select><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>DBServlet</servlet-name>
<servlet-class>com.mycompany.q24.DBServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DBServlet</servlet-name>
<url-pattern>/dbservlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30
</session-timeout>
</session-config>
</web-app>

DBServlet.java
package com.mycompany.q24;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class DBServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int id=Integer.parseInt(request.getParameter("id"));
int roll=Integer.parseInt(request.getParameter("roll"));
String name=request.getParameter("name");
String address=request.getParameter("address");
String faculty=request.getParameter("faculty");
dbConnector dbconn=new dbConnector();
String query="insert into students values
("+id+",'"+name+"','"+roll+"','"+address+"','"+faculty+"');";
if(dbconn.iud(query)>0)
{
String query2="select * from students where id="+id;
ResultSet rs=dbconn.select(query2);
out.println("<table
border='1'><thead><tr><th>ID</th><th>Name</th><th>Roll</th><th>Addre
ss</th><th>Faculty</th></tr></thead><tbody>");
try {
while(rs.next())
{

out.print("<tr><td>"+rs.getInt("id")+"</td><td>"+rs.getString("name"
)+"</td><td>"+rs.getInt("rollno")+"</td><td>"+rs.getString("address"
)+"</td><td>"+rs.getString("faculty")+"</td></tr>");
}
out.print("</tbody></table>");
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}

class dbConnector
{
String url="jdbc:mysql://localhost:3306/student";
String user="root";
String password="";
static Connection conn;
Statement statement;
public dbConnector()
{
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,user,password);
}catch(ClassNotFoundException | SQLException e){
e.printStackTrace();
}
}
public int iud(String query){
try{
statement=conn.createStatement();
return statement.executeUpdate(query);
}catch(SQLException se){
se.printStackTrace();
}
return -1;
}
public ResultSet select(String query){
try{
statement=conn.createStatement();
return statement.executeQuery(query);
}catch(SQLException se)
{
se.printStackTrace();
}
return null;
}}

28. WAP to demonstrate include and forward methods in servlet.


index.html
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
</head>
<body>
<a href="includeservlet">Click Here for Include</a><br>
<a href="forwardservlet">Click Here for Forward</a>
</body>
</html>

ForwardServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ForwardServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<h1>Hello Manoj</h1>");
RequestDispatcher rd=
request.getRequestDispatcher("test.html");
rd.forward(request,response);
}
}

test.html
<html>
<body>
<h3>This header is from test.html</h3>
</body>
</html>
IncludeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IncludeServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<h1>Hello Manoj</h1>");
RequestDispatcher rd=
request.getRequestDispatcher("test.html");
rd.include(request,response);
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>ForwardServlet</servlet-name>
<servlet-class>ForwardServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>IncludeServlet</servlet-name>
<servlet-class>IncludeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ForwardServlet</servlet-name>
<url-pattern>/forwardservlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>IncludeServlet</servlet-name>
<url-pattern>/includeservlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

29. Write a program to demonstrate session creation, setting and retrieving values form
session and destruction of session in servlet. (Write the contents of html and web.xml files
SessionServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
HttpSession session=request.getSession();
session.setAttribute("name","BishnuBohara");
out.println("Your Name is:
"+(String)session.getAttribute("name"));
session.invalidate();
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>SessionServlet</servlet-name>
<servlet-class>SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionServlet</servlet-name>
<url-pattern>/sessionservlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
index.html
<!DOCTYPE html>
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<a href="sessionservlet">Click Here to find your name.</a>
</body>
</html>

You might also like