Vous êtes sur la page 1sur 26

PRACTICAL: - 1

AIM: -STUDY BASIC CONCEPT OF JDBC.

Java JDBC is a java API to connect and execute query with the database. JDBC API uses
jdbc drivers to connect with the database.

Why use JDBC?

Before JDBC, ODBC API was the database API to connect and execute query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).

JDBC Driver: -
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
Steps to connect to the database in java: -
There are 5 steps to connect any java application with the database in java using JDBC.
They are as follows:
• Register the driver class
• Creating connection
• Creating statement
• Executing queries
• Closing connection

1
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used
to dynamically load the driver class.
Syntax of forName() method
1. public static void forName(String className)throws ClassNotFoundException

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

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection
with the database.
Syntax of getConnection() method
1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement.
The object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
1. public Statement createStatement()throws SQLException

1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to
the database. This method returns the object of ResultSet that can be used to get all
the records of a table.
Syntax of executeQuery() method
1. public ResultSet executeQuery(String sql)throws SQLException

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


2.
3. while(rs.next()){

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

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
Syntax of close() method
1. public void close()throws
SQLException Example to close
connection con.close();

3
PRACTICAL: - 2
AIM:- DEVELOPING A PROGRAM THROUGH JDBC
import java.sql.*;
import java.util.*;
class Main
{
public static void main(String a[])
{
//Creating the connection
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String pass = "12345";

//Entering the data


Scanner k = new Scanner(System.in);
System.out.println("enter name");
String name = k.next();
System.out.println("enter roll no");
int roll = k.nextInt();
System.out.println("enter class");
String cls = k.next();

//Inserting data using SQL query


String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
Connection con=null;
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

//Reference to connection interface


con = DriverManager.getConnection(url,user,pass);

Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println("inserted successfully :
"+sql); else
System.out.println("insertion failed");
con.close();
}
catch(Exception ex)
{
System.err.println(ex);
}
}
}

4
OUTPUT: -

5
PRACTICAL: - 3
AIM: -HISTORY OF SERVLET.
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a request coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

1. Performance is significantly better.

2. Servlets execute within the address space of a Web server. It is not necessary to create
a separate process to handle each client request.

3. Servlets are platform-independent because they are written in Java.

4. Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So, servlets are trusted.

5. The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.

Servlets Packages: -

Java Servlets are Java classes run by a web server that has an interpreter that supports the
Java Servlet specification.

Servlets can be created using the javax.servletand javax.servlet.httppackages, which are a


standard part of the Java's enterprise edition, an expanded version of the Java class library
that supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of writing this
tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

6
Servlets Life-Cycle: -

A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet

1. The servlet is initialized by calling the init () method.

2. The servlet calls service() method to process a client's request.

3. The servlet is terminated by calling the destroy() method.

Finally, servlet is garbage collected by the garbage collector of the JVM.

The init() Method: -

The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as with
the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as appropriate.
The init() method simply creates or loads some data that will be used throughout the life of
the servlet.

The init method definition looks like this:

public void init() throws ServletException {


// Initialization code...
}

The service() Method :-

The service() method is the main method to perform the actual task. The servlet container
(i.e. web server) calls the service() method to handle requests coming from the client(
browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

public void service(ServletRequest request,

7
ServletResponse response)
throwsServletException, IOException{
}
The service () method is called by the container and service method invokes doGe, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service()
method but you override either doGet() or doPost() depending on what type of request you
receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.

The doGet() Method:-

A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throwsServletException, IOException {
// Servlet code
}

8
PRACTICAL: - 4
AIM: - PROGRAM OF CALLING ONE SERVLET BY
ANOTHER SERVLET
RequestDispatcher2.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class RequestDispatcher2 extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html><body>");
String s="before dispatcher";
out.println(s);
try
{

RequestDispatcher rd=req.getRequestDispatcher("/run2");
rd.include(req,res);

}
catch(Exception e)
{
out.println("exception");
}
System.out.println("after dispatcher");
System.out.println("</body></html>");
}
}

DemoServlet2.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet2 extends
GenericServlet {
public void service(ServletRequest req, ServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");

9
PrintWriter out=res.getWriter();
out.println("<html><body>");
out.println("hello servlet with GenericServlet");
out.println("</body></html>");
}
}

Web.xml

<web-app>
<servlet>
<servlet-name>RequestDispatcher2</servlet-name>
<servlet-class>RequestDispatcher2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RequestDispatcher2</servlet-name>
<url-pattern>/run7</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DemoServlet2</servlet-name>
<servlet-class>DemoServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet2</servlet-name>
<url-pattern>/run2</url-pattern>
</servlet-mapping>
</web-app>

