AJP Lab Manual (1) - 1
AJP Lab Manual (1) - 1
Theory:
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet -
Drawback of Applet -
o Plugin is required at client browser to execute applet.
Hierarchy of Applet –
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized.
It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop
or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. By html file.
2. By appletViewer tool (for testing purpose).
The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package, and
it has three methods.
Interface declaration -
Following is the declaration for java.awt.event.KeyListener interface:
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 2
AWT
Theory:
AWT provides various components like button, label, checkbox, etc. used as objects
inside a Java Program. AWT components use the resources of the operating system,
i.e., they are platform-dependent, which means, component's view can be changed
according to the view of the operating system. The classes for AWT are provided by
the Java.awt package for various AWT components.
Java MouseListener Interface -
The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent. The MouseListener interface is found in java.awt.event
package. It has five methods.
ELO :Student will be able to implement various mouse events on frame using AWT.
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 3
GUI
Title:Develop GUI application.
Aim:Develop a GUI which accepts the information regarding the marks for all the
subjects of a student in the examination. Display the result for a student in a separate
window.
Theory:
GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for
Java applications. It is mainly made of graphical components like buttons, labels,
windows, etc. through which the user can interact with an application. GUI plays an
important role to build easy interfaces for Java applications.
Java BorderLayout -
A BorderLayout places components in up to five areas: top, bottom, left, right, and
center. It is the default layout manager for every java JFrame
Java FlowLayout -
FlowLayout is the default layout manager for every JPanel. It simply lays out
components in a single row one after the other.
Java GridBagLayout
It is the more sophisticated of all layouts. It aligns components by placing them within
a grid of cells, allowing components to span more than one cell.
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 4
JDBC
Aim: Write a program to insert and retrieve the data from the database using JDBC.
Theory:
To establish a connection with MySQL in JDBC, first we have to install MySQL on
our system and we have to add the MySQL connector (it is a .jar file containing the
classes that are the implementation of interfaces provided by Sun Microsystems ) to
our class path variable. After doing this the classes implementing the interfaces
provided by Sun Microsystem are available to our program.
How to add MySql connector to our class path variable: There are two approaches for
adding the MySQL connector to our class path variable. Both are given below.
For example, the given image is helpful for understanding the syntax
Adding MySQL connector permanently –
Go to My Computer and after right clicking, select the Properties option and click
on that.
System Properties window will open, select Advanced option and the following
window will open.
Select Environment Variable option and the following window will open.
Select the class path variable (left click) and click on Edit button and the following
window will open.
In the System Variable window, go to the end of Variable value option and place a
semicolon, after that add the path of connector followed by semicolon and click on the
ok button.
Creating database in MySQL and granting it all privileges: To perform this we follow
the following steps
Open MySQL and enter the password after this my mysql> prompt will open
Create a database with the following command
Granting a user name, password and all privileges with the following command
Now our MySQL database is ready for creating a connection with JDBC.
1. import java.sql.*;
2. public class MySQLdatabase {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con =
DriverManager.getConnection("jd
bc:mysql://localhost/sqldatabase", "amit", "amitabh");
7. Statement s = con.createStatement();
8. s.execute("create table student ( stud_id
intege r,stud_name varchar(20),stud_address
varchar(30) )"); // cre
ate a table
9. s.execute("insert into student
values(001,'ARman
','Delhi')"); // insert first row into the table
10. s.execute("insert into student
values(002,' Robert','Canada')"); // insert second row
into the table
11. s.execute("insert into student
values(003,'
Ahuja','Karnal')"); // insert third row into the table
12. ResultSet rs = s.executeQuery("select *
fro m student");
13. if (rs != null) // if rs == null, then
ther
e is no record in ResultSet to show
14. while (rs.next()) // By this line
we wi ll step through our data row-by-row
15. {
16. System.out.println("
");
17. System.out.println("Id of the
student:
" + rs.getString(1));
18. System.out.println("Name of student:
"
+ rs.getString(2));
19. System.out.println("Address of
student:
" + rs.getString(3));
20. System.out.println("
");
21. }
22. s.close(); // close the Statement to
let th e database know we're done with it
23. con.close(); // close the Connection to
let
the database know we're done with it
24. } catch (SQLException err) {
25. System.out.println("ERROR: " + err);
26. } catch (Exception err) {
27. System.out.println("ERROR: " + err);
28. }
29. }
30. }
After executing this program we can see the following output on the console
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 5
RMI
Title: Develop RMI application.
Aim: Develop an RMI application which accepts a string or a number and checks that string or
number is palindrome or not.
Theory:
RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one
system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.
Architecture of an RMI Application -
In an RMI application, we write two programs, a server program (resides on the server) and a client
program (resides on the client).
Inside the server program, a remote object is created and reference of that object is made
available for the client (using the registry).
The client program requests the remote objects on the server and tries to invoke its methods.
The following diagram shows the architecture of an RMI application.
Let us now discuss the components of this architecture.
Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.
Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client
system; it acts as a gateway for the client program.
Skeleton − This is the object which resides on the server side. stub communicates with this
skeleton to pass request to the remote object.
RRL(Remote Reference Layer) − It is the layer which manages the references made by the
client to the remote object.
Working of an RMI Application
The following points summarize how an RMI application works −
When the client makes a call to the remote object, it is received by the stub which eventually
passes this request to the RRL.
When the client-side RRL receives the request, it invokes a method called invoke() of the
object remoteRef. It passes the request to the RRL on the server side.
The RRL on the server side passes the request to the Skeleton (proxy on the server) which
finally invokes the required object on the server.
The result is passed all the way back to the
client. Marshalling and Unmarshalling -
Whenever a client invokes a method that accepts parameters on a remote object, the parameters are
bundled into a message before being sent over the network. These parameters may be of primitive
type or objects. In case of primitive type, the parameters are put together and a header is attached to
it. In case the parameters are objects, then they are serialized. This process is known as marshalling.
At the server side, the packed parameters are unbundled and then the required method is invoked.
This process is known as unmarshalling.
RMI Registry -
RMI registry is a namespace on which all server objects are placed. Each time the server creates an
object, it registers this object with the RMIregistry (using bind() or reBind() methods). These are
registered using a unique name known as bind name.
To invoke a remote object, the client needs a reference of that object. At that time, the client fetches
the object from the registry using its bind name (using lookup() method).
The following illustration explains the entire process –
Goals of RMI -
Following are the goals of RMI −
Algorithm –
Server side -
Step 1: Start
Step 2: Define the class rmiserver
Step 3: Create the object twox in try
Step 4: Register the object twox
Step 5: Display the exception in catch
Step 6: Stop
Algorithm –
Client side -
Step 1: Start
Step 2: Define the class rmiclient
Step 3: Initialize the string s1 in try
Step 4: Create and Initialize the object onex
Step 5: Assign the value to m by calling the method palin
Step 6: Check whether the string is palindrome or not
Step 7: Display whether the string is palindrome or not
Step 8: Display the exception in catch
Step 9: Stop
Program -
one.java
importjava.rmi.*;
two.java
importjava.rmi.*;
importjava.lang.*;
importjava.rmi.server.*;
public class two extends UnicastRemoteObject implements one
{
public two() throws RemoteException { }
publicintpalin(String a) throws RemoteException
{
System.out.println("Hello");
rmiserver.java
import java.io.*;
importjava.rmi.*;
import java.net.*;
public class rmiserver
{
public static void main(String args[]) throws Exception
{
try
{
twotwox = new two();
Naming.bind("palin", twox);
System.out.println("Object registered");
}
catch(Exception e)
{
System.out.println("Exception" + e);
}
}
}
rmiclient.java
import java.io.*;
import java.rmi.*;
import java.net.*;
public class rmiclient
{
public static void main(String args[]) throws Exception
{
try
{
String s1 = "rmi://localhost/palin";
one onex = (one)Naming.lookup(s1);
int m = onex.palin("madam");
System.out.println("Print : " + m);
if (m == 1)
{
System.out.println("The given string is a Palindrome");
}
else
{
System.out.println("The given string is not a Palindrome");
}
}
catch (Exception e)
{
System.out.println("Exception" + e);
}
}
}
Output –
Server side -
Client side –
ELO :Student will be able to check whether given string is palindrome or not using RMI.
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 6
Inet Address class
Aim:Write a program to demonstrate the use of Inet Address class and its factory methods.
Theory:
Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to
get the IP of any host name for example www.javatpoint.com, www.google.com,
www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress
represents the IP address with its corresponding host name. There are two types of addresses:
Unicast and Multicast. The Unicast is an identifier for a single interface whereas Multicast is an
identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name
resolutions.
IP Address -
o Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual
bridge among the destination and the source.
1. IPv4
IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the
ARAPNET in 1983. It is a widely used IP version to differentiate devices on network using an
addressing scheme. A 32-bit addressing scheme is used to store 2 32 addresses that is more than 4
million addresses.
Features of IPv4:
o It is a connectionless protocol.
o It utilizes less memory and the addresses can be remembered easily with the class based
addressing scheme.
o It also offers video conferencing and libraries.
2. IPv6
IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet addresses. It
provides solutions for the problems present in IPv4. It provides 128-bit address space that can be
used to form a network of 340 undecillion unique IP addresses. IPv6 is also identified with a name
IPng (Internet Protocol next generation).
Features of IPv6:
TCP/IP Protocol
o TCP/IP is a communication protocol model used connect devices over a network via internet.
o TCP/IP helps in the process of addressing, transmitting, routing and receiving the data
packets over the internet.
1. TCP i.e. Transmission Control Protocol. TCP provides the way to create a
communication channel across the network. It also helps in transmission of packets at
sender end as well as receiver end.
2. IP i.e. Internet Protocol. IP provides the address to the nodes connected on the
internet. It uses a gateway computer to check whether the IP address is correct and the
message is forwarded correctly or not.
InetAddress – Factory Methods :
o The InetAddress class is used to encapsulate both, the numerical IP address and the
domain name for that address. The InetAddress class has no visible constructors. The
InetAddress class has the inability to create objects directly, hence factory methods are
used for the purpose. Factory Methods are static methods in a class that return an object of
that class.
o There are 5 factory methods available in InetAddress class –
Methods –
Program –
import java.io.*;
import java.net.*;
importjava.util.*;
class GFG {
public static void main(String[] args)
throwsUnknownHostException
{
// To get and print InetAddress of Local Host
InetAddress address1 = InetAddress.getLocalHost();
System.out.println("InetAddress of Local Host : "
+ address1);
Output –
ELO : Student will be able to implement factory methods of Inet address class.
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 7
RMI Server
Title:Develop remote interface and implement RMI server.
Aim:Write program with suitable example to develop your remote interface, implement your RMI
server, implement application that create your server, also develop security policy file.
Theory:
To write an RMI Java application, you would have to follow the steps given below −
publicclassServerextendsImplExample{ pu
blicServer(){}
publicstaticvoid main(Stringargs[]){
try{
// Instantiating the implementation class
ImplExampleobj=newImplExample();
registry.bind("Hello", stub);
System.err.println("Server ready");
}catch(Exception e){
System.err.println("Server exception: "+e.toString());
e.printStackTrace();
}
}
}
Developing the Client Program
Write a client program in it, fetch the remote object and invoke the required method using this
object.
To develop a client program −
Create a client class from where your intended to invoke the remote object.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which
belongs to the package java.rmi.registry.
Fetch the object from the registry using the method lookup() of the class Registry which
belongs to the package java.rmi.registry.
To this method, you need to pass a string value representing the bind name as a parameter.
This will return you the remote object.
The lookup() returns an object of type remote, down cast it to the type Hello.
Finally invoke the required method using the obtained remote object.
Following is an example of an RMI client program.
importjava.rmi.registry.LocateRegistry;
importjava.rmi.registry.Registry;
publicclassClient{ privateClient(){}
publicstaticvoid main(String[]args){ try{
// Getting the registry
Registryregistry=LocateRegistry.getRegistry(null);
javac *.java
Executing the Application
Step 1 − Start the rmi registry using the following command.
startrmiregistry
Verification − As soon you start the client, you would see the following output in the server.
ELO:Student will be able to demonstrate concept of remote interface, and create a RMI server
along with security file in java.
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 8
Database application
How to add MySql connector to our class path variable: There are two approaches for adding the
MySQL connector to our class path variable. Both are given below.
For example, the given image is helpful for understanding the syntax
Creating database in MySQL and granting it all privileges: To perform this we follow the following
steps
Open MySQL and enter the password after this my mysql> prompt will open
Now our MySQL database is ready for creating a connection with JDBC.
31 import
.
32 java.sql.*;
public class
.
33 MySQLdatabase
public static{ void main(String[]
.
34 args)
try{
.
35 { Class.forName("com.mysql.jdbc.Driver
.
36 ");
Connection con =
. n("jdbc:mysql://localhost/sqldatabase",
DriverManager.getConnectio "amit",
"amitabh");
37 Statement s =
.
38 con.createStatement();
s.execute("create table student (
. nteger,stud_namestud_id i
varchar(20),stud_address varchar(30)
)"); /
39 / create a tables.execute("insert into student
. values(001,'
40 ARman','Delhi')"); // insert firstinto
s.execute("insert row student
into the table
. Robert','Canada')");
values(002,'
// insert second row into the
41 table s.execute("insert into student
. Ahuja','Karnal')");
values(003,'
// insert third row into the
table
42. ResultSet rs = s.executeQuery("select *
fro
m student");
43. if (rs != null) // if rs == null, then
ther e is no record in ResultSet to show
44. while (rs.next()) // By this line we
wi
ll step through our data row-by-row
45. {
46. System.out.println("
");
47. System.out.println("Id of the
student:
" + rs.getString(1));
48. System.out.println("Name of student:
"
+ rs.getString(2));
49. System.out.println("Address of
student: " + rs.getString(3));
50. System.out.println("
");
51. }
52. s.close(); // close the Statement to
let th e database know we're done with it
53. con.close(); // close the Connection to
let
the database know we're done with it
54. } catch (SQLException err) {
55. System.out.println("ERROR: " + err);
56. } catch (Exception err) {
57. System.out.println("ERROR: " + err);
58. }
59. }
60. }
After executing this program we can see the following output on the console
After executing this program we can see our table in MySQL as
ELO: Student will be able to write database application that uses JDBC driver.
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 9
JSP
Aim:Write a simple JSP page to display a simple message (It may be a simple html page).
Theory:
JSP technology is used to create web application just like Servlet technology. It can be thought of as
an extension to Servlet because it provides more functionality than servlet such as expression
language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet
because we can separate designing and development. It provides some additional features such as
Expression Language, Custom Tags, etc.
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation logic.
In Servlet technology, we mix our business logic with the presentation logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code needs
to be updated and recompiled if we have to change the look and feel of the application.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page -
To create the first JSP page, write some HTML code as given below, and save it by .jsp extension.
We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory
in apache tomcat to run the JSP page.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the JSP
page.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
No, there is no need of directory structure if you don't have class files or TLD files. For example, put
JSP files in a folder directly and deploy that folder. It will be running fine. However, if you are using
Bean class, Servlet or TLD file, the directory structure is required.
The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB- INF
folder or in any directory.
ELO :Student will be able to create JSP page to display a simple message.
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 10
Calculator Application
Title: Implementation of calculator using servlet.
Aim: Create a simple calculator application using servlet.
Theory:
Servlet technology is used to create a web application (resides at server side and generates a dynamic
web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was common as a server-side programming language.
However, there were many disadvantages to this technology. There are many interfaces and classes
in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse,
etc.
What is servlet –
o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page.
Calculator App
Program –
Enter First Number <input type="text" name="txtN1" ><br> Enter Second Number <input
type="text" name="txtN2" ><br> Select an Operation
<input type="radio" name="opr" value="+">ADDTION
<input type="radio" name="opr" value="*">MULTIPLY <input type="radio" name="opr"
value="/">DIVIDE
<input type="radio" name="opr" value="-">Substraction
<br><input type="reset">
<input type="submit" value="Calculate" >
</form>
</body>
</html
Step 3: Add a new Servlet to source package
-Name the servlet and package
-Check “Add information to deployment descriptor” to add servlet into web.xml But preferably use
annotation.
CalculatorServlet.java
Program-
packagemypack;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
out.println("<html><head><title>Servlet CalculatorServlet</title></head><body>");
double n1 = Double.parseDouble(request.getParameter("txtN1"));
double n2 = Double.parseDouble(request.getParameter("txtN2"));
double result =0;
String opr=request.getParameter("opr");
if(opr.equals("+")) result=n1+n2;
if(opr.equals("-")) result=n1-n2;
if(opr.equals("*")) result=n1*n2;
if(opr.equals("/")) result=n1/n2;
Output:
Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------