[go: up one dir, main page]

0% found this document useful (0 votes)
2 views46 pages

Lab Work for Computer Students

Uploaded by

ashasunuwar6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views46 pages

Lab Work for Computer Students

Uploaded by

ashasunuwar6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 46

Cover Page [Create By Yourself as preffered]

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.

 Creating New Project+:

Project Name: BIM5

 Started To Code:

 Created Package if Necessary

 Created web application

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:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os
etc.

1.1. Simple Applet Program

import java.awt.*;
import java.applet.*;

public class FirstApplet extends Applet {


public void paint(Graphics g) {
g.setColor(Color.blue);
Font font = new Font("Arial", Font.BOLD, 16);
g.setFont(font);
g.drawString("This is My First Applet",60,110);
}
}

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

1.2. Draw Shapes:


package Applet;
import java.applet.*;
import java.awt.*;
public class DrawShape extends Applet{
public void paint(Graphics g){
//to draw line
// g.drawLine(10,10,100,100); // to draw rectangle
// g.drawRect(10,10,200,100);
// g.setColor(Color.BLUE);
// g.fillRect(10,10,200,100);
// circle and oval
// g.drawOval(10,10,200,100); //create imagineary rectangle --> Oval
// g.drawOval(100,100,100,100); // create imagineray square --> Circle
// To draw arc
// g.drawArc(20, 20, 200, 100, 0, 90);
// 0--> start andgle 90--> end angle put -90 in place of 90 -- down opposite arc 360-->oval
// g.fillArc(20, 20, 200, 100, 0, 360);
// To Draw polygon
Polygon p = new Polygon();
p.addPoint(200,200);
p.addPoint(100,30);
p.addPoint(20,200);
g.drawPolygon(p); // g.fillPolygon--> color fill with black
}
}
Output: Polygon, Line and Rectangle
1.3. Exception Handling
ExceptionExample.java

import java.util.Random;