10
OUTPUT:

11
PRACTICAL: - 5

AIM: - STUDY BASIC CONCEPT OF JAVA SERVER PAGES.

Java Server Pages (JSP) is a technology for developing Webpages that supports dynamic
con-tent. This helps developers insert java code in HTML pages by making use of special
JSP tags, most of which start with <% and end with %>.

A Java Server Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.

Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control
between pages, and sharing information between requests, pages etc.

Why Use JSP?


Java Server Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.

• Performance is significantly better because JSP allows embedding Dynamic Elements


in HTML Pages itself instead of having separate CGI files.

• JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time the
page is requested.

• Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also
has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB,
JAXP, etc.

• JSP pages can be used in combination with servlets that handle the business logic, the
model supported by Java servlet template engines.

Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the most
complex and demanding.

12
Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −
vs. Active Server Pages (ASP)
The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it is
portable to other operating systems and non-Microsoft Web servers.

vs. Pure Servlets


It is more convenient to write (and to modify!) regular HTML than to have plenty of println
statements that generate the HTML.

vs. Server-Side Includes (SSI)


SSI is really only intended for simple inclusions, not for "real" programs that use form data,
make database connections, and the like.

vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.

vs. Static HTML


Regular HTML, of course, cannot contain dynamic information.

A JavaBean is a specially constructed Java class written in the Java and coded according to
the JavaBeans API specifications.

Following are the unique characteristics that distinguish a JavaBean from other Java classes

• It provides a default, no-argument constructor.

• It should be serializable and that which can implement the Serializable interface.

• It may have a number of properties which can be read or written.

• It may have a number of "getter" and "setter" methods for the properties.

JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the object. The
attribute can be of any Java data type, including the classes that you define.

13
A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class −

S.No. Method & Description

getPropertyName()
1
For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.

setPropertyName()

2 For example, if property name is firstName, your method name would


be setFirstName() to write that property. This method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only


attribute will have only a setPropertyName() method.

Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes
a scripting variable that can be accessed by both scripting elements and other custom tags
used in the JSP. The full syntax for the useBean tag is as follows −

<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>

Here values for the scope attribute can be a page, request, session or application based on
your requirement. The value of the id attribute may be any value as a long as it is a unique
name among other useBean declarations in the same JSP.

14
PRACTICAL: - 6

AIM: -PROGRAM TO DISPLAY MESSAGE ON BROWSER USING JSP

Init.jsp

<html>
<body>
<%!
String s;
public void jspInit()
{
ServletConfig con=getServletConfig();
s=con.getInitParameter("name");
}
%>

<%
String s1=config.getInitParameter("name");
out.println(s+s1);
%>
</body>
</html>

Web.xml

<web-app>
<servlet>
<servlet-name>my</servlet-name>
<jsp-file>Init.jsp</jsp-file>
<init-param>
<param-name>name</param-name>
<param-value> i miss you</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>my</servlet-name>
<url-pattern>/run</url-pattern>
</servlet-mapping>
</web-app>
</body>
</html>

15
OUTPUT:

16
PRACTICAL: - 7
AIM: - INTRODUCTION TO JAVA BEANS
Software components are self-contained software units developed according to the motto
“Developed them once, run and reused them everywhere”. Or in other words, reusability is
the main concern behind the component model. A software component is a reusable object
that can be plugged into any target software application. You can develop software
components using various programming languages, such as C, C++, Java, and Visual Basic.

• A “Bean” is a reusable software component model based on sun’s java bean specification
that can be manipulated visually in a builder tool.

• The term software component model describe how to create and use reusable software
components to build an application

• Builder tool is nothing but an application development tool which lets you both to create
new beans or use existing beans to create an application.

• To enrich the software systems by adopting component technology JAVA came up


with the concept called Java Beans.

Advantages of Java Beans:

• The java beans posses the property of “Write once and run anywhere”.

• Beans can work in different local platforms.

• Beans have the capability of capturing the events sent by other objects and vice
versa enabling object communication.

• The properties, events and methods of the bean can be controlled by the application
developer.(ex. Add new properties)

• Beans can be configured with the help of auxiliary software during design time.(no
hassle at runtime)

What can we create by using JavaBean: There is no restriction on the capability of a


Bean.

• It may perform a simple function, such as checking the spelling of a document, or a


complex function, such as forecasting the performance of a stock portfolio. A Bean may
be visible to an end user. One example of this is a button on a graphical user interface.

