Lab Work for Computer Students
Lab Work for Computer Students
Contents
1. Setup and Introduction to Applet ...................................................................................................... 2
1.1. Simple Applet & Operation ………................................................................................................. 3
1.2. Draw Shapes ………………................................................................................................................. 6
1.3. Exception Handling ..................................................................................................................... 11
1.4. Multithreading ........................................................................................................................... 12
1.5. File IO .......................................................................................................................................... 16
1.5.1. Read Into & Write From File .............................................................................................. 16
1.5.2. Zip and UnZip File ............................................................................................................... 18
2. User Interface Components with swings ........................................................................................... 20
2.1. GUI tools (Buttons, Labels, Text fields, Dialog box, Tooltips, Menus, etc.) ............................. 20
2.2. Layout Managements ................................................................................................................. 25
2.2.1. Border Layout ..................................................................................................................... 25
2.2.2. Grid Layout ......................................................................................................................... 27
2.2.3. Flow Layout ........................................................................................................................ 29
3. Events Handling ................................................................................................................................ ....32
4. Database Connectivity .................................................................................................................... ..... 34
5. Network Programming ..................................................................................................................... ... 34
5.1. Working with URLs ..................................................................................................................... 34
5.2. TCP sockets ................................................................................................................................. 35
6. Servlet …….......................................................................................................................................... 37
6.1. HTTP Request and Response ...................................................................................................... 37
7. Java Server Pages ............................................................................................................................. ... 38
7.1. JSP Basic ...................................................................................................................................... 38
7.2. Creating and Processing Forms .................................................................................................. 39
7.3. Session Management ................................................................................................................. 42
8. RMI…..................................................................................................................................................... 44
8.1. Creating and Executing RMI Application ................................................................................... 44
1. Setup and Introduction to Applet:
Installation:
Installed NetBeans IDE 8.2
About NetBeans IDE8.2:
NetBeans IDE is a free, open source, integrated development
environment (IDE) that enables you to develop desktop, mobile and web
applications. The IDE supports application development in various
languages, including Java, HTML5, PHP and C++. The IDE provides
integrated support for the complete development cycle, from project
creation through debugging, profiling and deployment. The IDE runs on
Windows, Linux, Mac OS X, and other UNIX-based systems.
The IDE provides comprehensive support for JDK 7 technologies and the
most recent Java enhancements. It is the first IDE that provides support
for JDK 7, Java EE 7, and JavaFX 2. The IDE fully supports Java EE using
the latest standards for Java, XML, Web services, and SQL and fully
supports the GlassFish Server, the reference implementation of Java EE.
Started To Code:
Applet:
An applet is a Java program that can be embedded into a web page. It runs inside the
web browser and works at client side. An applet is embedded in an HTML page using the APPLET
or OBJECT tag and hosted on a web server. Applets are used to make the website more dynamic
and entertaining
Objectives of Lab:
To See how applet looks like
To create simple applet
To create shapes and displaying them
Advantage of Applet
There are many advantages of applet. They are as follows:
import java.awt.*;
import java.applet.*;
Output
Operation Using Applet:
package Applet;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JLabel;
public class AppletOperations extends Applet implements ActionListener{
TextField t1,t2,t3;
Button b1 ,b2;
JLabel l1,l2,l3;
public void init(){ //size and close buttion is not used SetVisiable and setTitle is not
l1 = new JLabel("Num1");
t1 = new TextField(20);
l2 = new JLabel("Num2");
t2 = new TextField(20);
l3 = new JLabel("Result");
t3 = new TextField(20);
b1 = new Button("Add");
b2 = new Button("Subtract");
setLayout(new FlowLayout()); // by default it is used in applet
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
int a = Integer.parseInt(t1.getText());
int b= Integer.parseInt(t2.getText());
int c=0;
if(e.getSource()==b1){
c=a+b;
t3.setText(c+"");
}
else if(e.getSource()==b2){
c=a-b;
t3.setText(c+"");
} }
}
Outputs:
Add
Subtract
import java.util.Random;
class ExceptionExample {
int a = 0, b = 0, c = 0;
try {
b = r.nextInt();
c = r.nextInt();
System.out.println("Division by zero");
a = 0;
Output
1.4. Multithreading
ExtendThread.java
super(name);
try {
Thread.sleep(sleepTime);
System.out.println();
} catch (Exception e)
{ System.out.println(e.toString());
ImplementThread.java
this.name = name;
sleepTime = (int) (Math.random() * 5000);
System.out.println("Thread Name: " + getName() + " "
@Override
try {
th.sleep(sleepTime);
} catch (Exception e)
{ System.out.println(e.toString());
return this.name;
MultithreadingDemo.java
System.out.println("Starting Threads");
Thread1.start();
Thread2.start();
Thread3.start();
Thread4.start();
/ obj1.start();
/ obj2.start();;
/ obj3.start();
/ obj4.start();
Output
1.5. File IO
1.5.1. Read Into & Write From File
ReadFromFile.java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
FileReader fr = null;
BufferedReader br = null;
public ReadFromFile() {}
fr = new FileReader(filelocation);
br = new BufferedReader(fr);
String line="";
System.out.println("line");}
} finally {
if (fr != null) {
fr.close();
br.close();
}
}}}
WriteToFile.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
FileInputStream in = null;
try {
in = new FileInputStream(filelocation);
int size;
out.write(size);
System.out.println(ex.toString());
} finally {
in.close();
out.close();
}
FileIO.java
import java.io.IOException;
try {
rff.readDateFromFile();
wrf.writeDataToFile();
import java.io.*;
import java.util.zip.DeflaterOutputStream;
while((data = fis.read())!=-1){
dos.write(data);
}
dos.close();
fos.close();
fis.close();
}}
Unzip.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.InflaterInputStream;
fos.write(data);
iis.close();
fos.close();
fis.close();
}
2. User Interface Components with swings
2.1. GUI tools (Buttons, Labels, Text fields, Dialog box,
Tooltips, Menus, etc.)
GUIToolsDemo.java
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.TransferHandler;
import javax.swing.filechooser.FileNameExtensionFilter
;
public GUIToolsDemo() {
super("GUIToolsDemo");
con.setLayout(new FlowLayout());
lblName.setText("Name:");
con.add(lblName);
txtName.setText("Enter Name...");
txtName.setDragEnabled(true);
con.add(txtName);
con.add(lblPass);
txtPass.setText("*******");
con.add(txtPass);
genderGroup.add(rdMale);
genderGroup.add(rdFemale);
con.add(rdMale);
con.add(rdFemale);
con.add(lblCourse);
con.add(cmbCourses);
con.add(lblComments);
btnSubmit.addActionListener(this);
btnCancel.addActionListener(this);
con.add(btnSubmit);
btnSubmit.setTransferHandler(new TransferHandler("text"));
con.add(btnCancel);
fileMenu.add(newProject);
mainMenu.add(fileMenu);
fc.setFileFilter(filter);
fc.showOpenDialog(this);
fileMenu.add(newProject);
editMenu.add(cut);
editMenu.add(copy);
editMenu.add(paste);
mainMenu.add(editMenu);
setJMenuBar(mainMenu);
setSize(500, 600);
setVisible(true);
}
@Override
if(e.getSource()==btnSubmit)
String s= this.txtName.getText();
this.txtName.setText(s);
/int a= Integer.parseInt(s);
System.out.println("Cancel button is pressed");
Outputs
Output:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
private String names[] = {"HIDE NORTH", "HIDE SOUTH", "HIDE EAST","HIDE WEST", "HIDE CENTER"};
public BorderLayoutDemo() {
super("BorderLayout Demo");
con.setLayout(layout);
}
con.add(buttons[0], BorderLayout.NORTH);
buttons[0].addActionListener(this);
con.add(buttons[1], BorderLayout.SOUTH);
buttons[1].addActionListener(this);
con.add(buttons[2], BorderLayout.EAST);
buttons[2].addActionListener(this);
con.add(buttons[3], BorderLayout.WEST);
buttons[3].addActionListener(this);
con.add(buttons[4], BorderLayout.CENTER);
buttons[4].addActionListener(this);
setSize(400, 400);
setVisible(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@Override
if (e.getSource() == buttons[i]) {
buttons[i].setVisible(false);
}
Output
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
"Button8", "Button9"};
con.setLayout(layout);
setSize(400, 400);
setVisible(true);
new GridLayoutDemo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Output
2.2.3. Flow Layout
FlowLayoutDemo.java
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
FlowLayout layout;
public Flowlayout(){
con.setLayout(layout);
btnLeft.addActionListener(new ActionListener() {
@Override
layout.setAlignment(FlowLayout.LEFT);
layout.layoutContainer(con);
});
layout.setAlignment(FlowLayout.RIGHT);
layout.layoutContainer(con);
});
layout.setAlignment(FlowLayout.CENTER);
layout.layoutContainer(con);
}
});
setSize(400,400);
setVisible(true);
Outputs
3. Events Handling
GUIEventHandling.java
public GUIEventHandling() {
super("GUI EventHandling");
con.setLayout(new FlowLayout());
con.add(new JLabel("Country"));
cmbCountry.setToolTipText("Select Country");
cmbCountry.addActionListener(this);
con.add(cmbCountry);
con.add(new JLabel("-"));
setSize(500, 500);
setVisible(true);
@Override
if (e.getSource().equals(cmbCountry)) {
if (cmbCountry.getSelectedItem().toString() == "Nepal")
{ txtCodeNumber.setText("+977");
} else {
txtCodeNumber.setText("");
} Outputs
4.Database Connectivity
5.Network Programming
5.1. Working with URLs
ParseURL.java
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new
URL("http://example.com:80/docs/books/tutorial"
+
"/index.html?
name=networking#DOWNLOADIN
G");
System.out.println("protocol = " +
aURL.getProtocol());
System.out.println("authority = " +
aURL.getAuthority());
System.out.println("filename = " +
aURL.getFile()); System.out.println("host
= " + aURL.getHost());
System.out.println("port = " +
aURL.getPort());
System.out.println("path
= " + aURL.getPath());
System.out.println("query = " +
aURL.getQuery());
System.out.println("ref
= " + aURL.getRef());
}
}
Output
protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?
name=networking ref = DOWNLOADING
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.*;
String message;
String message;
try {
ostream = sock.getOutputStream();
dos.writeBytes(message);
ostream.close();
sock.close();
Server.java
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
try {
System.out.println("Server started!");
cSock = serSock.accept();
istream = cSock.getInputStream();
} finally {
dis.close();
istream.close();
cSock.close();
serSock.close();
Outputs
6. Servlets
6.1. HTTP Request and Response
HelloServlet.java
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 javax.sql.rowset.serial.SerialException;
public HelloServlet(){}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{
response.setContentType("text/html;charset= UTF-8");
write.println("HELLO WORLD!!");
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Hello World!!</h1>
</body>
</html>
Output
7.2. Creating and Processing Forms
Myjsp.html
<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form method="post" action ="mypage.jsp">
<table width="400" border="5" align="center">
<tr>
<td colspan="5" align="center"><h1>JSP form
Demo</h1></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type='text' name='name'/></td>
</tr>
<tr>
<td>Phone N0:</td>
<td><input type='text' name='phone'/></td>
</tr>
<tr>
<td colspan='5' align='center'><input type=
'submit' name='submit' value='Done'/></td>
</tr>
</form>
</body>
Mypage.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
Suresh Sunuwar
7.3. Session Management
Index.jsp
<%@page import="java.util.Date"%>
<%
if(session.isNew()){
session.setAttribute(UserIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
visitCount= (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount+1;
session.setAttribute(visitCountKey, visitCount);
userID = (String)session.getAttribute(UserIDKey);
%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<tr>
</tr>
<tr>
<td>user ID</td>
<td> <%out.print(userID);%></td>
</tr>
<tr>
<td>Session ID</td>
<td> <%out.print(session.getId());%></td>
</tr>
<tr>
<td>Creation Time</td>
<td><%out.print(creationTime);%></td>
</tr>
<tr>
<td><%out.print(lastAcessTime);%></td>
</tr>
<tr>
<td>Number of Visits</td>
<td><%out.print(visitCount);%></td>
</tr>
<tr>
<td>GOTO:</td>
</tr>
</form>
</body>
</html>
afterSession.jsp
<%
if(user==null){
%>
<jsp:forward page="index.jsp"></jsp:forward>
<%}%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>After Session</h1>
<p> <%out.print(user);%></p>
</html>
beforSession.jsp
<%
if(user==null){
%>
<jsp:forward page="index.jsp"></jsp:forward>
<%}%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>After Session</h1>
<p> <%out.print(user);%></p>
</body>
</html>
Outputs
8. RMI
8.1. Creating and Executing RMI Application
RMIInterface.java
import java.rmi.Remote;
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
try {
int respons=stub.add(2,5);
System.out.println("SUM="+ respons);
} catch (Exception e) {
Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
try {
System.out.println("Server ready");
} catch (Exception e) {
@Override
return (x+y);
Outputs
SUM= 7