class ExceptionExample {

public static void main(String args[]) {

int a = 0, b = 0, c = 0;

Random r = new Random();

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

try {

b = r.nextInt();

c = r.nextInt();

a = 12345 / (b / c);} catch (ArithmeticException e) {

System.out.println("Division by zero");
a = 0;

System.out.println("a: " + a);

Output
1.4. Multithreading
ExtendThread.java

public class ExtendThread extends Thread {


private int sleepTime;

public ExtendThread(String name) {

super(name);

sleepTime = (int) (Math.random() * 5000);


System.out.println("Thread Name: " + getName() + " "

+ ";Sleep Time :" + sleepTime);

public void run() {

try {

System.out.println(getName() + " is going to sleep");

Thread.sleep(sleepTime);

System.out.println();

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

System.out.println(getName()+" is done sleeping");

ImplementThread.java

public class ImplementThread implements Runnable {

private int sleepTime;

private String name;

public ImplementThread(String name) {

this.name = name;
sleepTime = (int) (Math.random() * 5000);
System.out.println("Thread Name: " + getName() + " "

+ ";Sleep Time :" + sleepTime);

@Override

public void run() {

Thread th = new Thread();

try {

System.out.println(getName() + " is going to sleep");

th.sleep(sleepTime);

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

System.out.println(getName() + " is done sleeping");

private String getName() {

return this.name;

MultithreadingDemo.java

public class MultiThreadingDemo {

public static void main(String[] args) {

ExtendThread Thread1, Thread2, Thread3, Thread4;

Thread1 = new ExtendThread("Thread1");

Thread2 = new ExtendThread("Thread2");

Thread3 = new ExtendThread("Thread3");

Thread4 = new ExtendThread("Thread4");

/ ImplementThread IThread1, IThread2, IThread3, IThread4;

/ IThread1 = new ImplementThread(" IThread1");


/ IThread2 = new ImplementThread(" IThread2");

/ IThread3 = new ImplementThread(" IThread3");

/ IThread4 = new ImplementThread(" IThread4");

/ Thread obj1 = new Thread(IThread1);

/ Thread obj2 = new Thread(IThread2);

/ Thread obj3 = new Thread(IThread3);

/ Thread obj4 = new Thread(IThread4);

System.out.println("Starting Threads");

Thread1.start();

Thread2.start();

Thread3.start();

Thread4.start();

/ obj1.start();

/ obj2.start();;

/ obj3.start();

/ obj4.start();

System.out.println("Thread has been started");

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;

public class ReadFromFile {

String filelocation = "E:\\abc.docx";

FileReader fr = null;

BufferedReader br = null;

public ReadFromFile() {}

public void readDateFromFile() throws IOException


{ try {

fr = new FileReader(filelocation);

br = new BufferedReader(fr);

String line="";

while ((line = br.readLine()) != null) {

System.out.println("line");}

} catch (FileNotFoundException ex) {


System.out.println(ex.toString());

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

public class WriteToFile {

String filelocation = "E:\\new.txt";

String outputFile = "E:\\new(copy).txt";

FileInputStream in = null;

FileOutputStream out = null;

public WriteToFile() throws IOException {}

public void writeDataToFile() throws IOException {

try {

in = new FileInputStream(filelocation);

out = new FileOutputStream(outputFile);

int size;

while ((size = in.read()) != -1) {

out.write(size);

} catch (FileNotFoundException ex) {

System.out.println(ex.toString());

} finally {

in.close();

out.close();

}
FileIO.java

import java.io.IOException;

public class FileIO {

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


ReadFromFile rff = new ReadFromFile();

WriteToFile wrf = new WriteToFile();

try {

rff.readDateFromFile();

wrf.writeDataToFile();

} catch (IOException ex)


{ System.out.println(ex.toString()
);
}}}

1.5.2. Zip and UnZip File


Zip.java

import java.io.*;

import java.util.zip.DeflaterOutputStream;

public class Zip {

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

FileInputStream fis = new FileInputStream("E:\\abc.docx");

FileOutputStream fos = new FileOutputStream("E:\\zip");


DeflaterOutputStream dos = new DeflaterOutputStream(fos);
int data;

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;

public class Unzip {

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


FileInputStream fis = new FileInputStream("E:\\zip");

FileOutputStream fos = new FileOutputStream("E:\\Unzip.docx");

InflaterInputStream iis = new InflaterInputStream(fis); int data;

while ((data = iis.read()) != -1) {

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 class GUIToolsDemo extends JFrame implements ActionListener {

private JButton btnSubmit,btnCancel;

private JTextField txtName;

public GUIToolsDemo() {

super("GUIToolsDemo");

Container con = getContentPane();

con.setLayout(new FlowLayout());

JLabel lblName= new JLabel();

lblName.setText("Name:");

con.add(lblName);

txtName = new JTextField("kkkk");

txtName.setText("Enter Name...");

txtName.setDragEnabled(true);

con.add(txtName);

JLabel lblPass= new JLabel("password");

con.add(lblPass);

JPasswordField txtPass= new JPasswordField();

txtPass.setText("*******");

con.add(txtPass);

JLabel lblgender = new JLabel("Gender");


con.add(lblgender);

JRadioButton rdMale = new JRadioButton("Male");

JRadioButton rdFemale = new JRadioButton("Female");

ButtonGroup genderGroup = new ButtonGroup();

genderGroup.add(rdMale);

genderGroup.add(rdFemale);

con.add(rdMale);

con.add(rdFemale);

JLabel lblCourse = new JLabel("Course");

con.add(lblCourse);

String[] courses = {"java Programming ", "PHP", "ROR",


"ASP.Net","Python"}; JComboBox cmbCourses = new JComboBox(courses);

con.add(cmbCourses);

JLabel lblComments= new JLabel("Comments");

con.add(lblComments);

JTextArea txtComments= new JTextArea("Comments


here..."); con.add(txtComments);

btnSubmit = new JButton("Submit");

btnSubmit.addActionListener(this);

btnCancel = new JButton("Cancel");

btnCancel.addActionListener(this);

con.add(btnSubmit);

btnCancel.setToolTipText("This button does nothing");

btnSubmit.setTransferHandler(new TransferHandler("text"));

con.add(btnCancel);

JMenuBar mainMenu = new JMenuBar();

JMenu fileMenu = new JMenu("FILE");


JMenuItem newProject = new JMenuItem(" New project");

fileMenu.add(newProject);

mainMenu.add(fileMenu);

final JFileChooser fc = new JFileChooser();

FileNameExtensionFilter filter = new FileNameExtensionFilter("All Files", "*.*");

fc.setFileFilter(filter);

fc.showOpenDialog(this);

JMenu editMenu = new JMenu("EDIT");

JMenuItem copy = new JMenuItem(" copy");

JMenuItem cut = new JMenuItem(" cut");

JMenuItem paste = new JMenuItem("paste");

fileMenu.add(newProject);

editMenu.add(cut);

cut.setIcon(new ImageIcon("C:\\Users\\Prashant Gautam\\Documents\\


NetBeansProjects\\GUIToolsDemo\\src\\icons/cut.png"));

editMenu.add(copy);

editMenu.add(paste);

mainMenu.add(editMenu);

setJMenuBar(mainMenu);

setSize(500, 600);

setVisible(true);

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


= new GUIToolsDemo();
guiDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// TODO code application logic here

}
@Override

public void actionPerformed(ActionEvent e) {

if(e.getSource()==btnSubmit)

String s= this.txtName.getText();

System.out.println("Submit Button is pressed");

else if(e.getSource()== btnCancel)

String s="Dummy text";

this.txtName.setText(s);

/int a= Integer.parseInt(s);
System.out.println("Cancel button is pressed");

Outputs
Output:

2.2. Layout Managements


2.2.1. Border Layout
BorderLayoutDemo.java

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;

public class BorderLayoutDemo extends JFrame implements ActionListener


{ private JButton buttons[];

private String names[] = {"HIDE NORTH", "HIDE SOUTH", "HIDE EAST","HIDE WEST", "HIDE CENTER"};

private BorderLayout layout;

public BorderLayoutDemo() {

super("BorderLayout Demo");

layout = new BorderLayout();

Container con = getContentPane();

con.setLayout(layout);

buttons = new JButton[names.length];

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

buttons[i] = new JButton(names[i]);

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

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

app = new BorderLayoutDemo();

app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

@Override

public void actionPerformed(ActionEvent e) {

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

if (e.getSource() == buttons[i]) {

buttons[i].setVisible(false);

}
Output

2.2.2. Grid Layout


GridLayoutDemo.java

import java.awt.Container;

import java.awt.GridLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

public class GridLayoutDemo extends JFrame {

private JButton buttons[];

private String names[] = {"Button1", "Button2", "Button3",

"Button4", "Button5","Button6", "Button7",

"Button8", "Button9"};

private GridLayout layout;


public GridLayoutDemo() {

super("Grid Layout Demo");

layout = new GridLayout(3, 3);

Container con = getContentPane();

con.setLayout(layout);

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

con.add(new JButton("MyButton" + (i + 1)));

setSize(400, 400);

setVisible(true);

public static void main(String[] args) { GridLayoutDemo app =

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;

public class Flowlayout extends JFrame{

private JButton btnLeft,btnRight,btnCenter;

FlowLayout layout;

public Flowlayout(){

super("Flow layout demo");


Container con = getContentPane();

layout = new FlowLayout();

con.setLayout(layout);

con.add(btnLeft = new JButton("LEFT"));

btnLeft.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

layout.setAlignment(FlowLayout.LEFT);

layout.layoutContainer(con);

});

con.add(btnRight = new JButton("Right"));


btnRight.addActionListener(new ActionListener()
{ @Override

public void actionPerformed(ActionEvent e) {

layout.setAlignment(FlowLayout.RIGHT);

layout.layoutContainer(con);

});

con.add(btnCenter = new JButton("Center"));


btnCenter.addActionListener(new ActionListener()
{ @Override

public void actionPerformed(ActionEvent e) {

layout.setAlignment(FlowLayout.CENTER);

layout.layoutContainer(con);
}

});

setSize(400,400);

setVisible(true);

public static void main(String[] args) { Flowlayout app =


new Flowlayout();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Outputs
3. Events Handling
GUIEventHandling.java

public class GUIEventHandling extends JFrame implements ActionListener {

private String[] countyName = {"Nepal", "India", "USA", "Select Country"};

private JComboBox cmbCountry;

private JTextField txtCodeNumber;

private JTextField txtMobileNumber;

public GUIEventHandling() {

super("GUI EventHandling");

Container con = getContentPane();

con.setLayout(new FlowLayout());

con.add(new JLabel("Country"));

cmbCountry = new JComboBox(countyName);

cmbCountry.setToolTipText("Select Country");

cmbCountry.addActionListener(this);

con.add(cmbCountry);

con.add(new JLabel("Mobile NO:"));

con.add(txtCodeNumber = new JTextField("", 3));

con.add(new JLabel("-"));

con.add(txtMobileNumber = new JTextField("", 10));

setSize(500, 500);

setVisible(true);

public static void main(String[] args)


{ GUIEventHandling App = new
GUIEventHandling();
App.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

@Override

public void actionPerformed(ActionEvent e) {

if (e.getSource().equals(cmbCountry)) {

if (cmbCountry.getSelectedItem().toString() == "Nepal")
{ txtCodeNumber.setText("+977");

} else if (cmbCountry.getSelectedItem().toString() == "India") {


txtCodeNumber.setText("+91");

} else if (cmbCountry.getSelectedItem().toString() == "USA")


{ txtCodeNumber.setText("+1");

} 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

5.2. TCP sockets


Client.java

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.net.*;

public class Client {

String message;

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


OutputStream ostream = null;

Socket sock = null;

DataOutputStream dos = null;

String message;

try {

sock = new Socket("127.0.0.1", 5001);

message = "Hello Server ";

ostream = sock.getOutputStream();

dos = new DataOutputStream(ostream);

dos.writeBytes(message);

} catch (IOException ex)


{ System.out.println(ex.toString()
);
} finally
{ dos.close(
);

ostream.close();

sock.close();

Server.java

import java.io.DataInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.*;

public class Server {

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

ServerSocket serSock = null;

DataInputStream dis = null;

InputStream istream = null;

Socket cSock = null;

try {

serSock = new ServerSocket(5001);

System.out.println("Server started!");

cSock = serSock.accept();

istream = cSock.getInputStream();

dis = new DataInputStream(istream);

String msg = dis.readLine();

System.out.println("From client :" + msg);


} catch (IOException ex)
{ System.out.println(ex.toString()
);

} 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 class HelloServlet extends HttpServlet {

public HelloServlet(){}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{

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

PrintWriter write = response.getWriter();

write.println("HELLO WORLD!!");

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException{

7. Java Server Pages


7.1. JSP Basic
Index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</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>

<%--<meta http-equiv="Content-Type" content="text/html;


charset=UTF-8">--%> <title>JSP Page</title>
</head>
<body>
Name= <%= request.getParameter("name")%>
<br>
Phone=<%= request.getParameter("phone")%>
</body>
</html>
Outputs

Suresh Sunuwar
7.3. Session Management
Index.jsp

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

<%

Integer visitCount = new Integer(0);

String visitCountKey = new String("Visit count");

String userID = new String("prashant");

String UserIDKey = new String("userID");

Date creationTime = new Date(session.getCreationTime());

Date lastAcessTime = new Date(session.getLastAccessedTime());

if(session.isNew()){

session.setAttribute(UserIDKey, userID);

session.setAttribute(visitCountKey, visitCount);

visitCount= (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount+1;

session.setAttribute(visitCountKey, visitCount);

creationTime = new Date(session.getCreationTime());

lastAcessTime = new Date(session.getLastAccessedTime());

userID = (String)session.getAttribute(UserIDKey);

%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>
<form>

<table width='400' border='5' align='center'>

<tr>

<td colspan='5' align='center'><h1>SESSION INFORMATION</h1></td>

</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>Last Access Time</td>

<td><%out.print(lastAcessTime);%></td>

</tr>

<tr>

<td>Number of Visits</td>

<td><%out.print(visitCount);%></td>

</tr>
<tr>

<td>GOTO:</td>

<td><a href="afterSession.jsp"> Link to next page</a></td>

</tr>

</form>

</body>

</html>

afterSession.jsp

<%

String user = (String)session.getAttribute("userID");

if(user==null){

%>

<jsp:forward page="index.jsp"></jsp:forward>

<%}%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>

<h1>After Session</h1>

<p> <%out.print(user);%></p>

<p><a href="destroySession.jsp">Destroy Session</a></p>


</body>

</html>
beforSession.jsp

<%

String user = (String)session.getAttribute("userID");

if(user==null){

%>

<jsp:forward page="index.jsp"></jsp:forward>

<%}%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>

<h1>After Session</h1>

<p> <%out.print(user);%></p>

<p><a href="destroySession.jsp">Destroy Session</a></p>

</body>

</html>
Outputs
8. RMI
8.1. Creating and Executing RMI Application

RMIInterface.java

import java.rmi.Remote;

public interface RMIinterface extends Remote {

public int add( int x, int y);

Client.java

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

public class Client {

public static void main(String[] args) {

try {

Registry reg = LocateRegistry.getRegistry("127.0.0.1",1099);

RMIinterface stub = (RMIinterface) reg.lookup("key");

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;

public class Server implements RMIinterface{


public static void main(String[] args) {

try {

Server s = new Server();

RMIinterface stub = (RMIinterface) UnicastRemoteObject.exportObject(s,

0); Registry reg = LocateRegistry.createRegistry(1099); reg.bind("key", stub);

System.out.println("Server ready");

} catch (Exception e) {

@Override

public int add(int x, int y) {

return (x+y);

Outputs

SUM= 7

You might also like