Advanced - Java - Lab Manual (Updated) 31.05.2022

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

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING(DATA SCIENCE)
IV SEMESTER
ACADEMIC YEAR 2021-22 [EVEN]

Advanced Java Programming Lab


MVJ20CDL48
LABORATORY MANUAL

NAM E OF THE
:
STUDENT

BRANCH :

UNIVERSITY SEAT NO. :

SEMESTER & SECTION :

BATCH :
Advanced Java Programming Lab [MVJ20CDL48]

Department of Information Science and Engineering

Institute Vision
To become an institute of academic excellence with international standards.

Institute Mission
Impart quality education along with industry exposure.

Provide world class facilities to undertake research activities relevant to


industrial and professional needs.

Promote entrepreneurship and value added education that is socially


relevant with economic benefits
Department Vision
To be recognized as a department of repute in Information Science and Engineering by adopting
quality teaching learning process and impart knowledge to make students equipped with capabilities
required for professional, industrial and research areas to serve society.
Department Mission
Innovation and technically competent: To impart quality education in Information Science
and Engineering by adopting modern teaching learning processes using innovation
techniques that enable them to become technically competent.
Competitive Software Professionals: Providing training Programs that bridges gap between
industry and academia, to produce competitive software professionals.
Personal and Professional growth: To provide scholarly environment that enables value
addition to staff and students to achieve personal and profession growth.
Program Outcomes (PO):
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
Dept. of CSE(Data Science), MVJCE Page 2 2021-22
Advanced Java Programming Lab [MVJ20CDL48]

considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Program Educational Objectives (PEOs):
IT Proficiency: Graduates will excel as IT Experts with extensive knowledge to analyze and design
solutions to Information Engineering problems.
Social &moral principles: Graduates will work in a team, showcase professionalism; ethical values
expose themselves to current trends and become responsible Engineers.
Higher education: Graduates will pursue higher studies with the sound knowledge of fundamental

Dept. of CSE(Data Science), MVJCE Page 3 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

concepts and skills in basic sciences and IT disciplines.

Program Specific Outcomes (PSO):


PSO1. Software professional expertise: An ability to understand, analyze and develop computer
programs in the areas related to algorithms, system software, multimedia, web design,
DBMS, and networking for efficient design of computer-based systems of varying
complexity.
PSO2. Core competence: An ability to compete practically to provide solutions for real world
problems with a broad range of programming language and open source platforms in
various computing domains
Course objectives: This course will enable students to
Develop error free and , well documented, Java programs
Course outcomes: The students should be able to:
Develop Java Network programs
Develop Search Engine and web framework programs
Learn how to write advanced-level Object-Oriented Programs using Java
Develop appropriate data model and data base scheme
Test and validate programs
PREREQUISITES:

 Understanding of Eclipse
Operating System:
 Windows

Dept. of CSE(Data Science), MVJCE Page 4 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

CONTENTS
Sl.No. Title of Experiment
1 Write a java program on Network Programming i.e Client - Server Programming.

2 Write a java program on Multi threading using Runnable interface.

3 Write a java program to create a New Data Source for Ms Access.


4 Write a java program to show connectivity with data base using JDBC/ODBC Driver
5 Write a java program to get Information about data base using Data base Metadata
Write a java program to get Information about particular table using Result Set Meta
6 Data.
Write a java program to implement the concept of swings.
7
Write a java program to develop an RMI application.
8
Write a program in Servlets to get and display value from an HTML page.
9
10 Write a program in JSP to get and display value from an HTML page

Content Beyond Syllabus:


11. Program to implement Calculator using applets

12. Program to demonstrate prints the different parts of a URL specified as a command line argument.

Conduction of Practical Examination:


• All laboratory experiments are to be included for practical examination.
• Students are allowed to pick one experiment from the lot.
• Strictly follow the instructions as printed on the cover page of answer script
• Marks distribution: Procedure + Conduction + Viva: 20 + 50 +10 (80)
Change of experiment is allowed only once and marks allotted to the procedure part to be made
zero.

Dept. of CSE(Data Science), MVJCE Page 5 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 1- Write a program on Network Programming i.e Client - Server Programming.

Implementation:

Establish a Socket Connection

To connect to another machine we need a socket connection. A socket connection means the two
machines have information about each other’s network location (IP Address) and TCP port. The
java.net.Socket class represents a Socket. To open a socket:

