Record 2 Final

  • Uploaded by: Ramaguru Radhakrishnan
  • 0
  • 0
  • April 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Record 2 Final as PDF for free.

More details

  • Words: 2,712
  • Pages: 37
JAVA SERVLETS

Ex.no:7 HTML FORM PROCESSING USING SERVLETS Aim: 1. To design a HTML form which contains various fields. 2. On submission of HTML form a servlet is invoked which processes the data entered by the user & display it in a tabular format. Steps: Serve1.java 1) In order to develop a Httpservlet import the two necessary packages which provides Http functionality. package p1; import java.io.*; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; 2) Every Httpservlet application must be a subclass of predefined Httpservlet class. public class second extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 3) Receive all the values entered by the user & store it an enumeration object using getParameterNames in HttpRequest object. Enumeration e=request.getParameterNames(); 4) Use the getWriter method present in the HTTPRequest interface to create a PrintWriter object. PrintWriter out=response.getWriter(); 5) Insert table tags in the servlet to display header information & close the first row. out.println(""+"") 6) To display parameter names & values two methods are used. i) hasMoreElements() present in enumeration interface

- Whose return value is a Boolean. - loops until there is no object in enumeration interface. ii) nextElement()-moves from one object to the next object. getParameter() method retrieves the value of the control in HTML form while(e.hasMoreElements()) { String p= (String)e.nextElement(); String s1=request.getParameter(pname); 7) Insert second row of table tag to display the values. out.println(""+""); } out.println("
PnamePvalue
"+p+""+s1+"
"); } }

Coding: table.html
Enter your name:


anychange:
Yes
No


fav place:
<select name=n1>


Serve1.java import java.io.*; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class firstservlet extends HttpServlet { private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); out.println(""); Enumeration e=request.getParameterNames(); while(e.hasMoreElements()) { String p=(String) e.nextElement(); String s1=request.getParameter(p); out.println(""+""); } out.println("
parametervalue
"+p+""+s1+"
"); } }

Output:

Result: Thus an html form containing various fields is processed using Servlets.

JAVA NETWORKING

Ex.no:8

CLIENT SERVER APPLICATION USING UDP SOCKETS Aim: To write a java program using UDP Sockets to send a message from server to client UDP sockets overview: Two classes in java which enables communication using datagrams •

DatagramPacket is the class which acts as data container.



DatagramSocket is a mechanism used to send and receive data.

Datagram Packet Constructors: 1. DatagramPacket(byte data[], int size)

2. Datagram

Packet(byte

data[],

int

//used for receiving the data size,

InetAddress

address,

int

portno)//used for sending the data Datagram Socket DatagramPacket does not provide any methods to send or receive data.this job is taken by the DatagramSocket class. Constructors: 1. DatagramSocket s=new DatgramSocket(); 2. DatagramSocket s1=new DatagramSocket(int port); Methods in Datagram Socket: send(DatagramPacket d)-Dispatches the DatagramPacket object receive(DatagramPacket p)-Receives the DatagramPacket object Steps: Server Program 1. Import the net package in java which provides the facility for networking. import java.net.*; 2.

Declare a class with main function and initialize the Datagram Socket and a array whose return type is byte to receive the data. public static void main(String arg[]) throws Exception {

DatagramSocket ds; byte b[] = new byte[1024]; 3. Initialise the port number where the server can send the data to the client and create

a Datagram Socket object using that port number. int serverport = 1500; ds = new DatagramSocket(serverport); 4. Initialise the clientport number which will be used to send the data. This port

number must be the same as the client port number int clientport=1500; 5. Using the getByName method present in InetAddress classto create an InetAddress

object,which is used to send the data to the client. System.out.println("Enter the input: "); InetAddress ia=InetAddress.getByName("localhost"); where localhost indicates it returns the IPAddress of the local machine 6. Using streams get the input fromn the user BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); while (true) { String s1= br.readLine(); if(s1==null || s1.equals("end")) break; 7. Since the data can be sent only in the form of bytes in Datagram Packet by means of getBytes() method in String class it is converted into byte and stored in a byte array. b = s1.getBytes(); 8. Send the data ds.send(new DatagramPacket(buffer,ss.length(),ia,clientport)); where buffer is the array of data to be sent,the second is the length of the data,the third the Ipaddress of the client machine and fourth the port number where the client waits to receive the data.

Client program 1. Import the net package in java which provides the facility for networking. import java.net.*; 2. Declare a class with main function and initialise the DatagramSocket and a array whose return type is byte to receive the data. public static void main(String arg[]) throws Exception { DatagramSocket ds; byte b2[] = new byte[1024]; 3. Initialise the port number where the client can receive the data from the server and create a DatagramSocket object using that port number. int clientport = 1500;// int serverport=1501; ds1 = new DatagramSocket(clientport); 4. Create a DatgramPacket object which takes two arguments,the first a byte array and second the size of the array. DatagramPacket p= new DatagramPacket(byte data[], int size) 5. Use the socket object to receive the DataPacket ds1.receive(p); b2=p.getData(); 6. Inorder to print the received data in the console, create a String Constructor which takes three arguments: the first a byte array, the second starting point from where the contents to be read, the third ending point of the reading process String s1 = new String (buffer, 0, p.getLength()); System.out.println(" received from client" + s1); 7. Close the socket connection ds.close();

Coding: DatagramServer.java import java.net.*; import java.io.*; public class datagramserver { public static void main(String srgs[])throws Exception{ DatagramSocket ds; int clientport=796; int serverport=795; byte b[]=new byte[1024]; InetAddress ia= InetAddress.getLocalHost(); ds=new DatagramSocket(serverport); System.out.println("Enter Input:"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); b=s.getBytes(); DatagramPacket p1=new DatagramPacket(b,s.length(),ia,clientport); ds.send(p1); } } DatagramClient.java import java.io.*; import java.net.*; public class datagramclient { public static void main(String[] args) throws Exception{ DatagramSocket ds1; int clientport=796; int serverport=795; byte b2[]=new byte[1024]; ds1=new DatagramSocket(clientport);

System.out.println("Client Waiting"); DatagramPacket p=new DatagramPacket(b2,b2.length); ds1.receive(p); b2=p.getData(); String s1=new String(b2,0,p.getLength()); System.out.println(s1); } }

Output:

Result: Thus a message is sent from the server to client using UDP Sockets.

Ex.no:9 CLIENT SERVER APPLICATION USING TCP/IP SOCKETS Aim: To develop a client server application using TCP/IP Sockets. Steps: TCPServer.java 1. Create a server Socket which perfoms 3-wayhandshake (initial negotiations) with client on the specified port no. import java.net.*; import java.io.*; public class tcpserver { public static void main(String[] args) throws IOException { ServerSocket s1=new ServerSocket(195); 2. Create an other socket using the accept() method present in server socket, by which further communication with client can be done Socket s2=s1.accept(); 3. In order to send the data from server to client getOutputStream() method present in socket is invoked and a PrintWriter object is attached to it. OutputStream o1=s2.getOutputStream(); PrintWriter Out=new PrintWriter(o1); 4.Getting input from the user in server program using predefined streams. System.out.println("enter file name"); BufferedReader br=new BufferedReader(newInputStreamReader(System.in)); String s=br.readLine(); File f=new File(s); if(f.exists()) { FileReader f2=new FileReader(f1); BufferedReader b2=new BufferedReader(f2);

String st; 5.Sending the data using the PrintWriter’s object to send the data to sockets. while((st=b2.readLine())!=null) { out.write(st); out.flush(); } 6.Close the connection s2.close(); s1.close(); } } } TCP Client.java 1. Create a client Socket and get the inet address of the host

machine.

import java.io.*; import java.net.*; public class tcpclient{ public static void main(String args[]) throws UnknownHostException, IOException{ Socket s=new Socket (InetAddress.getLocalHost (), 495); 2. In order to recieve the data from server , getInputStream() method

present in

socket is invoked and a InputStreamReader object is attached to it. Getting data from the server program using predefined streams. BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); 4. Read the received data and print it in the console. while ((s2=in.readLine())!=null) { System.out.println (s2); }

Coding: TCPServer.java import java.io.*; import java.net.*; public class tcpserver { public static void main(String[] args) throws Exception { ServerSocket s1=new ServerSocket(196); Socket s2=s1.accept(); OutputStream o1= (OutputStream) s2.getOutputStream(); PrintWriter out=new PrintWriter(o1); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); File f=new File(s); if(f.exists()) { FileReader f2=new FileReader(f); BufferedReader b2=new BufferedReader(f2); String st; while((st=b2.readLine())!=null) { out.write(st); out.flush(); } s2.close(); s1.close(); } } } TCPClient.java: import java.io.*; import java.net.*;

public class tcpclient { public static void main(String[] args) throws Exception { Socket s=null; BufferedReader in=null; //InetAddress ia=InetAddress.getLocalHost(); try{ s=new Socket(InetAddress.getLocalHost(),196); in = new BufferedReader(new InputStreamReader(s.getInputStream())); }catch(IOException e){} System.out.println("Connected to port 196"); String s2; while((s2=in.readLine())!=null) { System.out.println(s2); } in.close(); s.close(); } }

Output:

Result: Thus a client server application is developed using TCP/IP Sockets.

REMOTE METHOD INVOCATION (RMI)

Ex.no:10

RMI PROGRAM TO PERFORM ARITHMETIC OPERATIONS Aim: To write a RMI program to perform arithmetic operations. Steps: Interface A. Define an interface which contains various methods that client can use. B. It can be invoked from any machine in the network where server resides. Remote interface 1. Import the necessary package. import java.rmi.*; 2. The interface must extend the Remote class present in java.rmi package, otherwise it cannot be used by the client. public interface vi extends Remote { 3. The method signature must throw Remote Exception. It occurs when a client cannot able to locate the server (or) whenever there is a fault in network. Interface implementation Interface implementation must implement all the abstract methods defined in interface. 1. Import the packages. import java.rmi.*; import java.rmi.server.*; 2. Implementation

must

extends

UnicastRemoteObject

java.rmi.server package, which provides the facility for

class

present

in

serialization and

deserialization. public class viimpl extends UnicastRemoteObject implements vi 3. Implementation must also contain a default constructor which is used during runtime for exporting of remote objects. viimpl() throws RemoteException

{} public int add(int a,int b)throws RemoteException { return a+b; } public int sub(int a,int b)throws RemoteException { return a-b; } public int mul(int a,int b)throws RemoteException { return a*b; } public int div(int a,int b)throws RemoteException { return a/b; } Server Create a remote object and bind it in registry. 1. Import the necessary packages. import java.rmi.*; class server1 { public static void main(String[] args)throws Exception { 2. Create a remote object for the interface implementation. vilmpl a1=new vilmpl(); 3. Bind it in registry using rebind method() present in Naming class under a specified name. Naming.rebind("add",a1); Naming.rebind("sub",a1);

Naming.rebind("mul",a1); Naming.rebind("div",a1); } }

Client Invoking of a method present in server using interface . Interface of a particular object is retrieved by looking up in registry. 1. Import necessary packages. import java.rmi.*; class client1 { public static void main(String[] args)throws Exception { 2. To lookup in RMI registry , a protocol format similar to http is followed and it is assigned to a string. String s="rmi://"+args[0]+"/add"; Where rmi = protocol args[0] = IP address of machine add = Name of remote object. 3. Using the lookup() method present in Naming class, the remote object is searched in RMI Registry. If the object is binded in RMI registry, it returns a RemoteInterface of that object. vi a1=(vi)Naming.lookup(s); 4.

Using the interface object the corresponding methods present in the interface are invoked and values are present are passed as arguments to it. System.out.println(a1.add(7,6)); System.out.println(a1.sub(7,6)); System.out.println(a1.mul(7,6)); System.out.println(a1.div(7,6));

} } Running of RMI Program 1. Compile all the four programs javac vi.java javac vilmpl.java javac ser.java javac cli.java 2. Stub and skeletons are generated using rmic(rmi compiler) with interface implementation rmic vilmpl 3. Run the RMI registry to bind the remote object created in the server side start rmiregistry 4. Run the server java ser 5. Run the client program with the needed command line arguments. java cli 90.0.0.149

Coding: vi.java import java.rmi.*; public interface vi extends Remote { public int add(int a,int b) throws RemoteException; public int sub(int a,int b) throws RemoteException; public int mul(int a,int b) throws RemoteException; public int div(int a,int b) throws RemoteException; } vilmpl.java import java.rmi.*; import java.rmi.server.*; public class vilmpl extends UnicastRemoteObject implements vi { vilmpl() throws RemoteException {} public int add(int a,int b) throws RemoteException { return a+b; } public int sub(int a,int b) throws RemoteException { return a-b; } public int mul(int a,int b) throws RemoteException { return a*b; } public int div(int a,int b) throws RemoteException {

return a/b; } } ser.java import java.rmi.*; class ser { public static void main(String[] args) throws Exception { vilmpl a1=new vilmpl(); Naming.rebind("add",a1); Naming.rebind("sub",a1); Naming.rebind("mul",a1); Naming.rebind("div",a1); } } cli.java import java.rmi.*; class cli { public static void main(String[] args) throws Exception { String S="rmi://"+args[0]+"/add"; vi a1=(vi)Naming.lookup(S); System.out.println("Addition:"+a1.add (7,6)); System.out.println("Subraction:"+a1.sub(7,6)); System.out.println("Multiplication:"+a1.mul (7,6)); System.out.println("division:"+a1.div (7,6)); } }

Output:

Result: Thus the arithmetic operations are performed using RMI.

JAVA DATABASE CONNECTIVITY (JDBC)

Ex.no:11

SIMPLE JDBC APPLCIATION Aim: To write a jdbc application to get the input from the user, store it in a table, to retrieve and display it. Steps: MS-ACCESS 1. Create a database file in ms-access by selecting Start ->programs-> file-> new-> Blank database and save it using a name. 2. In order to create a system DSN, clicking on control panels->administrative tools> ODBC->is chosen. 3. In that system DSN is chosen and a unique name is given with a specified database. Java program 1. Interfaces and classes of JDBC API are present inside the package called as java.sql. So this package must be imported for any application using JDBC API. import java.io.*; import java.sql.*; public class dconnection { public

static

void

main(String[]

args)

throws

ClassNotFoundException,

SQLException, IOException { 2. Register the driver or load the driver using the forName() method present in class (java.lang.pkg) the driver is loaded. Class.forName(sun.jdbc.odbc.jdbcodbcdriver); 3. Connect to the database using the getConnection() method present in the driver manager class to establish a connection . Connection c=DriverManager.getConnection("jdbc:odbc:data2"); 4. Create a statement to execute sql query statement object must be created , since sql execution methods are present in it. Statement s=c.createStatement();

5. Execute the SQL statements using executeUpdate method() present in Statement interface. s.executeUpdate("CREATE

TABLE

STUDENT8

(Name

VARCHAR(20),id INT, Address VARCHAR(20))"); System.out.println("Table created"); 6. Insert values into the tables Get input from the user and using insert statement values are stored in database. s.executeUpdate(“INSERT INTO EMPL VALUES(‘surya’,52,’cbe’)”); System.out.println("One row created"); 3. Retrieve the values from the database using executequery() method whose return type is a resultset (an interface which contains methods for retrieval of data returned by sql statement execution) ResultSet rs=s.executeQuery("SELECT * FROM STUDENT8"); 4. Iterate through each and every value of SI using next() method and close the connection while(rs.next()) { System.out.println(rs.getString("Name")); System.out.println(rs.getInt("ID")); System.out.println(rs.getInt("Address")); } rs.close(); s.close(); c.close(); }

Coding: import java.sql.*; public class dcon { public static void main(String[] args) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:new"); System.out.println("Connection Ok"); Statement s=c.createStatement(); s.executeUpdate("CREATE TABLE EMPL(Name VARCHAR(20),ID INT,Address

VARCHAR(20))”); System.out.println(“Table created”); s.executeUpdate(“INSERT INTO EMPL VALUES(‘surya’,52,’cbe’)”); System.out.println(“One row created”); ResultSet rs=s.executeQuery(“SELECT * FROM EMPL”); while(rs.next()) { System.out.println(rs.getString(“Name”)); System.out.println(rs.getInt(“ID”)); System.out.println(rs.getString(“Address”)); } rs.close(); s.close(); c.close();

} }

Output:

Result: Thus the inputs got from the user are stored and displayed in a table using JDBC.

JAVA APPLETS

Ex.no:12

EVENT HANDLING MECHANISM IN APPLETS Aim: To develop an applet to using event handling mechanism. Steps: 1. Import the following packages. import java.applet.*; import java.awt.*; import java.awt.event.*; 2. Every applet application must be a subclass of applet class. For a checkbox to click item event is generated. So in order to listen to an event, a listener must be implemented here it is ItemListener. public class check extends Applet implements ItemListener { String msg=" "; 3. Override the init method () which contains initialization of checkbox objects. public void init() { c1=new Checkbox("Pink"); c2=new Checkbox("Red"); c3=new Checkbox("Green"); c4=new Checkbox("Blue"); 4. Add the created buttons to the window or else it cannot be viewed. add(c1); add(c2); add(c3); add(c4); 5. Add actionListener to the buttons to process action events generated by them. c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this);

c4.addItemListener(this); 6. Override the itemStateChanged() method of actionListener interface. public void itemStateChanged(ItemEvent arg0) { repaint(); } 7. Override the paint () method which contains the message to be drawn to a window using the drawString() method present in graphics object. public void paint(Graphics g) { msg="Current State"; g.drawString(msg,20,75); msg="Pink:"+ c1.getState()+"\n"; g.drawString(msg,20,100); msg="Red:"+ c2.getState()+"\n"; g.drawString(msg,20,125); msg="Green:"+ c3.getState()+"\n"; g.drawString(msg,20,150); msg="Blue:"+ c4.getState()+"\n"; g.drawString(msg,20,175); }

Coding: import java.applet.*; import java.awt.*; import java.awt.event.*; public class check extends Applet implements ItemListener { String msg=""; Checkbox c1,c2,c3,c4; public void init() { c1=new Checkbox("Pink"); add(c1); c2=new Checkbox("Red"); add(c2); c3=new Checkbox("Green"); add(c3); c4=new Checkbox("Blue"); add(c4); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); c4.addItemListener(this); } public void itemStateChanged(ItemEvent arg0) { repaint(); } public void paint( Graphics g) { msg="Current State"; g.drawString(msg,20,75); msg="Pink:"+ c1.getState()+"\n"; g.drawString(msg,20,100); msg="Red:"+ c2.getState()+"\n"; g.drawString(msg,20,125); msg="Green:"+ c3.getState()+"\n"; g.drawString(msg,20,150); msg="Blue:"+ c4.getState()+"\n"; g.drawString(msg,20,175);

Output:

Result: Thus an applet is developed for handling the events generated by checkbox.

Related Documents

Record 2 Final
April 2020 8
Record
June 2020 17
Record
May 2020 11
Record
October 2019 18
Record
April 2020 17
Cash Record 2
November 2019 3

More Documents from ""

Abstracts New Java
April 2020 28
Java Lab Questions
April 2020 18
Systemsoft(3)
May 2020 30
Record 55
April 2020 3
Record 2 Final
April 2020 8