Download Type 1 - csepoint

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

Object-relational impedance mismatch wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Transcript
Programming in Java
Sachin Malhotra, Chairperson,
PGDM-IT, IMS Ghaziabad
Saurabh Chaudhary, Dean,
Academics, IMS Ghaziabad
© Oxford University Press 2010. All rights reserved.
Chapter 16
Introduction to Advanced
Java
© Oxford University Press 2010. All rights reserved.
Objectives
• Handle databases
• Do server side programming with Servlets
• Create remote application using RMI
© Oxford University Press 2010. All rights reserved.
DATABASE HANDLING USING
JDBC
• JDBC stands for Java database connectivity.
• a standard API for all Java programs to connect to
databases. The JDBC API is available in two packages:
– Core API java.sql.
– Standard extension to JDBC API javax.sql (supports connection
pooling, transactions, etc.)
• JDBC defines a few steps to connect to a database and
retrieve/insert/update databases.
• The steps are as follows:
–
–
–
–
–
Load the driver
Establish connection
Create statements
Execute query and obtain result
Iterate through the results
© Oxford University Press 2010. All rights reserved.
Load the Driver
• The latest JDBC 4.0 (works only with Java 6) has parted
away with the manual loading of database driver. It is
now done automatically, but for learning purpose, we will
show you all the steps involved. The driver is loaded with
the help of a static method,
– Class.forName(drivername)
• Every database has its own driver.
• All the JDBC drivers have been classified into four
categories:
–
–
–
–
Type 1: JDBC ODBC bridge driver
Type 2: Native-API/partly Java driver
Type 3: Net-protocol driver
Type 4: Pure Java driver
© Oxford University Press 2010. All rights reserved.
Driver Names
© Oxford University Press 2010. All rights reserved.
JDBC ODBC Bridge Driver
© Oxford University Press 2010. All rights reserved.
Native API/ Partly Java Driver
© Oxford University Press 2010. All rights reserved.
Type 3: Net Protocol Driver
© Oxford University Press 2010. All rights reserved.
Type 4: Pure Java Driver
© Oxford University Press 2010. All rights reserved.
Establish a Connection
• A connection to the database is established using the
static method getConnection(databaseUrl) of the
DriverManager class.
• The DriverManager class is class for managing JDBC
drivers.
• The database URL takes the following shape
jdbc:subprotocol:subname.
• If any problem occurs during accessing the database, an
SQLException is generated, else a Connection object is
returned which refers to a connection to a database.
• Connection is actually an interface in java.sql package.
• Connection
con=DriverManager.getConnection(databaseUrl);
© Oxford University Press 2010. All rights reserved.
Few Database URLs
© Oxford University Press 2010. All rights reserved.
Create Statement
• The connection is used to send SQL statements to the
database.
• three interfaces are used for sending SQL statements to
databases
– Statement and its two sub-interfaces,
– PreparedStatement and Callable Statement.
• Three methods of the Connection object are used to
return objects of these three statements.
• A Statement object is used to send a simple SQL
statement to the database with no parameters.
– Statement stmt = con.createStatement();
© Oxford University Press 2010. All rights reserved.
Create Statement (contd.)
• A PreparedStatement object sends precompiled
statements to the databases with or without IN
parameters.
• If n rows need to be inserted, then the same statement
gets compiled n number of times.
• So to increase efficiency, we use precompiled
PreparedStatement.
• only the values that have to be inserted are sent to the
database again and again.
– PreparedStatement ps = con.prepareStatement(String query);
• A CallableStatement object is used to call stored
procedures.
– CallableStatement cs = con.prepareCall(String query);
© Oxford University Press 2010. All rights reserved.
Execute Query
• Three methods are used
– ResultSet executeQuery(String sqlQuery) throws SQLException
– int executeUpdate(String sqlQuery) throws SQLException
– boolean execute(String sqlQuery) throws SQLException
• executeQuery is used for executing SQL statements that
return a single ResultSet, e.g. a select statement.
– The rows fetched from database are returned as a single
ResultSet object. For example,
– ResultSet rs=stmt.executeQuery(“select * from emp”);
• executeUpdate is used for DDL
and DML SQL
statements like insert,update, delete, and create.
– returns an integer value for DML to indicate the number of rows
affected and 0 for DDL statements which do not return anything.
© Oxford University Press 2010. All rights reserved.
Execute Query (contd.)
– PreparedStatement ps = con.prepareStatement(“update emp set
salary=? where empid=?”);
• The statement is sent to database and is prepared for
execution, only the value of the IN (?) parameters need
to be sent.
– ps.setInt(1,100000);
– ps.setString(2,”Emp001”);
– ps.executeUpdate();
• The execute method is used when the statement may
return more than one ResultSet or update counts or a
combination of both.
• This happens when stored procedures are executed.
© Oxford University Press 2010. All rights reserved.
Iterate ResultSet
•
•
•
•
•
•
while (rs.next())
{
System.out.println(rs.getString(1));
System.out.println(rs.getInt(2));
……..
}
© Oxford University Press 2010. All rights reserved.
Meta Data
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println(“Column in
ResultSet:”+rsmd.getColumnCount());
for(int i=1;i<=rsmd.getColumnCount();i++)
{
System.out.println(“Column Name
:”+rsmd.getColumnName(i));
System.out.println(“Column Type
:”+rsmd.getColumnTypeName (i));
}
© Oxford University Press 2010. All rights reserved.
Example
import java.sql.*;
class DatabaseConnection{
public static void main(String args[]) throws Exception{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection
con=DriverManager.getConnection(“jdbc:odbc:sac”);
PreparedStatement ps=con.prepareStatement(“insert into
emp values (?,?,?)”);
ps.setString(1,”Emp001”);
ps.setString(2,”Peter”);
ps.setInt(3,10000);
System.out.println(“Row inserted : “+ps.execute Update());
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“select * from emp”);
© Oxford University Press 2010. All rights reserved.
Example (contd.)
ResultSetMetaData rsmd=rs.getMetaData();
int cc=rsmd.getColumnCount();
System.out.println(“Number of columns in result set:
“+cc);
for(int i=1;i<=cc;i++)
System.out.print(rsmd.getColumnName(i)+”\t”);
System.out.println();
while(rs.next()){
System.out.print(rs.getString(1)+”\t”);
System.out.print(rs.getString(2)+”\t”);
System.out.print(rs.getString(3)+”\n”);} } }
© Oxford University Press 2010. All rights reserved.
Servlets
• Servlets are Java server-side programs that accept
client’s request (usually http request), process them and
generate (usually http response) responses.
• The requests originate from client’s web browser and are
routed to a servlet located inside an appropriate web
server.
• Servlets execute within a servlet Containers which
resides in a web server like Apache Tomcat.
• Normally HTTP (hyper text transfer protocol) is used
between web client and servlets, but other protocols like
FTP (file transfer protocol) can also be used.
© Oxford University Press 2010. All rights reserved.
Life cycle of Servlets
© Oxford University Press 2010. All rights reserved.
First Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class FirstServlet extends HttpServlet{
public void service(ServletRequest req, Servlet
Response res) throws ServletException,IOException{
res.setContentType(“text/plain”);
PrintWriter pw=res.getWriter();
pw.println(“My First Servlet is running”);
}}}
© Oxford University Press 2010. All rights reserved.
How to run the servlet?
• The First step is to compile the servlet.
• Install a web server or a servlet container.
• The third step is to place the compiled servlet class into
an appropriate directory in the Tomcat.
© Oxford University Press 2010. All rights reserved.
The Output
© Oxford University Press 2010. All rights reserved.
Reading Client Data
• The client’s data is sent to the server from the client’s
browser via two methods of http protocols:
– get and post.
• The get method appends data to the URL (of the servlet
handling the request) and passes it to the server.
• The drawbacks of this approach are:
– The URLs are of fixed size and it puts a restriction on the amount
of data that can be transmitted to the server.
– Moreover, whatever data is sent to the server is visible in clear
text.
• On the other hand, post method overcomes these
limitations by sending data to the server as a part of http
header format instead of appending it to the URL.
© Oxford University Press 2010. All rights reserved.
Methods to fetch data
© Oxford University Press 2010. All rights reserved.
Example
<html>
<head> <title> form data</title></head><body>
<center><h1><U>Registration Form</u></h1>
<form method = get action =
“http://localhost:8080/myproj/servlet/ReadData”>
Name <input type=text name=fname><br>
Address <input type=text name=add><br>
User id <input type=text name=uid><br>
Password <input type=password name=pass><br>
Gender :male <input type=radio name=gender value=male>
female <input type=radio name=gender value=female><br>
Hobbies:Dancing <input type=checkbox name=hobbies
value=dance>
Music <input type=checkbox name=hobbies value=music>
Travel <input type=checkbox name=hobbies value=travel><br>
<input type=submit><input type=reset></center>
</body>
</html>
© Oxford University Press 2010. All rights reserved.
Example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class ReadData extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
res.setContentType(“text/html”);
PrintWriter out=res.getWriter();
Enumeration e=req.getParameterNames();
while(e.hasMoreElements()){
String name=(String)e.nextElement();
String[] values=req.getParameterValues(name);
for(int i=0;i<values.length;i++){
out.println(“<html><head><title> client data</title></head>”);
out.println(“<body><B>”);
out.println(name +” : <i>”+values [i]+”</i><br>”);
out.println(“</body></html>”);}}}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
doGet(req,res);}}
© Oxford University Press 2010. All rights reserved.
The Output
© Oxford University Press 2010. All rights reserved.
The Output
© Oxford University Press 2010. All rights reserved.
Http Redirect
• Http redirect is a way of redirecting a user to another
location on the Internet.
• Http redirect is a way of telling the client’s browser about
the new URL.
• All the requests that arrive on the old URL are redirected
to the new URL.
• res.sendRedirect (“http: // localhost: 8080/ myproj /
Formdata.html”);
© Oxford University Press 2010. All rights reserved.
Cookies
• Cookies are basically small pieces of information stored
on the client’s machine by the browser.
• A cookie contains information like user browsing
preferences, user id and password combinations,
session id, number of times a user has visited a page,
etc.
• This information is stored in pairs, i.e. name-value pairs.
• This information wrapped in a cookie object is sent to the
client browser by a servlet, which stores it somewhere in
its temporary Internet files.
• Whenever a request is sent to that particular server
(from where cookie was downloaded), all the cookies
(stored in the client’s machine from that very server) are
attached to the http request and sent to the server.
© Oxford University Press 2010. All rights reserved.
Example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CookieDemo extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse
res) throws ServletException,IOException{
res.setContentType(“text/html”);
PrintWriter out=res.getWriter();
Cookie c[]=req.getCookies();
if(c==null){
Cookie counts=new Cookie(“Counts”,”1”);
out.println(“<html><head><title> client data</title></head>”);
out.println(“<body><B>”);
out.println(“Welcome <br>”);
out.println(“This is the first time you have visited this page”);
out.println(“</body></html>”);
© Oxford University Press 2010. All rights reserved.
Example
res.addCookie(counts);}
else{
for(int i=0;i<c.length;i++){
String name=c[i].getName();
String val=c[i].getValue();
int accessCount=(Integer.parseInt(val) +1);
out.println(“<html><head><title> client data</title></head>”);
out.println(“<body><B>”);
out.println(“Welcome back<br>”);
out.println(“Number of times you have visited this page:
“+accessCount);
out.println(“</body></html>”);
Cookie counts=new Cookie(name,new
Integer(accessCount).toString());
res.addCookie(counts);}}}
public void doPost(HttpServletRequest req,HttpServletResponse
res) throws ServletException,IOException{
doGet(req,res);}}
© Oxford University Press 2010. All rights reserved.
The output
© Oxford University Press 2010. All rights reserved.
Remote Method Invocation
• RMI client/server applications are used over TCP/IP
networking model.
• In TCP/IP, it is the application layer’s responsibility to
deal with presentation as well as session layer issues.
• So the RMI provides the functionality for these layers
• The presentation layer’s functionality at client and server
is handled by stub and skeleton respectively.
• RRL (Remote Reference Layer) handles the session
layer functionality by managing the session among client
and server.
© Oxford University Press 2010. All rights reserved.
Stub and Skeleton
• Stub is a client-side proxy class, whereas Skeleton is a
server-side proxy class generated by the special, rmic
(rmicompiler).
• Both these classes are generated from the server
(.class) has been compiled by the rmic.
• (The newer version of JRMP protocol has made
Skeleton class obsolete and now it is not generated by
the rmic.
• Functions of Stubs are:
– Marshalling arguments and unmarshalling return values.
– Informs the RRL that a call should be invoked on the server.
– Informs the RRL that the call is complete.
• The functions performed by Skeleton are:
– Marshalling return values and unmarshalling arguments.
– Invoking the actual remote object implementation.
© Oxford University Press 2010. All rights reserved.
RMI over TCP/IP
© Oxford University Press 2010. All rights reserved.
Creating a RMI Application
• An interface needs to be created which would contain
the definition of the methods that can be invoked
remotely.
• Create a Server class that provides the implementation
of the methods in the interface.
• Generate Stubs using rmic.
• A client to invoke the remote methods.
• Run RMI registry.
• Run server and client.
© Oxford University Press 2010. All rights reserved.
Creating an Interface
import java.rmi.*;
public interface Calculation extends Remote{
public double remainder(double a, double b) throws
RemoteException;
public double cube(double a) throws RemoteException;}
© Oxford University Press 2010. All rights reserved.
RMI Server
import java.rmi.*;
import java.rmi.server.*;
public class Server extends UnicastRemoteObject implements
Calculation{
public Server() throws RemoteException{
super();}
public double remainder(double a,double b) throws
RemoteException{
return a%b;}
public double cube(double a) throws RemoteException{
return a*a*a;}
public static void main(String args[]) throws Exception{
try{
Server s=new Server();
System.out.println(“Object created”);
Naming.rebind(“rmi://localhost/Calculator”,s);
System.out.println(“Object Registered”);}
catch(Exception e){System.out.println(e);}}}
© Oxford University Press 2010. All rights reserved.
RMIRegistry & rmic
• RMI registry
– helps to locate a remote object whose methods it wishes to
invoke.
– a name service which keeps an association of simple names to
their corresponding remote objects.
– runs on the same machine as that of RMI server.
– objects must register itself by a name on the registry service.
– Client look up the registered name in the registry service and get
a reference to the remote object in return.
• Stub
– The stub class is generated by a special rmicompiler (rmic). The
Server class is first compiled and then, the rmic is used on the
compiled Server class.
– The stub class generated has the following name:
<Servername>_Stub.class.
© Oxford University Press 2010. All rights reserved.
Client
import java.rmi.*;
public class Client{
public static void main(String args[]) throws Exception{
Calculation
c=(Calculation)Naming.lookup(“rmi://localhost/Calculator
”);
System.out.println(“Remainder of 3.2 % 3.2:
“+c.remainder(3.2,3.2));
System.out.println(“Cube of 3.2: “+c.cube(3.2));
}}
© Oxford University Press 2010. All rights reserved.
The Output
C:\javabook\programs\CHAP15~1\rmiserver>java Server
Object created
Object Registered
C:\javabook\programs\chap 15\rmiclient>java Client
Remainder of 3.2 % 3.2: 0.0
Cube of 3.2: 32.76800000000001
© Oxford University Press 2010. All rights reserved.
Summary
• In this chapter, we have learnt about some of the
concepts of advanced Java such as servlets, JDBC, and
RMI.
• Servlets are used for generating responses for clients,
based on the requests received.
• JDBC API deals with a variety of databases for storing
and manipulating data within them.
• Java RMI is the solution for RPC, where a Java program
on remote machine can be called from a Java client
program.
• Basically, RMI helps in distributed computing.
© Oxford University Press 2010. All rights reserved.