Socket socket = new Socket(“127.0.0.1”, 8091)

The first argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where code
will run on the single stand-alone machine).

The second argument – TCP Port. (Just a number representing which application to run on a
server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

Communication

To communicate over a socket connection, streams are used to both input and output the
data.

Closing the connection:

The socket connection is closed explicitly once the message to the server is sent.

In the program, the Client keeps reading input from a user and sends it to the server until “Stop”
is typed.

PROGRAM

package networkprograms;

//A Java program for a //Client

import java.net.*;

import java.io.*;

public class Client

// initialize socket and input output streams

Dept. of CSE(Data Science), MVJCE Page 6 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

private Socket socket = null;

private DataInputStream input = null;

private DataOutputStream out = null;

// constructor to put ip address and port

public Client(String address, int port)

// establish a connection

try

socket = new Socket(address, port);

System.out.println("Connected");

// takes input from terminal

input = new DataInputStream(System.in);

// sends output to the socket

out = new DataOutputStream(socket.getOutputStream());

catch(UnknownHostException u)

System.out.println(u);

catch(IOException i)

System.out.println(i);

Dept. of CSE(Data Science), MVJCE Page 7 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

// string to read message from input

String line = "";

// keep reading until "Over" is input

while (!line.equals("Stop"))

try

line = input.readLine();

out.writeUTF(line);

catch(IOException i)

System.out.println(i);

// close the connection

try

input.close();

out.close();

socket.close();

catch(IOException i)

Dept. of CSE(Data Science), MVJCE Page 8 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

System.out.println(i);

public static void main(String args[])

Client client = new Client("127.0.0.1", 8091);

package networkprograms;

//A Java program for a Server

import java.net.*;
public class Server

//initialize socket and input stream

private Socket socket = null;

private ServerSocket server = null;

private DataInputStream in = null;

// constructor with port

public Server(int port)

// starts server and waits for a connection

try

server = new ServerSocket(port);

Dept. of CSE(Data Science), MVJCE Page 9 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

System.out.println("Server started");
System.out.println("Waiting for a client ...");

socket = server.accept();

System.out.println("Client accepted");

// takes input from the client socket

in = new DataInputStream(

new BufferedInputStream(socket.getInputStream()));

String line = "";

// reads message from client until "Over" is sent

while (!line.equals("Stop"))

try

line = in.readUTF();

System.out.println(line);

catch(IOException i)

System.out.println(i);

System.out.println("Closing connection");

// close connection

Dept. of CSE(Data Science), MVJCE Page 10 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

socket.close();

in.close();

catch(IOException i)

System.out.println(i);

public static void main(String args[])

Server server = new Server(8091);

}
Output: First compile the Server, Client programs
And Run Server first

Give input in Client Console

Dept. of CSE(Data Science), MVJCE Page 11 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

Type Stop in Client Console

Dept. of CSE(Data Science), MVJCE Page 12 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 2: Write a java program on Multi threading using Runnable Interface

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight
processes within a process.

Threads can be created by using two mechanisms :

Extending the Thread class

Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the run() method available
in the Thread class. A thread begins its life inside run() method. We create an object of our new class and
call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.

/* Java code for thread creation by extending the Thread class

class MultithreadingDemo extends Thread {

public void run()

try {

// Displaying the thread that is running

System.out.println(

"Thread " + Thread.currentThread().getId()

+ " is running");

catch (Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

}
Dept. of CSE(Data Science), MVJCE Page 13 2021-22
Advanced Java Programming Lab [MVJ20CDL48]

// Main Class

public class Multithread {

public static void main(String[] args)

int n = 8; // Number of threads

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

MultithreadingDemo object

= new MultithreadingDemo();

object.start();

} */

Thread creation by implementing the Runnable Interface

We create a new class which implements java.lang.Runnable interface and override run() method. Then
we instantiate a Thread object and call start() method on this object.

PROGRAM-

// Java code for thread creation by implementing

// the Runnable Interface