• Software to generate a pie chart from a set of data points is an example of a Bean that
can execute locally.

• Bean that provides real-time price information from a stock or commodities exchange.

17
JavaBeans basic rules

A JavaBean should:

be public

implement the Serializable interface

have a no-arg constructor

be derived from javax.swing.JComponent or java.awt.Component if it is visual

The classes and interfaces defined in the java.beans package enable you to create JavaBeans.
The Java Bean components can exist in one of the following three phases of development:

 Construction
 Build phase
 Execution phase
It supports the standard component architecture features of

• Properties

• Events

• Methods

• Persistence. In addition Java Beans provides support for

• Introspection (Allows Automatic Analysis of a java beans)

• Customization (To make it easy to configure a java beans component)

The JavaBean Component Specification:

Customization: Is the ability of JavaBean to allow its properties to be changed in build


and execution phase.

Persistence: - Is the ability of JavaBean to save its state to disk or storage device and restore
the saved state when the JavaBean is reloaded.

Communication :-Is the ability of JavaBean to notify change in its properties to


other JavaBeans or the container.

Introspection: - Is the ability of a JavaBean to allow an external application to query the


properties, methods, and events supported by it.

18
Services of JavaBean Components

Builder support: - Enables you to create and group multiple JavaBeans in an application.
Layout: - Allows multiple JavaBeans to be arranged in a development environment. Interface
publishing: Enables multiple JavaBeans in an application to communicate with each other.
Event handling: - Refers to firing and handling of events associated with a JavaBean.
Persistence: - Enables you to save the last state of JavaBean.

Features of a JavaBean

• Support for “introspection” so that a builder tool can analyze how a bean works.

• Support for “customization” to allow the customization of the appearance and behavior
of a bean.

• Support for “events” as a simple communication metaphor than can be used to connect
up beans.

• Support for “properties”, both for customization and for programmatic use.

• Support for “persistence”, so that a bean can save and restore its customized state.

19
PRACTICAL: -8
AIM: -PROGRAM TO SET SCOPE OF BEANS

MyBean.java

package my;
public class MyBean
{
private String name;
private int pass;
public void setName(String name)
{
this.name=name;
}
public void setPass(int pass)
{
this.pass=pass;
}
public String getName()
{
return name;
}
public int getPass()
{
return pass;
}

public String validate()


{
try
{
if(name.equals("ducat"))
return "valid";
}
catch(Exception e){}
return "invalid";
}

public int add(int x,int y)


{
return x+y;
}
}

20
Bean.jsp

<jsp:useBean id="t1" class="my.MyBean" scope="session"/>


<jsp:setProperty name="t1" property="*" param="name"/>

<%
String s=t1.validate();
int r=t1.add(10,20);
out.println(s+r);
%>

<jsp:getProperty name="t1" property="name"/>


<jsp:getProperty name="t1" property="pass"/>

Index.jsp

<html>
<body>
<form action="Bean.jsp">
enter your name:
<input type="text" name="name">
<br>
enter your password:
<input type="password" name="pass"/>
<br>
<input type="submit"/>
</body>
</html>

21
OUTPUT:

22
PRACTICAL: - 9

AIM: - TO STUDY BASICS OF RMI


The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM.

The RMI provides remote communication between the applications using two
objects stub and skeleton.

Understanding stub and skeleton: -

RMI uses stub and skeleton object for communication with the remote object.

A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:

Stub

The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the caller
invokes method on the stub object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

Skeleton

The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does the
following tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.

23
\

Understanding requirements for the distributed applications:-

If any application performs these tasks, it can be distributed application.

1. The application need to locate the remote method


2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.

The RMI application have all these features, so it is called the distributed application.

24
PRACTICAL: - 10

AIM: - DEVELOPMENT OF A PROGRAM USING RMI


Adder.java-
import java.rmi.*;
public interface Adder extends Remote{

public int add(int x,int y)throws RemoteException;


}
AdderRemote.java-
import java.rmi.*;
import java.rmi.server.*;

public class AdderRemote extends UnicastRemoteObject implements Adder{

AdderRemote()throws RemoteException{
super();
}

public int add(int x,int y){return x+y;}

}
MyClient.java-
import java.rmi.*;

public class MyClient{

public static void main(String args[]){


try{

Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));

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

}
MyServer.java-
import java.rmi.*;
import java.rmi.registry.*;

public class MyServer{

public static void main(String args[]){


try{

Adder stub=new AdderRemote();


Naming.rebind("rmi://localhost:5000/sonoo",stub);

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

25
OUTPUT: -

26

Vous aimerez peut-être aussi