Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

myfile Advanced Java

This document is a practical file for Advanced Java Programming submitted by Nikhil Kumar Vats to Mrs. Ayushi Aggarwal at Hindu College of Engineering, Sonepat. It includes a detailed index of various Java programs covering concepts such as classes, inheritance, interfaces, user-defined packages, and GUI components using AWT and Swing. Each program is accompanied by its code and output, demonstrating practical applications of Java programming techniques.

Uploaded by

mayankggn4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

myfile Advanced Java

This document is a practical file for Advanced Java Programming submitted by Nikhil Kumar Vats to Mrs. Ayushi Aggarwal at Hindu College of Engineering, Sonepat. It includes a detailed index of various Java programs covering concepts such as classes, inheritance, interfaces, user-defined packages, and GUI components using AWT and Swing. Each program is accompanied by its code and output, demonstrating practical applications of Java programming techniques.

Uploaded by

mayankggn4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

HINDU COLLEGE OF ENGINEERING

SONEPAT

PRACTICAL FILE
Advanced Java Programming

Submitted To: Submitted By:


Mrs. Ayushi Aggarwal Nikhil Kumar Vats
Assistant Professor (CSE) CSE 6th Semester
Roll no: 18011001013

1|Page
INDEX

S.NO PROGRAM DATE PAGE NO.


1. Write a program to show the 15-02-21 4
concept of classes and objects.
2. Write a program to create default & 15-02-21 5
parametrized (constructor
overloading).
3. Write a program to show the 23-02-21 8
concept of inheritance with method
overriding.
4. Write a program to implement and 23-02-21 10
create interface (show multiple
behaviour).
5. Write a program to create user 02-03-21 13
defined package in java.
6. Write a program to get the input 02-03-21 15
from the user using util and io
package.
7. Write a program to create and 08-03-21 17
implement Applet.
8. Write a program to create login 08-03-21 19
form using awt controls.
9. Write a program to create Label, 17-03-21 21
TextField, Button, CheckBox and
Radio button using swing.
10. Write a program to create Table and 17-03-21 24
add ScrollPane in swings.
11. Write a program to create 24-03-21 26
TabbedPane in swing.
12. Write a program to implement trees 24-03-21 28
using swing.
13. Write a program to create a list 07-04-21 30
using swing in java.
14. Write a program to extract data 07-04-21 32
from the database using JDBC.

2|Page
15. Write a program to insert record 14-04-21 34
into the database using prepared
statement.
16. Write a program to extract 21-04-21 36
information about database and
table using metadata.
17. Write a program to use built in 21-04-21 38
beans using BDK.
18. Write a program to create and load 28-04-21 46
user defined java beans in BDK.
19. Write a program to create simple 28-04-21 48
servlet using generic class.
20. Write a program to create and 05-05-21 51
handle HTTP request and response.
21. Write a program to show JSP 12-05-21 54
expression and declaration in
scriplets.
22. Write a program to print welcome 19-05-21 56
message in JSP using implicit
objects.

3|Page
PROGRAM 1
Write a program to show the concept of classes and
objects.

public class Area

int a = 4;

int b = 8;

int c = a*b;

int d = 1/2*(a*b);

int e = a*a;

public static void main(String[]args)

Area ob = new Area();

System.out.println("Area of rectangle is:"+ob.c);

System.out.println("Area of triangle is:"+ob.d);

System.out.println("Area of square is:"+ob.e);

OUTPUT:

4|Page
PROGRAM 2
Write a program to create default and parametrized
constructor.
public class Timetable

String AI;

String AJ;

String CS;

String CD;

String DM;

Timetable()

AI = "Mr. Ashu Bansal";

AJ = "Mrs. Aayushi Aggarwal";

CS = "Mr. Ankit Tyagi";

CD = "Mrs. Preeti Aneja";

DM = "Mr. Puneet Sharma";

Timetable(String a,String b,String c,String d,String e)

AI = a;

AJ = b;

CS = c;

CD = d;

DM = e;