class MultithreadingDemo implements Runnable {

public void run()

try {

// Displaying the thread that is running

Dept. of CSE(Data Science), MVJCE Page 14 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

System.out.println(

"Thread " + Thread.currentThread().getId()

+ " is running");

catch (Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

// Main Class

public class Program2Runnable {

public static void main(String[] args)

int n = 8; // Number of threads

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

Thread object = new Thread(new MultithreadingDemo());

object.start();

Dept. of CSE(Data Science), MVJCE Page 15 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

OUTPUT-

Dept. of CSE(Data Science), MVJCE Page 16 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 3: Write a java program to create a New Data Source for Ms Access.

Introduction

In this article, we make a connection using JDBC to a Microsoft Access database. This
connection is made with the help of a JdbcOdbc driver. You need to use the following steps for
making a connection to the database.
Creating a Database
Step 1: Open Microsoft Access and select Blank database option and give the database name
as File name option

Step 2: Create a table and insert your data into the table

Step 3: Save the table with the desired name; in this article, we save the following records with
the table name student.

Now Creating DSN of your database


Dept. of CSE(Data Science), MVJCE Page 17 2021-22
Advanced Java Programming Lab [MVJ20CDL48]

Step 4: Open your Control Panel and then select Administrative Tools.

Step 5 : Click on Data Source(ODBC)-->System DSN.

Step 6: Now click on add option for making a new DSN.select Microsoft Access Driver (*.mdb.
*.accdb) and then click on Finish

Dept. of CSE(Data Science), MVJCE Page 18 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

Step 7: Make your desired Data Source Name and then click on the Select option, for example in
this article we use the name mydsn

Step 8: Now you select your data source file for storing it and then click ok and then click
on Create and Finish

Dept. of CSE(Data Science), MVJCE Page 19 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

Add the access database and select the path of data base with data source.

Dept. of CSE(Data Science), MVJCE Page 20 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

package msaccessprogram3pack;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

public class Msprog3 {

public static void main(String[] args)

try

Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:/Users/MVJ PC-119/eclipse-


workspace/msaccessprogram3/db1.accdb");

Statement stment = conn.createStatement();

String qry = "SELECT * FROM emp";

ResultSet rs = stment.executeQuery(qry);

while(rs.next())

String id = rs.getString(1) ;

String fname = rs.getString(2);

String address=rs.getString(3);

System.out.println(id + fname);

catch(Exception err)

Dept. of CSE(Data Science), MVJCE Page 21 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

System.out.println(err);

OUTPUT:

FILE STRUCURE

Dept. of CSE(Data Science), MVJCE Page 22 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 4: Write a java program to show connectivity with data base using JDBC/ODBC
Driver

Commit;

Create java project, create a package. And write Myjdbc.java class file

Myjdbc.java

package jdbcpack;

import java.sql.*;

public class Myjdbc {

public static void main(String[] args) {

// TODO Auto-generated method stub

Dept. of CSE(Data Science), MVJCE Page 23 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE","kalyani","kalyani");

Statement stmt=con.createStatement();

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

while(rs.next())

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

con.close();

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

Create folder lib in project.

Build path: lib file path:


C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib
Build path for project. And also class path.
Go to project run as java application :
Output:

Dept. of CSE(Data Science), MVJCE Page 24 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 5: Write a java program to get Information about data base using Data
base Metadata
Java DatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number of views etc.
Commonly used methods of DatabaseMetaData interface
public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
public String getDriverVersion()throws SQLException: it returns the version number of the
JDBC driver.
public String getUserName()throws SQLException: it returns the username of the database.
public String getDatabaseProductName()throws SQLException: it returns the product name of
the database.
public String getDatabaseProductVersion()throws SQLException: it returns the product version
of the database.
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types)throws SQLException: it returns the description of the tables of the specified
catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.

How to get the object of DatabaseMetaData:


The getMetaData() method of Connection interface returns the object of DatabaseMetaData.
Syntax:
public DatabaseMetaData getMetaData()throws SQLException

PROGRAM-

package jdbcpack;

import java.sql.*;

public class Myjdbc {

public static void main(String[] args) {

// TODO Auto-generated method stub

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE","kalyani","kalyani");
Dept. of CSE(Data Science), MVJCE Page 25 2021-22
Advanced Java Programming Lab [MVJ20CDL48]

DatabaseMetaData dbmd=con.getMetaData();

String table[]={"VIEW"};

ResultSet rs=dbmd.getTables(null,null,null,table);

while(rs.next()){

System.out.println(rs.getString(3));

con.close();

catch(Exception e)

System.out.println("Exception"+e);

}
OUTPUT:

Dept. of CSE(Data Science), MVJCE Page 26 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

(OUTPUT AS META DATA DISPLAY)

Dept. of CSE(Data Science), MVJCE Page 27 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 6: Write a java program to get Information about particular table using Result
Set Meta Data.

Java ResultSetMetaData Interface:

The metadata means data about data i.e. we can get further information from the data.If you have to get
metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface
is useful because it provides methods to get metadata from the ResultSet object.Commonly used methods of
ResultSetMetaData interface

MethodDescription:

public int getColumnCount()throws SQLExceptionit returns the total number of columns in the ResultSet
object.

public String getColumnName(int index)throws SQLExceptionit returns the column name of the specified
column index.

public String getColumnTypeName(int index)throws SQLExceptionit returns the column type name for the
specified index.

public String getTableName(int index)throws SQLExceptionit returns the table name for the specified column
index.

How to get the object of ResultSetMetaData:The getMetaData() method of ResultSet interface returns the
object of ResultSetMetaData.

Syntax:

public ResultSetMetaData getMetaData()throws SQLException

package jdbcpack;

import java.sql.*;

public class Myjdbc {

public static void main(String[] args) {

// TODO Auto-generated method stub

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE","kalyani","kalyani");

PreparedStatement ps=con.prepareStatement("select * from emp");


Dept. of CSE(Data Science), MVJCE Page 28 2021-22
Advanced Java Programming Lab [MVJ20CDL48]

ResultSet rs=ps.executeQuery();

ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());

System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));

System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));

con.close();

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

OUTPUT:

Dept. of CSE(Data Science), MVJCE Page 29 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 7: Write a java program to implement the concept of swings.


Swing is lightweight and platform independent. It is used for creating window based applications. It includes
components like button, scroll bar, text field etc.

package swingspack;

import javax.swing.*;

import java.awt.*;

//Step 2 – Decide the class name & Container class

//(JFrame/JApplet) to be used

public class SwingExample extends JFrame {

//Step 3 – Create all the instances required

JTextField txtName,txtPass;

JLabel lblName, lblPass;

JButton cmdOk,cmdCancel;

public SwingExample()

//Step 4- Create objects for the declared instances

txtName=new JTextField(10);

txtPass =new JTextField(10);

lblName=new JLabel("User Name");

lblPass =new JLabel("Password");

cmdOk =new JButton("Ok");

cmdCancel=new JButton("Cancel");

//Step 5 – Add all the objects in the Content Pane with Layout

Container con=getContentPane();

con.setLayout(new FlowLayout());

Dept. of CSE(Data Science), MVJCE Page 30 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

con.add(lblName); con.add(txtName);

con.add(lblPass); con.add(txtPass);

con.add(cmdOk); con.add(cmdCancel);

}//constructor

//Step 6 – Event Handling. (Event handling code will come

//here)

public static void main(String args[]) {

//Step 7 – Create object of class in main method

SwingExample l=new SwingExample();

l.setSize(150,200);

l.setVisible(true);

}//main

}//class

OUTPUT-

Dept. of CSE(Data Science), MVJCE Page 31 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 8: Write a java program to develop an RMI application.

Java Remote Method Invocation (RMI) is an object-oriented Remote Procedure Call (RPC)

technique. It allows us to invoke methods on an object that exists in a different address space.

RMI Programming Model:

Application components

Server

This is a program that typically creates a remote object to be used for method invocation. This object is
an ordinary object except that its class implements a Java RMI interface. Upon creation, the object is
exported and registered with a separate application called object registry (or simply registry).

Client : A client program typically consults the object registry to get a reference (handle) to a remote
object with a specified name. It can then invoke methods on the remote object using this reference
(handle) as if the object is stored in the client’s own address space. The RMI handles the details of
communication (using sockets) between the client and the server and passes information back and forth.
Note that this complex communication procedure is absolutely hidden to the client and server applications.

Object Registry

It is essentially a table of objects. Each entry of the table maps the object name to its proxy known as
stub.

Basic Steps

Developing and running RMI applications involves the following steps:

Dept. of CSE(Data Science), MVJCE Page 32 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

• Define the remote interface

• Implement the remote interface

• Create, export and register a remote object in the server program

• Get a reference of the remote object in the client program

• Compile the Java source files

• Run the application

Define a remote interface

The remote interface must be public.

The remote interface extends (either directly or indirectly) the

interface java.rmi.Remote. The interface

Remote is a marker interface and has no methods.

public interface java.rmi.Remote {

Implement the remote interface

We then write a concrete class implementing one or more such remote interfaces

Implement the server

Implementing a server application that creates an instance of the remote object and registers it to the RMI
registry with a name is called object deployment.

Implement the client

bA client application gets a handle to this remote object and invokes methods on it.

Start the application

First, start an object registry. In Java, the object registry is started using the application rmiregistry.

It can also be created dynamically

RMI Architecture

Dept. of CSE(Data Science), MVJCE Page 33 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

An Application:

SERVER_HOME FOLDER:
//Calculator.java
import java.rmi.*;
public interface Calculator extends Remote {
public int add(int a, int b) throws RemoteException;
}

//SimpleCalculator.java
import java.rmi.*;
public class SimpleCalculator implements Calculator {
public int add(int a, int b) {
System.out.println("Received: " + a + "and" + b);
int result = a + b;
Dept. of CSE(Data Science), MVJCE Page 34 2021-22
Advanced Java Programming Lab [MVJ20CDL48]

System.out.println("Sent: " + result);


return result;
}
}

//CalculatorServer.java
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class CalculatorServer {
public static void main(String args[]) {
try {
SimpleCalculator cal = new SimpleCalculator();
Calculator stub = (Calculator)UnicastRemoteObject.exportObject(cal,0);
Registry registry = LocateRegistry.getRegistry();
String name = "calculator";
registry.rebind(name, stub);
System.out.println("Calculator server ready...");
}catch (Exception e) { e.printStackTrace(); }
}
}
CLIENT_HOME FOLDER:
//Calculator.java
import java.rmi.*;
public interface Calculator extends Remote {
public int add(int a, int b) throws RemoteException;
}
//CalculatorClient.java
import java.rmi.*;
import java.rmi.registry.*;
public class CalculatorClient {
public static void main(String args[]) {
try {
String name = "calculator";
Registry registry = LocateRegistry.getRegistry(args[0]);
//System.out.println(registry);
//uncomment above line if you want to display the info. about registry
Calculator cal = (Calculator)registry.lookup(name);
//System.out.println(cal);
//uncomment above line if you want to display the info. about cal
int x = 4, y = 3;
int result = cal.add(x,y);
System.out.println("Sent: " + x +" and "+y);
System.out.print("Received("+x+"+"+y+"=): " + result);

Dept. of CSE(Data Science), MVJCE Page 35 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

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


}
}

Open 2 command prompt one is for SERVER_HOME,another one is for CLIENT_HOME


Go to that corresponding SERVER_HOME, CLIENT_HOME directories and compile all java
programs by typing

javac *.java

set path=”C:\Program Files\Java\jdk-16.0.1\bin”;

start rmiregitry

Dept. of CSE(Data Science), MVJCE Page 36 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

Minimize the window.

First Run the Server

Second Run the Client

Dept. of CSE(Data Science), MVJCE Page 37 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 9: Write a program in Servlets to get and display value from an HTML page.

ParameterServlet.java
package myservlet;

import javax.servlet.*;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Enumeration;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.*;

public class ParameterServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

doGet(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// TODO Auto-generated method stub

response.setContentType("text/html");

PrintWriter out=response.getWriter();

out.println("<html><head>");

out.println("<title>Servlet Parameter</title>");

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

out.println("<body>");

Dept. of CSE(Data Science), MVJCE Page 38 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

Enumeration parameters = request.getParameterNames();

String param=null;

while (parameters.hasMoreElements())

param=(String)parameters.nextElement();

out.println(param + ":" + request.getParameter(param) + "<br>" );

out.println("</body></html>");

out.close();

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Parameter Servlet Form</title>

</head>

<body>

<form action="parameter" method=Post>

<table width="400" border="0" cellspacing="0">

<tr>

<td>Name:</td>

<td>

Dept. of CSE(Data Science), MVJCE Page 39 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

<input type="text" name="name" size="20" maxlength="20">

</td>

<td>SSN:</td>

<td>

<input type="text" name="ssn" size="11" maxlength="11">

</td>

</tr>

<tr>

<td>Age:</td>

<td>

<input type="text" name="age" size="3" maxlength="3">

</td>

<td>email:</td>

<td>

<input type="text" name="email" size="30" maxlength="30">

</td>

</tr>

<tr>

<td> </td>

<td> </td>

<td> </td>

<td>

<input type="submit" name="submit" >

<input type="reset" name="reset" >

</td>

Dept. of CSE(Data Science), MVJCE Page 40 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

</tr>

</table>

</form>

</body>

</html>

web.xml

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<servlet>

<servlet-name>ParameterServlet</servlet-name>

<servlet-class>myservlet.ParameterServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ParameterServlet</servlet-name>

<url-pattern>/parameter</url-pattern>

</servlet-mapping>

</web-app>

Dept. of CSE(Data Science), MVJCE Page 41 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

OUTPUT:

Dept. of CSE(Data Science), MVJCE Page 42 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 10: Write a program in JSP to get and display value from an HTML page.
In JSP, the session is the most regularly used implicit object of type HttpSession. It is mainly
used to approach all data of the user until the user session is active.
Methods used in session Implicit Object are as follows:
Method 1: isNew(): This method is used to check either the session is new or not. Boolean value
(true or false) is returned by it. Primarily it used to trace either the cookies are enabled on client
side or not. If cookies are not enabled then the session.isNew() method should return true all the
time.
Method 2: getId(): While creating a session, the servlet container allots a distinctive string
identifier to the session. This distinctive string identifier is returned by getId method.
Method 3: getAttributeNames(): All the objects stored in the session are returned by
getAttributeNames method. Fundamentally, this method results in an enumeration of objects.
Method 4: getCreationTime(): The session creation time (the time when the session became
active or the session began) is returned by getCreationTime method.
Method 5: getAttribute(String name): Using getAttribute method, the object which is stored by
the setAttribute() method is retrieved from the session. For example, We need to store the
“userid” in session using the setAttribute() method if there is the requirement of accessing userid
on every jsp page until the session is active and when needed it can be accessed using the
getAttribute() method.
Method 6: setAttribute(String, object): The setAttribute method is used to store an object in
session by allotting a unique string to the object. Later, By using the same string this object can
be accessed from the session until the session is active. In JSP, while dealing with session
setAttribute() and getAttribute() are the two most regularly used methods.
Method 7: getMaxInactiveInterval(): The getMaxInactiveInterval return session’s maximum
inactivates time interval in seconds.
Method 8: getLastAccessedTime: The getLastAccessedTime method is mostly used to notice the
last accessed time of a session.
Method 9: removeAttribute(String name): Using removeAttribute(String name) method, the
objects that are stored in the session can be removed from the session.
Method 10: invalidate(): The invalidate() method ends a session and breaks the connection of the
session with all the stored objects.
Implementation:
The ‘index.html’ page given below will display a text box together with a go button. On clicking
go button, the control is transferred to welcome.jsp page. All the outputs are appended at last.

Dept. of CSE(Data Science), MVJCE Page 43 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

The name which is entered by user in the index page is displayed on the welcome.jsp page and it
saves the same variable in the session object so that it can be retrieved on any page till the
session becomes inactive.
index.html

<!DOCTYPE html>

<html>

<head>

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

<title>Get data from HTML Program</title>

</head>

<body>

<form action="Welcome.jsp">

<input type="text" name="uname">

<input type="submit" value="go"><br/>

</form>

</body></html>

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

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>

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

<title>JSP PAGE</title>

</head>

<body>

<%

Dept. of CSE(Data Science), MVJCE Page 44 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

String name=request.getParameter("uname");

out.print("Welcome "+name);

session.setAttribute("user",name);

%>

<a href="Second.jsp">Display the value</a>

</body>

</html>

In second.jsp page, the value of variable is retrieved from the session and displayed.

Second.jsp

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

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>

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

<title>Insert title here</title>

</head>

<body>

<h1>Display the session value on this page</h1>

<%

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

out.print("Hello "+name);

%>

</body>

</html>

Dept. of CSE(Data Science), MVJCE Page 45 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

Web.xml

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

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"


"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app id="WebApp_ID">

<display-name>jspprog</display-name>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

<welcome-file>index.htm</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>default.jsp</welcome-file>

</welcome-file-list>

</web-app>

Dept. of CSE(Data Science), MVJCE Page 46 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

Dept. of CSE(Data Science), MVJCE Page 47 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

Content Beyond Syllabus:


EXPERIMENT 11:

This is a Java Program to Demonstrate a Basic Calculator using Applet

Problem Description
We have to write a program in Java such that it creates a calculator which allows basic operations of
addition, subtraction, multiplication and division.

Expected Input and Output


For creating a calculator, we can have the following different sets of input and output.

To Perform Addition :

When the addition expression "98+102" is typed,

it is expected that the result is displayed as "98+102=200.0".


To Perform Subtraction :

When the subtraction expression "200.0-58.75" is typed,

it is expected that the result is displayed as "200.0-58.75=141.25".


To Perform Multiplication :

When an multiplication expression "141.25*20" is typed,

it is expected that the result is displayed as "141.25*20=2825.0".


To Perform Division : When the denominator is non-zero

When an division expression "2825.0/5" is typed,

it is expected that the result is displayed as "2825.0/5=565.0".


To Perform Division : When the denominator is zero

When an division expression "565.0/0" is typed,

Dept. of CSE(Data Science), MVJCE Page 48 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

it is expected that the error is displayed as "565.0/0=Zero Divison Error".

Problem Solution

1. Create a text field to accept the expression and display the output also.

2. Create buttons for digits and a decimal point.

3. Create a button to clear the complete expression.

4. Create the buttons for operations, that is for addition, subtraction, multiplication and division and an
equals button to compute the result.

5. Add ActionListener to all the buttons.

6. Compute the result and display in the text field.

/*Java Program to Demonstrate a Basic Calculator using Applet*/

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class Calculator extends Applet implements ActionListener

TextField inp;

//Function to add features to the frame

public void init()

setBackground(Color.white);

setLayout(null);

int i;

Dept. of CSE(Data Science), MVJCE Page 49 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

inp = new TextField();

inp.setBounds(150,100,270,50);

this.add(inp);

Button button[] = new Button[10];

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

button[i] = new Button(String.valueOf(9-i));

button[i].setBounds(150+((i%3)*50),150+((i/3)*50),50,50);

this.add(button[i]);

button[i].addActionListener(this);

Button dec=new Button(".");

dec.setBounds(200,300,50,50);

this.add(dec);

dec.addActionListener(this);

Button clr=new Button("C");

clr.setBounds(250,300,50,50);

this.add(clr);

clr.addActionListener(this);

Button operator[] = new Button[5];

Dept. of CSE(Data Science), MVJCE Page 50 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

operator[0]=new Button("/");

operator[1]=new Button("*");

operator[2]=new Button("-");

operator[3]=new Button("+");

operator[4]=new Button("=");

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

operator[i].setBounds(300,150+(i*50),50,50);

this.add(operator[i]);

operator[i].addActionListener(this);

operator[4].setBounds(350,300,70,50);

this.add(operator[4]);

operator[4].addActionListener(this);

String num1="";

String op="";

String num2="";

//Function to calculate the expression

public void actionPerformed(ActionEvent e)

String button = e.getActionCommand();

Dept. of CSE(Data Science), MVJCE Page 51 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

char ch = button.charAt(0);

if(ch>='0' && ch<='9'|| ch=='.')

if (!op.equals(""))

num2 = num2 + button;

else

num1 = num1 + button;

inp.setText(num1+op+num2);

else if(ch=='C')

num1 = op = num2 = "";

inp.setText("");

else if (ch =='=')

if(!num1.equals("") && !num2.equals(""))

double temp;

double n1=Double.parseDouble(num1);

double n2=Double.parseDouble(num2);

if(n2==0 && op.equals("/"))

Dept. of CSE(Data Science), MVJCE Page 52 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

inp.setText(num1+op+num2+" = Zero Division Error");

num1 = op = num2 = "";

else

if (op.equals("+"))

temp = n1 + n2;

else if (op.equals("-"))

temp = n1 - n2;

else if (op.equals("/"))

temp = n1/n2;

else

temp = n1*n2;

inp.setText(num1+op+num2+" = "+temp);

num1 = Double.toString(temp);

op = num2 = "";

else

num1 = op = num2 = "";

Dept. of CSE(Data Science), MVJCE Page 53 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

inp.setText("");

else

if (op.equals("") || num2.equals(""))

op = button;

else

double temp;

double n1=Double.parseDouble(num1);

double n2=Double.parseDouble(num2);

if(n2==0 && op.equals("/"))

inp.setText(num1+op+num2+" = Zero Division Error");

num1 = op = num2 = "";

else

if (op.equals("+"))

temp = n1 + n2;

else if (op.equals("-"))

Dept. of CSE(Data Science), MVJCE Page 54 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

temp = n1 - n2;

else if (op.equals("/"))

temp = n1/n2;

else

temp = n1*n2;

num1 = Double.toString(temp);

op = button;

num2 = "";

inp.setText(num1+op+num2);

/*

<applet code = Calculator.class width=600 height=600>

</applet>

*/

Dept. of CSE(Data Science), MVJCE Page 55 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

OUTPUT:

OUTPUT:

Dept. of CSE(Data Science), MVJCE Page 56 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

EXPERIMENT 12:

Parsing URL

A URL consists of several parts, as follows:

protocol://host:[port]/[path[?params][#anchor]]

The optional parts are shown in [ ]. Examples of protocols include HTTP, HTTPS, FTP, and

File. The path is also called filename, and the host is also referred to as the authority. If a URL

does not specify a port, a default port for the protocol is used. For example, for HTTP, the
default port is 80.

The URL class provides numerous methods to retrieve these parts. For example, we can get

the protocol, authority, host name, port number, path, query, filename, and reference from a URL

using these methods. The following program (ParsingURL.java) prints the different parts of a
URL specified as a command line argument.

HttpURLConnection— A Java class that represents an HTTP connection

InetAddress—A Java class that represents an IP address

Interface addresses—The IP address(es) assigned to a network interface

NetworkInterface —A Java class that represents a network interface

Network Interface—Usually a Network Interface Card (NIC), that acts as a point of


interconnection between a computer and other devices.

Proxy—A class that represents a proxy

ProxySelector—A class used to select a proxy from a list of available proxies

Sub-interface—A child interface of an existing interface

URLConnection—A Java class that represents a connection

URLDecoder—A Java class used to decode a URL

URLEncoder—A Java class used to encode a URL

Dept. of CSE(Data Science), MVJCE Page 57 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

URL—A class that encapsulates the Uniform

Resource Locator (URL), which identifies a resource

in the WWW uniquely

Source code:

import java.net.*;

public class ParsingURL

public static void main(String arg[]) throws Exception

URL obj=new URL(arg[0]);

System.out.println("Protocol "+obj.getProtocol());

System.out.println("Authority"+obj.getAuthority());

System.out.println("host"+obj.getHost());

System.out.println("Port"+obj.getPort());

System.out.println("Default port"+obj.getDefaultPort());

System.out.println("Path"+obj.getPath());

System.out.println("query"+obj.getQuery());

System.out.println("File"+obj.getFile());

System.out.println("Ref"+obj.getRef());

Dept. of CSE(Data Science), MVJCE Page 58 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

OUTPUT:

Dept. of CSE(Data Science), MVJCE Page 59 2021-22


Advanced Java Programming Lab [MVJ20CDL48]

MVJ COLLEGE OF ENGINEERING


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (DATA SCIENCE)

DO'S AND DON'TS

Do's
1. Do wear ID card and follow dress code.
2. Do log off the computers when you finish.
3. Do ask the staff for assistance if you need help.
4. Do keep your voice low when speaking to others in the LAB.
5. Do ask for assistance in downloading any software.
6. Do make suggestions as to how we can improve the LAB.
7. In case of any hardware related problem, ask LAB in charge for solution.
8. if you are the last one leaving the LAB, make sure that the staff in charge of the LAB is informed to
close the LAB.
9. Be on time to LAB sessions.
10. Do Keep the LAB as clean as possible.

Don'ts

1.Do not use mobile phone inside the lab.


2.Don't do anything that can make the LAB dirty (like, eating, throwing waste papers etc.).
3.Do not carry any external devices without permission.
4.Don't move the chairs of the LAB.
5.Don't interchange any part of one computer with another.
6.Don't leave the computers of the LAB turned on while leaving the LAB.
7.Do not install or download any software or modify or delete any system files on any lab
computers.
8.Do not damage, remove, or disconnect any labels, parts, cables, or equipment.
9.Don't attempt to bypass the computer security system.
10. Do not read or modify other users' files.
11.If you leave the lab, do not leave your personal belongings unattended. We are not responsible
for any theft.
Dept. of CSE(Data Science), MVJCE Page 60 2021-22

You might also like