public static void main(String[] args)

5|Page
{

System.out.println("Teachers of different subjects are:");

Timetable o = new Timetable();

System.out.println("AI: "+o.AI);

System.out.println("AJ: "+o.AJ);

System.out.println("CS: "+o.CS);

System.out.println("CD: "+o.CD);

System.out.println("DM: "+o.DM);

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

System.out.println("Time table of Monday is:");

Timetable ob = new Timetable("Communication Skills","Advanced Java","Disaster


Management","Artificial Intelligence","Advanced Java lab");

System.out.println("First period is: "+ob.CS);

System.out.println("Second period is: "+ob.AJ);

System.out.println("Third period is: "+ob.DM);

System.out.println("Fourth period is: "+ob.AI);

System.out.println("Fifth period is: "+ob.AJ);

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

System.out.println("Time table of Tuesday is: ");

Timetable tue = new Timetable("Compiler Design","Disaster Management","Artificial


Intelligence","Communication Skills","Compiler Design lab");

System.out.println("First period is: "+tue.CD);

System.out.println("Second period is: "+tue.DM);

System.out.println("Third period is: "+tue.AI);

System.out.println("Fourth period is: "+tue.CS);

System.out.println("Fifth period is: "+tue.CD);

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

6|Page
}

OUTPUT:

7|Page
PROGRAM 3
Write a program to show the concept of inheritance
with method overriding.
class Vivo

void print()

System.out.println("Models of Vivo are:");

System.out.println("1. Vivo Y20");

System.out.println("2. Vivo Y30");

System.out.println("3. Vivo Y15");

System.out.println("4. Vivo Y12");

System.out.println("5. Vivo X50 Pro, etc.");

class VivoY30 extends Vivo

void print()

System.out.println("Features of Vivo Y30 are:");

System.out.println("CPU : Octa-core(4*2.35 GHz Cortex-A53 & 4*1.8 GHz Cortex-A53");

System.out.println("GPU : PowerVR GE8320");

System.out.println("Camera : 13MP, 8MP, 2MP, 2MP");

System.out.println("Battery : Li-Po 5000mAh, non-removable");

System.out.println("Browser : HTML 5");

public static void main(String[]args)

Vivo h = new Vivo();

8|Page
Vivo h1 = new VivoY30();

h.print();

h1.print();

OUTPUT:

9|Page
PROGRAM 4
Write a program to implement and create interface
(show multiple inheritance).
interface F1

default void show()

System.out.println("Name: Chotta Bheem");

System.out.println("Department: CSE");

System.out.println("College: HCE");

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

interface F2

default void show()

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

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

System.out.println("Department: ECE");

System.out.println("College: HCE");

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

interface F3

default void show()

10 | P a g e
System.out.println("\n");

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

System.out.println("Department: CSE");

System.out.println("College: HCE");

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

interface F4

default void show()

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

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

System.out.println("Department: CE");

System.out.println("College: HCE");

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

class Dost implements F1,F2,F3,F4

public void show()

F1.super.show();

F2.super.show();

F3.super.show();

F4.super.show();

public static void main(String args[])

11 | P a g e
{

Dost d = new Dost();

d.show();

OUTPUT:

12 | P a g e
PROGRAM 5
Write a program to create user-defined package in
java.
Package:

package Laptop;

public class Dabbu

public void show()

System.out.println("Some features of Dabbu:");

System.out.println("Windows edition: Windows 10");

System.out.println("Processor: intel(R) Core(TM) i5-10210U CPU@ 1.60GHz 2.11GHz");

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

System.out.println("Installed memory(RAM): 8.00 GB(7.85 GB usable)");

System.out.println("System type: 64-bit Operating System,x64-based processor");

Import of package

import Laptop.*;

class L1

public static void main(String args[])

Dabbu l = new Dabbu();

l.show();

13 | P a g e
OUTPUT:

14 | P a g e
PROGRAM 6
Write a program to get the input from the users using
util or io package.
import java.util.*;

import java.io.*;

class use_Of_util {

String str;

Scanner scn = new Scanner(System.in);

void input() {

System.out.println("Enter your message: ");

str = scn.nextLine();

void print() {

System.out.println(str);

class use_Of_io {

String str;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

void input() {

System.out.println("Enter your message: ");

try {

str = br.readLine();

} catch (IOException e) {

e.printStackTrace();

15 | P a g e
}

void print() {

System.out.println(str);

public class psix {

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

use_Of_util obj1 = new use_Of_util();

use_Of_io obj2 = new use_Of_io();

obj1.input();

obj1.print();

obj2.input();

obj2.print();

OUTPUT:

16 | P a g e
PROGRAM 7
Write a program to create and implement java.
import java.awt.*; // Abstract Window Toolkit

import java.applet.*; // Applet

/*<applet code="pseven.class" width = 400 height = 400>

</applet> */

public class pseven extends Applet {

public void init() {

Label userName = new Label();

userName.setText("Username");

TextField userNameText = new TextField(10);

Label password = new Label();

password.setText("Password");

TextField passwordText = new TextField(10);

add(userName);

add(userNameText);

add(password);

add(passwordText);

public void paint(Graphics g) {

update(g);

17 | P a g e
OUTPUT:

18 | P a g e
PROGRAM 8
Write a program to create login form using Awt
controls.
import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

/*<applet code="Cute.class" height=300 width=300></applet> */

public class Cute extends Applet implements ActionListener{

TextField t1,t2;

Label l1,l2,l3;

Button b1;

public void init(){

l1 = new Label("Please enter your name:");

t1 = new TextField(20);

add(l1);

add(t1);

l2 = new Label("Please enter your password:");

t2 = new TextField(20);

add(l2);

add(t2);

b1= new Button("Sign in");

add(b1);

b1.addActionListener(this);

l3 = new Label("Please login here!");

add(l3);

19 | P a g e
}

public void actionPerformed(ActionEvent ae){

if(ae.getSource() == b1 && t1.getText().equals("admin") && t2.getText().equals("admin")){

l3.setText("Login Success");

else{

l3.setText("Login Fail");

OUTPUT:

20 | P a g e
PROGRAM 9
Write a program to create Label, TextField, Button,
CheckBox, and RadioButton using swings.
import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class pnine {

public static void main(String[] args) {

swingDemo obj = new swingDemo();

class swingDemo extends JFrame implements ActionListener {

JTextField t1;

JButton b1;

JRadioButton r1, r2;

JCheckBox c1, c2;

JLabel l;

public swingDemo() {

t1 = new JTextField(15);

l = new JLabel("Greeting");

r1 = new JRadioButton("Male");

r2 = new JRadioButton("Female");

c1 = new JCheckBox("Dancer");

c2 = new JCheckBox("Singer");

b1 = new JButton("Submit");

ButtonGroup bg = new ButtonGroup();

bg.add(r1);

21 | P a g e
bg.add(r2);

add(t1);

add(r1);

add(r2);

add(c1);

add(c2);

add(b1);

add(l);

b1.addActionListener(this);

setLayout(new FlowLayout()); // Center the content layout

setVisible(true);

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent e) {

String name = t1.getText();

if (r1.isSelected()) name = "Mr." + name;

else name = "Ms. " + name;

if(c1.isSelected()) name += " Dancer";

if(c2.isSelected()) name += " Singer";

l.setText(name);

22 | P a g e
OUTPUT:

23 | P a g e
PROGRAM 10
Write a program to create table and add scrollpane in
swings.
import javax.swing.*;

import javax.swing.table.DefaultTableModel;

import java.awt.*;

public class pten {

public static void main(String[] args) {

TableWithScroll obj = new TableWithScroll();

class TableWithScroll extends JFrame {

JTable t1;

TableWithScroll() {

Object[][] data = {{5, "Bheem", 15}, {10, "Arjun", 21}, {22, "Nakul", 45}, {14, "Nischal", 95}, {13,
"Nikhil", 101}};

String[] columnNames = {"Roll No.", "Names", "Age"};

DefaultTableModel model = new DefaultTableModel(data, columnNames);

t1 = new JTable(model);

JScrollPane scroll = new JScrollPane(t1, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,


ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

add(scroll);

24 | P a g e
setLayout(new FlowLayout());

setVisible(true);

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

OUTPUT:

25 | P a g e
PROGRAM 11
Write a program to create TabbedPane in swings.
import javax.swing.*;

import java.awt.*;

public class peleven {

public static void main(String[] args){

TabbedPane obj = new TabbedPane();

class TabbedPane extends JFrame{

TabbedPane(){

JTabbedPane tp = new JTabbedPane();

JPanel panel1 = new JPanel();

JPanel panel2 = new JPanel();

JPanel panel3 = new JPanel();

panel1.add(new JLabel("This is my First page"));

panel2.add(new JLabel("This is my Second page"));

panel3.add(new JLabel("This is my Third page"));

tp.add("First", panel1);

tp.add("Second", panel2);

tp.add("Third", panel3);

add(tp);

setBounds(50, 50, 200, 200);

setVisible(true);

setSize(400, 400);

26 | P a g e
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

OUTPUT:

27 | P a g e
PROGRAM 12
Write a program to implements trees using swings.
import javax.swing.*;

import java.awt.*;

import javax.swing.tree.*;

public class ptwelve{

public static void main(String[] ags){

TreeExample obj = new TreeExample();

class TreeExample extends JFrame{

TreeExample(){

DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Top");

DefaultMutableTreeNode A = new DefaultMutableTreeNode("A");

DefaultMutableTreeNode B = new DefaultMutableTreeNode("B");

DefaultMutableTreeNode A1 = new DefaultMutableTreeNode("A1");

DefaultMutableTreeNode A2 = new DefaultMutableTreeNode("A2");

DefaultMutableTreeNode B1 = new DefaultMutableTreeNode("B1");

DefaultMutableTreeNode B2 = new DefaultMutableTreeNode("B2");

DefaultMutableTreeNode B3 = new DefaultMutableTreeNode("B3");

A.add(A1);

A.add(A2);

B.add(B1);

28 | P a g e
B.add(B2);

B.add(B3);

rootNode.add(A);

rootNode.add(B);

JTree tree = new JTree(rootNode);

add(tree);

setBounds(50, 50, 200, 200);

// setLayout(new FlowLayout());

setVisible(true);

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

OUTPUT:

29 | P a g e
PROGRAM 13
Write a program to create a list using swings in java.
import javax.swing.*;

import java.awt.*;

import javax.swing.JList;

public class pthirteen {

public static void main(String[] args) {

JListExample obj = new JListExample();

class JListExample extends JFrame {

String[] items = { "item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9",
"item10",

"item11" };

JListExample() {

JList list = new JList(items);

JPanel panel = new JPanel();

panel.add(new JScrollPane(list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,

ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED));

add(panel);

// setLayout(new FlowLayout());

setBounds(50, 50, 600, 700);

setVisible(true);

30 | P a g e
setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

OUTPUT:

31 | P a g e
PROGRAM 14
Write a program to extract data from database using
JDBC.
import java.sql.*;

class MySQLcon{

public static void main(String args[]){

try{

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

Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/worker","root","nikhil3009@");

//here worker is database name, root is username and nikhil3009@ is password

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("select * from worker");

while(rs.next())

System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " +


rs.getInt(4));

con.close();

catch(Exception e){

System.out.println(e);

32 | P a g e
OUTPUT:

33 | P a g e
PROGRAM 15
Write a program to insert record into the database
using prepared statement.
import java.sql.*;

public class MySQLcon1 {

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

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

String uname = "root";

String pass = "nikhil3009@";

String query = "insert into worker values (?, ?, ?, ?)";

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

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

PreparedStatement st = con.prepareStatement(query);

st.setString(1, "Tom");

st.setString(2, "Khanna");

st.setString(3, "CSE");

st.setInt(4, 9500);

int count = st.executeUpdate();

System.out.println(count + " rows affected");

st.close();

con.close();

34 | P a g e
OUTPUT:

35 | P a g e
PROGRAM 16
Write a program to extract information about
database and table using matadata.
import java.sql.*;

class MySQLcon1{

public static void main(String args[]){

try{

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

Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/worker","root","nikhil3009@");

//here worker is database name, root is username and nikhil3009@ is password

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("select * from worker");

ResultSetMetaData rm = rs.getMetaData();

System.out.println("\n Number of Columns = "+rm.getColumnCount());

System.out.println(rm.getTableName(4));

int c = rm.getColumnCount();

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

System.out.println("\n Column name" + i + "=" +rm.getColumnLabel(i));

System.out.println("\n Column size" + i + "=" +rm.getColumnDisplaySize(i));

System.out.println("\n Column Data Type" + i + "=" +rm.getColumnTypeName(i));

while(rs.next())

System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));

con.close();

catch(Exception e){

System.out.println(e);

36 | P a g e
}

OUTPUT:

37 | P a g e
PROGRAM 17
Write a program to use built in beans using BDK

Example:

The easiest way to understand how BeanBox works is to use it. You can construct simple beans
applications without writing any Java code using BeanBox. As a first example, you can build a simple
"Juggling Duke" application in which Duke will start or stop juggling depending on which of two
buttons you push.

The first thing to do is add the Juggler Bean. Starting with an empty BeanBox select the Juggler Bean
from the list of Beans in the Toolbox window.

38 | P a g e
Now, placing the cursor anywhere in the BeanBox will cause a Juggler Bean to be inserted in the
design form. The highlighted box surrounding the Juggler indicates the Juggler is the currently
selected bean.

Next, you'll need to add a start button and a stop button to control the juggler. Each of these Beans is
an instance of the OurButton Bean class.

39 | P a g e
Place an instance of the button in the form.

To change the label on the button, edit the label field in the property sheet to read "start."

The text for the button changes at the same time you type it into the property sheet editor.

The next step is to specify an event to be fired by the button. A corresponding event-handler method
is then selected for the Juggler Bean.

Use the edit menu to select an action event to be fired by the start button. Note that in order for this
to work, the start button must be selected.

40 | P a g e
Once the actionPerformed menu selection is made, BeanBox enters a state where a line emanates
from the start button and follows the mouse as you move it around the window. This indicates that
the button is the selected source for the action event, and that your next mouse press should be over
the target which defines appropriate event-handler methods, in this case the Juggler.

When you drag the line from the start button and release it over the Juggler Bean, a dialog appears
listing applicable event handlers defined by the Juggler Bean.

41 | P a g e
Select the start method as the target for the event, then press OK. You can now press the start
button; Duke should start tossing beans around in a circle over his head like a professional juggler.

You can control Duke's juggling speed by manually setting the propery value labeled animationRate
in the Juggler's property sheet editor. For the appropriate property sheet editor to appear, the
Juggler must be the currently selected Bean within the BeanBox frame.

To complete the example program, you need to add a stop button. Again, from the list of available
beans in the Toolbox menu select OurButton.

42 | P a g e
Drag the button just below the start button, and drop it in place. Make sure the new button is the
currently selected Bean. If it is, the appropriate property editor appears to the right.

Edit the label field of the property sheet to read "start." The button's label reflects your changes as
you type.

43 | P a g e
Hook up the action event from the stop button to the Juggler's stop event-handler method. Make
sure the stop button is the currently selected bean. Select the actionPerformed event from the
Edit/Events menu.

Now drag the event line from the button source to the Juggler Bean target. Press and release the
mouse button with the connection line over the Juggler. You'll now see the dialog of applicable
event-handler methods defined for the Juggler Bean.

44 | P a g e
Select the stop event.

Now you're finished. You should be able to start and stop the juggler by pressing the appropriate
button.

45 | P a g e
PROGRAM – 18
Write a program to create and load user defined java
beans in BDK

• In order to create a javabean we need to follow the following steps:


• Navigate to the C: Drive and open “Beans” folder further navigate to “Demo” and inside
“Demo” go further inside “sunw” and then to “demo” to understand the address easily see
below:

Address: C:\Beans\demo\sunw\demo

• Create a Directory(folder) with the same name that you want to keep of your javabean to
distinguish better.
• Inside this Directory create a .java file of your javabean code and compile it using cmd
prompt and jdk to create .class file within the same directory.
• Now come outside of your javaBean Directory and navigate till below address:
C:\Beans\demo

• Here you have to create a manifest(.mft) file of your javaBean code using cmd prompt.
• Now again navigate outside the demo directory and navigate to jars directory located within
Beans and create .jar file of your javaBean code using cmd prompt.
• Now you are ready to use your JavaBean using the BeanBox.

Source code:
import javax.swing.*;
public class My extends JPanel
{
private String sname="My logo";
JLabel lname;
JTextField tname;
public CSE1()
{
lname=new JLabel(sname);
tname=new JTextField(10);
add(lname);
add(tname);
}
public void setSname(String str)
{
sname=str;
lname.setText(sname);
}

46 | P a g e
public String getSname()
{
return sname;
}
}

Output:

47 | P a g e
PROGRAM – 19
Write a program to create simple servlet using generic
class.

hello.java file:

package com.abhinav;
import java.io.*;
import javax.servlet.*;

public class hello extends GenericServlet{


public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
pwriter.print("<html>");
pwriter.print("<body>");
pwriter.print("<h2>Generic Servlet Example</h2>");
pwriter.print("<p>Hello BeginnersBook Readers!</p>");
pwriter.print("</body>");
pwriter.print("</html>");
}
}

index.html file:

<!DOCTYPE html>
<html>
<body>

<a href="welcome">Click to call Servlet</a>

</body>
</html>

web.xml file:

48 | P a g e
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xm
l/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">

<servlet>
<servlet-name>MyGenericServlet</servlet-name>
<servlet-class>com.abhinav.hello</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>MyGenericServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>

Output:

49 | P a g e
50 | P a g e
PROGRAM – 20
Write a program to create and handle HTTP request
and response.

AddServlet.java file:

package com.abhinav;

import java.io.*;

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

public class AddServlet extends HttpServlet{

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletEx


ception {

int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));

int k = i + j;

PrintWriter out = res.getWriter();


out.println("Hello sum : " + k);
}
}

index.html file:

<!DOCTYPE html>
<html>
<body>

<form action="add">

Enter 1st number : <input type="text" name="num1"><br>


Enter 2nd number : <input type="text" name="num2"><br>
<input type="submit">

</form>

</body>
</html>

51 | P a g e
web.xml file:

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


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xm
l/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">

<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.abhinav.AddServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>

</web-app>

Output:

52 | P a g e
53 | P a g e
PROGRAM – 21
Write a program to show JSP exp and declaration in
scriplets

add.jsp file:

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


pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP</title>
</head>

<body>
<h3>Declaration of JSP</h3>
<%! int count =10; %>
<% out.println("The Number is " +count); %>

<h3>Expression of JSP</h3>
<% out.println("The expression number is "); %>
<% int num1=10; int num2=10; int num3 = 20; %>
<%= num1*num2+num3 %>
</body>

</html>

index.html file:

<!DOCTYPE html>
<html>
<body>

<a href="add.jsp">Click here to run JSP</a>

</body>
</html>

54 | P a g e
Output:

55 | P a g e
PROGRAM – 22
Write a program to print welcome message in JSP
using implicit objects.

add.jsp file:

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


pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="cyan">
<%

out.println("Welcome to Java World ");

%>
</body>
</html>

index.html file:

<!DOCTYPE html>
<html>
<body>

<a href="add.jsp">Click here to run JSP</a>

</body>
</html>

56 | P a g e
Output:

57 | P a g e

You might also like