• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
projectsgeek

ProjectsGeek

Download Mini projects with Source Code, Java projects with Source Codes

  • Home
  • Java Projects
  • C++ Projects
  • VB Projects
  • PHP projects
  • .Net Projects
  • NodeJs Projects
  • Android Projects
    • Project Ideas
      • Final Year Project Ideas
      • JSP Projects
  • Assignment Codes
    • Fundamentals of Programming Language
    • Software Design Laboratory
    • Data Structure and Files Lab
    • Computer Graphics Lab
    • Object Oriented Programming Lab
    • Assembly Codes
  • School Projects
  • Forum

Java Tutorials

SQL and JDBC(Java Database Connectivity) in Java

April 18, 2012 by ProjectsGeek Leave a Comment

SQL and JDBC(Java Database Connectivity)



This section of Java tutorial will deal with the connectivity of Java with databasis lik…MySql . Apart from connectivity we will discuss some basic concepts about Sql Language . 


For using SQL you can install MYsQL with its connector from official web Site of MySql here . You can use this Tutorial as source for connectiong database and Java applications .


Starting with the Topics that will be covered in this section of tutorial are :   

  • Introduction to SQL
  • DDL Statements
  • DML Statements
  • Relational Operators
  • JDBC Connectivity 

So , What is Sql ?


SQL is used to make a request to retrieve data from a database. Whenever you want to access data from database you should use Sql commands for this Purpose . 


On receiving the request, DBMS system processes that request by retrieving data from the database. This process of requesting data from a database is called  a database query and hence SQL.
A database query can be very simple to very complex query .


SQL Commands


Commanda under sql can divided into three sections as described Below 

  1. DDL Commands : Create, Alter, Drop, Truncate
  2. DML Commands : Insert, Update, Delete, Select
  3. DCL Commands : Grant, Revoke, Commit, Rollback.

Data Types


Now Discususing about Datatypes in Sql languge which will be very useful for making and executing the Queries for your requirements .


Char : Fixed Length Character String (Max range : 2000 bytes)
Varchar2(n) : Variable length Character String (Max range : 4000 bytes)
Long: Variable length Character String (max one column in a table) (Max range: 2GB)
Number (p, s): Numbers P for Precision and s for scale.
Date: Date and time (dd-mon-yy format)
Raw and Long Raw: Binary data


Object Naming Rules


Rules that must be followed for namimg conventions in Sql langauge are given below : 

  1. The first letter should be alphabet
  2. Oracle reserved words are not to be used.
  3. Maximum length 30 characters
  4. Only Underscore are allowed. 
  5. Not case sensitive.

More About SQL Commands 


Data Definition Language:

  1. Create : Create a new table
  2. Alter : Modify the existing table
  3. Drop : Drop a table
  4. Truncate : delete all rows from a table 

Create Table Command


If the user wants to create a new table you should use the following query  :

Create table  
(
datatype,
datatype,
datatype
);


Alter Table Command


If the user wants to add column to the existing table use the following query   :
Alter table add ( datatype);


If the user wants to modify column in the existing table use the following query  :
Alter table modify ( datatype);


If the user wants to drop column in existing table use the following query  : 
Alter table drop column :


Drop, Truncate Commands 


If the user wants to drop the table use :
drop table


If the user wants to delete all records from the table but not the table use :
truncate table


desc Command 


If the user wants to view the structure of the table use :
desc


Other SQL Commands  


Data Manipulation Language Commands :

  1. Insert : Insert data in a table
  2. select : Display data in table
  3. Update : Update data in a table
  4. Delete : delete data in a table

Insert Table Command


If the user wants to insert data in a table use:
insert into values ( , , …..);
insert into (, ) values 
( , );


Select Table Command


If the user wants to display data in a table use:
select * from ;
select distinct from ;
select , from ;


Update Table Command


If the user wants to modify data in a table use:
update set field= value where condition;


Delete Table Command


If the user wants to delete data in a table use:
     delete from ;
    delete from where


Rest of SQL Commands


Data/Transaction Control Language Commands:

  1. Commit: fully save
  2. savepoint: create a savepoint
  3. Rollback: Undo 
  4. Grant: Grant permission
  5. Revoke : Revoke permission

Commit Command


If the user wants to save all work done use:
Commit;

Savepoint Command


Savepoints are markers to divide a very lengthy transaction to smaller ones. They are used to identify a point in transaction to which we can later rollback;


Savepoint ;
Rollback
Undo the work done


Rollback;
Rollback to savepoint ;
Grant
Grant permission to other users use:


Grant all on to
Grant select, update on to


Revoke Command


Revoke permission from other users use:
Revoke all on from
Revoke select, update on from


SQL Operators in Sql Language 


Arithmetic Operators:
+    –    *   /
Comparison Operators
=    !=   <   >   <=   >=
between, not between, in, like, not like, is null, is not null
Logical Operators:
and,  not,  or 
Concatenation Operators
||
SQL Constraints
Not Null
Check
Unique
Primary
Foreign
On delete cascade




JDBC(Java Database Connectivity)   


It is a software layer that allows developers to write real client-server projects in Java. 
JDBC was designed to be a very compact, simple interface focusing on the execution of raw SQL statements and retrieving the results. 
The components of JDBC are Application, Driver manager and Driver.


JDBC Components


Application
Invokes methods to send SQL statements to the database and retrieve the results. 


Driver Manager
Loads specific drivers for the user application


Driver
Processes methods invocation, sends SQL statements to a data source & returns results-back to application.


JDBC Driver Models


Two Tier Model


Java Applications interact directly with the database. This type pf model is called as client-server configuration where user is the client and database machine is called as server. 


Three Tier Model


A middle tier is introduced, which is used to collect SQL from the client and handed over to the database and collect the results from the database and handed to the client. 


JDBC Vs. ODBC Important Differences


ODBC cannot be directly used with Java because it uses a C interface. ODBC makes use of pointers which have been totally removed from Java Langauge thats why ODBC cannot be used in Java.


ODBC requires manual installation of the ODBC driver manager and driver on all client machines. 


JDBC drivers are written in Java and JDBC code is automatically installable, secure and portable on all java platforms.

JDBC features 


The JDBC API defines a set of interfaces and classes to be used for communications with a database. These interfaces and classes are found in the java.sql package.


The results of the SQL statements are stored in ResultSet object and getXXX method used to retrieve the data from ResultSet. 


DSN(Data Source Name )


Types of DSN

  1. File DSN –  Accessibility is very low
  2. System DSN – Easy to access and by all users.
  3. User DSN –  Specific to a user but not portable.

Steps in Java Database Connectivity  

  1. Import the java.sql package
  2. Register the driver
  3. Connect to a database
  4. Create a statement
  5. Execute the statement
  6. Retrieve the results
  7. Close the statement and connection

Steps for SQL Commands (except select)




1. class.forName (”sun.jdbc.odbc.JdbcOdbcDriver”);
2. Connection c= DriverManager.getConnection (“Jdbc.odbc:DSN”);
3. Statement s = c.createStatement( );
4. s.executeUpdate (“ SQL INSERT/UPDATE”);
Steps Used for SELECT
1. class.forName (”sun.jdbc.odbc.JdbcOdbcDriver”);
2. Connection c= DriverManager.getConnection (“Jdbc.odbc:DSN”, “Username”, “Password”);
3. Statement s = c.createStatement( );
4. ResultSet rs =s.executeQuery (“ SQL INSERT/UPDATE”);


Steps Used for SELECT


5.
ResultSetMetaData rsmd =rs.getMetaData( );
int count =rsmd.getColumnCount( );
for(int j=0; j<=count; j++)
{
System.out.println(rsmd.getColumnName( j)+”\t”);
}


Steps Used for SELECT


6. while (rs.next( ) );
{
for(int j=0; j<=count; j++)
{
System.out.println( rs.getString( j)+”\t”);
}
}


7. s.close( );
8. c.close( );
ResultSet
execute();
returns boolean value.


executeUpdate();
Returns nothing. 


executeQuery();
Returns ResultSet (Applicable for select query)
Statement 
Statement s = c.createStatement(, );


First Parameters is 
TYPE_SCROLL_SENSITIVE
TYPE_SCROLL_INSENSITIVE
TYPE_FORWARD_ONLY (default)


Second parameters is
CONCUR_READ_ONLY (default)
CONCUR_UPDATABLE
ResultSet Methods
afterLast();
Cursor moves to the last record + 1


previous();
Cursor moves backward


absolute (int)
Cursor moves to absolute position


relative (int)
Cursor moves to relative position
ResultSet Methods
last();
Cursor moves to the last record


updateDouble(,
Update some Column Value


moveToInsertRow();
Row could be inserted.


updateRow() / insertRow();
Update/Insert all changes done above this function.
Example : 
ResultSet rs=s.executeQuery (“select * from student’);
rs.afterLast();
while (rs.previous( ) );
{
for(int j=0; j<=count; j++)
{
System.out.println( rs.getString( j)+”\t”);
}
}




Example : Update Values


ResultSet rs=s.executeQuery (“select * from student’);
rs.last();
rs.updateDouble (“Percentage”, 85.55);
rs.updateInt (“Marks”, 1255);
rs.updateRow();
Example : Insert Values
ResultSet rs=s.executeQuery (“select * from student’);
rs.moveToInsertRow();
rs.updateString (“Name”, “Amit”);
rs.updateDouble (“Percentage”, 85.55);
rs.updateInt (“Marks”, 1255);
rs.insertRow();
Batch Update 


A batch update is a set of multiple update/insert statements that is submitted to the database for processing as a batch.


addBatch (“SQL Query”);
Create a new Batch which is a set of multiple insert or update statements. 


Int executeBatch();
Execute the batch. 




Batch Update : Example


All insert Statement get executed or none of it executed. 

Statement s= c.createStatement();
s.addBatch (“Insert Statement – 1”);
s.addBatch (“Insert Statement – 2”);
s.addBatch (“Insert Statement – 3”);
s.addBatch (“Insert Statement – 4”);
s.addBatch (“Insert Statement – 5”);
s.executeBatch();




Questions for Revision of Above Topic?


What are different components of JDBC?
Differentiate between JDBC and ODBC.
Explain the concept of batch update in JDBC. 

Other Projects to Try:

  1. Database connectivity in Java with MYSQL
  2. Database Operations without pointers source code
  3. Write a program in Java for student details (Roll No, Name etc) to Access as a database and write the application in JDBC. (AWT or JFame).
  4. Student Database using Shell Programming OS problem
  5. SQL Workbench Project using Java

Filed Under: Java Tutorials

Threads in Java Tutorial for Beginners

April 17, 2012 by ProjectsGeek Leave a Comment

Threads in Java Tutorial for Beginners





Threads in Java Tutorial for Beginners is part of previous tutorial on Java core programming . As we know threads is the important feature of Java programming So , it’s necessary to learn concepts of threads in java .


Threads in Java Course Contents are Given below in Sequence

  • Introduction to Multitasking
  • Definition of Thread
  • Thread Methods
  • Synchronization
  • InterThread Communication
  • Questions

Starting with the Terms related to threads in Java …


What is Process ?


A process is a program in execution on system or computer . Two or more processes running concurrently in a computer is called multitasking. So , multiple process leads to multitasking .
Java also supports for multithreading. A Process can contain multiple threads to execute its different sections. So , Process having multiple threads is multithreading in Java .


These terms are important from many point of views , So I suggest you to keep these terms in mind .


What is Thread?


A thread is a line of execution of code . It is the smallest unit of code that is dispatched by the scheduler.


A process can contain multiple threads to execute its different sections. This is called multithreading.


Advantages of Threads –

  1. Can be created faster.
  2. Requires less overhead.
  3. Interprocess communication is faster.
  4. Context switching is faster.
  5. Maximum use of CPU time.

Some Common Thread Methods which are generally used for programming threads in Java codes are given below:


start();
Start the execution of thread.


stop();
Stop the execution of Thread.


suspend();
Suspend the execution of Thread.


resume();
Resume the execution of suspended Thread.
Common Thread Methods


sleep (long);
Suspend the execution of thread for a certain period of time . Time is in milliseconds.


How to Create a Thread?


A thread in Java is created as an Object of Class Thread.
Thread t = new Thread();


A thread in Java can also be created by implementing your class by Runnable Interface.


Example :


By default every Java class contains a main thread where the execution of the program starts.


class sample
{
public static void main (String args)
{
— Print even numbers from 0 to 100
— Print odd numbers from 0 to 100
}
}


Example : (Multithreading)


class sample
{
— New Thread Print even Numbers from 0 to 100.
public static void main (String args)
{
— Create a New Thread t1
— Starts a New Thread t1
— Print odd numbers from 0 to 100
}
}


Example : (Multithreading)


class sample extends Thread
{
— New Thread Print even Numbers from 0 to 100.
public static void main (String args)
{
sample s = new sample();
— Starts a New Thread t1
— Print odd numbers from 0 to 100
}
}


Example : (Multithreading)


class sample extends Thread
{
— New Thread Print even Numbers from 0 to 100.
public static void main (String args)
{
sample s = new sample();
s.start();
— Print odd numbers from 0 to 100
}
}


Example : (Multithreading)


class sample extends Thread
{
public void run() { — even Numbers from 0 to 100 }
public static void main (String args)
{
sample s = new sample();
s.start();
— Print odd numbers from 0 to 100
}
}


Thread Methods


User can create multiple threads in a Java program and set the priority of each.


int getPriority()
setPriority(int);


User can check whether the Thread is alive or dead.


boolean isAlive();


Waits forever for this Thread to die.


join()


Thread Methods


Returns a reference to the currently executing Thread object and is a static method.


currentThread();


Thread Names can be set by using :
String getName();
setName(String);


Example :
Class sample extends Thread
{
public static void main (String args[]) {
Thread t= Thread.currentThread();
System.out.println (t.getName());
System.out.println (t.getPriority());
t.setName (“myThread”);
t.setPriority(2);
System.out.println (t.getName());
System.out.println (t.getPriority());
} }


Synchronization


Two or more Thread accessing the same data simultaneously may lead to loss of data integrity.


For example, when two people access a saving account, it is possible that one person may overdraw and the cheque may bounce.


Monitor


Java uses the concept of monitor or a semaphore to enable this. A monitor is an object, used as a mutually exclusive lock.


At a time, only one thread can access the monitor. A second thread cannot enter the monitor until the first comes out. Till such time, the other thread is said to be waiting.
Monitor
The keyword synchronized is used in the code to enable synchronization.


The word synchronized can be used with a method or within a block.
public void synchronized request();


Inter Thread Communication


Java offers interprocess communication through the usage of wait(), notify() and notifyall() methods of Object class and all are synchronized methods.


Wait() – waits indefinitely on another thread of execution until it receives a notify() or notifyall() message.


Inter Thread Communication


notify() – This method wakes up a single thread waiting on the Object’s monitor.


notifyAll()- This methods wakes up all threads waiting on the Object’s monitor.




Questions ?




Define Thread. In Java what are different ways to create a Thread?


What are different Thread Methods present in class Thread?


Which is the default method executed by Created new Thread.?


What are the advantages of Threads over processes?

Other Projects to Try:

  1. First Program in Java
  2. Multiple Inheritance in java program
  3. File Handling and IO Handling in Java Programming
  4. Java Applet Tutorial for Beginners
  5. Java Tutorial for beginners – Introduction to Java

Filed Under: Java Tutorials

Java Applet Tutorial for Beginners

April 17, 2012 by ProjectsGeek Leave a Comment

Java Applet Tutorial for Beginners



This tutorial is basically for Begineers who have no knowkedge of Applets before reading this tutorial . So , I am expecting that you know some basics of Java programming . If you are also new to Java programming I suggest you to go through java tutorial also here .


So , what is Applet in Short ?


Applet is small java program that can be placed on the HTML pages . Applet are featured with graphics and you can easily animate graphics by the help of Applet .


Example of Applet can be considered as the google ads you see on the Web pages that includes rich graphics .


Now starting with the other topics that need to be covered in the turorial .


Classification of Java programs


Java programs are classified into three groups:

  • Java Applications
  • Java Applets
  • Java Servlets.

Java Applications


Java Applications are executed on the command prompt on the desktop system like other windows application .


Java Applets


Applets are executed on the web browsers on client side .


So what is Applet Finally ?


An applet is a dynamic and interactive program that can run inside a web page displayed by a browser.


It is possible to download the applets and play applets on our system.


Applets can be used as rich graphics java programs on the Web .


Limitations of Applets

  1. Applets cannot read or write to the file system.
  2. Applets cannot communicate with any other server than the one ion which they were stored originally.
  3. Applets cannot run any programs on the system.

So, after reading limitations of Applets we are sure that applets can’t harm our computer with any other code . This feature of the applet makes it more popular on the Web .


Now , We should take a simple exmaple of applet in java . To create a applet on eclipse just follow these instructions :

  1. Create a Java Project .
  2. Add package and then class to the project .
  3. Now name the class as ” myApplet ” and put the given below in the class .
  4. Now run Project as Applet…Enjoy .

 import java.awt.*;  
import java.applet.*;
public class myApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString (“Hello”, 70, 30);
}
}
A simple Applet with Parameters
public class myApplet extends Applet
{
String name;
public void init() { name=getParameter(“t1”); }
public void paint (Graphics g)
{
g.drawString (name, 70, 30);
}
}

If you want to embeeded the applet into Webpages just put the below code in the Webpage . Your applet.class file should be present in the same folder of your webpage .


HTML file to Run an Applet

Inside HTML file include tag.  

   




You can tune size of applet by changing WIDTH and HEIGHT values as required .


Now , it’s time to learn meathods that are present in applet class as derived from extended applet class .


Here are the Applet Methods


init() method :


This method gets called as soon as applet is started. Initialization of all variables, creation of objects, setting of parameters etc can be done in this method. 


start() method :


This method is executed after the init() method. When a browser is used to run an applet, any time it is reloaded, the execution begins from the start() method. 


stop() method :


This method is used to halt the running of an applet. When a browser is used  to run an applet, as soon as web browser is closed, this method is called. 


destroy() method :


This method is used to free the memory occupied by the variables and objects initialized in the applet. Any clean up activity that need to be performed can be done in this method. 


paint() method :


This method helps in drawing and creating a colored background or an image onto the applet. It always takes a Graphics Class object as an parameter. 


repaint() method :


This method calls the update() method, to clear the screen. The update() method in turn calls the paint() method.


Methods in a Graphics Class


These methods are inbuild methods which you can use to draw graphics on applet . You just have to pass coordinates for drawing figures and graphics .


drawBytes( byte[], int start, int end, int x, int y);
drawChars(char[], int start, int end, int x, int y);
drawString (String str, int x, int y);
drawLine(int x1, int y1, int x2, int y2);
drawRect(int x1, int y1, int w, int h);
fillRect(int x1, int y1, int w, int h);
drawRoundRect (int x1, int y1, int w, int h, int w1, int h1);
fillRoundRect (int x1, int y1, int w, int h, int w1, int h1);
draw3DRect(int x1, int y1, int w, int h, true/false);
drawPolygon (int xs, int ys, pts);
fillPolygon (int xs, int ys, pts);


Other  methods in a Graphics Class


drawOval(int x1, int y1, int w, int h);
fillOval(int x1, int y1, int w, int h);
drawArc(int x1, int y1, int w, int h, angle1, angle2);
fillArc(int x1, int y1, int w, int h, angle1, angle2);


Now taking about Fonts and Colors available in applet :


setFont (Font f);
setColor (Color c);
drawImage (Image img, int x, int y, this);


At last Questions for Revision of Applet ?

  1. Define Applet?
  2. Explain the significance of methods present in Applet Class.
  3. Draw an applet of Displaying The hello message on the html page Showing smiling face onto the html page.



tag.



=top>

You can tune size of applet by changing WIDTH and HEIGHT values as required .

Now , it’s time to learn meathods that are present in applet class as derived from extended applet class .

Here are the Applet Methods

init() method :

This method gets called as soon as applet is started. Initialization of all variables, creation of objects, setting of parameters etc can be done in this method.

start() method :

This method is executed after the init() method. When a browser is used to run an applet, any time it is reloaded, the execution begins from the start() method.

stop() method :

This method is used to halt the running of an applet. When a browser is used to run an applet, as soon as web browser is closed, this method is called.

destroy() method :

This method is used to free the memory occupied by the variables and objects initialized in the applet. Any clean up activity that need to be performed can be done in this method.

paint() method :

This method helps in drawing and creating a colored background or an image onto the applet. It always takes a Graphics Class object as an parameter.

repaint() method :

This method calls the update() method, to clear the screen. The update() method in turn calls the paint() method.

Methods in a Graphics Class

These methods are inbuild methods which you can use to draw graphics on applet . You just have to pass coordinates for drawing figures and graphics .

drawBytes( byte[], int start, int end, int x, int y);
drawChars(char[], int start, int end, int x, int y);
drawString (String str, int x, int y);
drawLine(int x1, int y1, int x2, int y2);
drawRect(int x1, int y1, int w, int h);
fillRect(int x1, int y1, int w, int h);
drawRoundRect (int x1, int y1, int w, int h, int w1, int h1);
fillRoundRect (int x1, int y1, int w, int h, int w1, int h1);
draw3DRect(int x1, int y1, int w, int h, true/false);
drawPolygon (int xs, int ys, pts);
fillPolygon (int xs, int ys, pts);

Other methods in a Graphics Class

drawOval(int x1, int y1, int w, int h);
fillOval(int x1, int y1, int w, int h);
drawArc(int x1, int y1, int w, int h, angle1, angle2);
fillArc(int x1, int y1, int w, int h, angle1, angle2);

Now taking about Fonts and Colors available in applet :

setFont (Font f);
setColor (Color c);
drawImage (Image img, int x, int y, this);

At last Questions for Revison of Applet ?

Define Applet? Explain the significance of methods present in Applet Class.

Draw an applet of Displaying The hello message on the html page
Showing smiling face onto the html page.

Other Projects to Try:

  1. Design an applet that displays the string “Hello College Name” moving from left to right. When it reaches to right, it scrolls back to left.
  2. Java Programs
  3. Threads in Java Tutorial for Beginners
  4. Java Tutorial for beginners – Introduction to Java
  5. Communication between applet and servlet Java Code

Filed Under: Java Tutorials

Introduction to Java

April 3, 2012 by ProjectsGeek Leave a Comment

Introduction to Java
Part 1 Contents :

  •     History of Java
  •     What is JDK
  •     Features of Java
  •     Sample program 


History of Java

Java is Object oriented, Multi-threading language developed by Sun Microsystems in 1991.

It is designed to be small, simple and portable across different platforms as well as OS.

What is JDK

JDK stands for Java development Kit.

There are two parts: Java Compiler and Java Interpreter (JVM).

Java Compiler generates bytecode instead of machine code and interpreter executes java

program. 

What is bytecode?

Bytecode is a set of instructions that resemble machine code but are not specific to any

processor.

The disadvantage of using bytecode is the execution speed. Since system specific programs

run directly on the hardware, they are faster than the Java bytecode. 

Features of Java

  1. Syntax based on C++
  2. Object-oriented
  3. Support for Internet applications
  4. Extensive library of prewritten classes
  5. Portability among platforms
  6. Built-in networking
  7. Security as JRE is inaccessible to other parts of computer. 

Class 

  • Tool for encapsulating data and operations (methods) into one package
  • Defines a template or model for creating and manipulating objects

Objects
  • Data created using the class and its methods
  • An object is an instance of the class
  • Creating an object is instantiation
OOP : Advantage
  • Well-written classes can be reused in new applications
  • Shortens development time because programmers don’t need to write new code
  • Programs are more robust because the class code is already tested
  
Introduction to Java 1

Other Projects to Try:

  1. Java for Programmers By -Paul Dietel and Harvey Dietel
  2. First Program in Java
  3. Active X DLL in VB.Net
  4. Java Applet Tutorial for Beginners
  5. Java Tutorial for beginners – Introduction to Java

Filed Under: Java Tutorials

Communication between applet and servlet Java Code

April 13, 2011 by ProjectsGeek Leave a Comment

                        Communication between applet and servlet Java Code

Today i will discuss about the communication between applet and servlet’s,  the most common problem faced by beginner’s during Java  development . So taking the applet as front end , our servlet at middle and database at back end most probably MYSQL.

Beginning at the applet end put the given below code in applet class outside paint function (must) . Change the  URL urlServlet = new URL(getCodeBase(), “points”) ,if your  servlet location is different than default location. You can send any object through this connection .just create the  object and send it through  oos.writeObject(your object) .

Communication between applet and servlet Java Code –Applet Code

import java.applet.Applet;  
 import java.awt.*;  
 import java.awt.event.*;  
 import java.io.*;  
 import java.net.*;  
 public class tank extends Applet {  
   private URLConnection ServletConnection()  
     throws MalformedURLException, IOException {  
     URL urlServlet = new URL(getCodeBase(), "points");  
     URLConnection con = urlServlet.openConnection();  
     con.setDoInput(true);  
     con.setDoOutput(true);  
     con.setUseCaches(false);  
     con.setRequestProperty("Content-Type", "application/x-java-serialized-object");  
         return con;  
   }  
   private void SendData() {  
     try {  
       String input="hi hello !!";  
      // sending string from applet to servlet  
       URLConnection con = ServletConnection();  
       OutputStream outstream = con.getOutputStream();  
       ObjectOutputStream oos = new ObjectOutputStream(outstream);  
       oos.writeObject(input);  
       oos.flush();  
       oos.close();  
       // receive string from servlet  
       InputStream instr = con.getInputStream();  
       ObjectInputStream inputFromServlet = new ObjectInputStream(instr);  
       String data = (String) inputFromServlet.readObject();  
       inputFromServlet.close();  
       instr.close();  
       outputField.setText(result);  
     } catch (Exception ex) {  
       ex.printStackTrace();  
          }  
   }  
 }

Communication between applet and servlet Java Code-Servlet Code

Now moving to our servlet whose name is points in root folder of our workspace(Server folder apache). The code given below simply accept the string send by the applet and send it back to applet.

 import java.io.*;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.*;  
 public class points extends HttpServlet {  
   public void doPost  
   (  
     HttpServletRequest request,  
     HttpServletResponse response)  
     throws ServletException, IOException  
      {  
       try {  
           response.setContentType("application/x-java-serialized-object");  
           InputStream in = request.getInputStream();  
           ObjectInputStream inputFromApplet = new ObjectInputStream(in);  
           String abc = (String) inputFromApplet.readObject();     // receiving string from applet  
           OutputStream outstr = response.getOutputStream();  
           ObjectOutputStream oos = new ObjectOutputStream(outstr);  
           oos.writeObject(abc);                                  // sending string back to applet  
           oos.flush();  
           oos.close();  
         } catch (Exception e) {  
       e.printStackTrace();  
     }  
   }  
 }

 

 

Other Projects to Try:

  1. To Implement Web Crawler in Java BE(IT) CLP-II Pratical
  2. Design an applet that displays the string “Hello College Name” moving from left to right. When it reaches to right, it scrolls back to left.
  3. GET vs POST in PHP | easy example
  4. Java Applet Tutorial for Beginners
  5. 100+ Free Java mini projects with Source Code

Filed Under: Java Tutorials

  • « Go to Previous Page
  • Page 1
  • Page 2

Primary Sidebar

Tags

.Net Projects Download Android Project Ideas Android Projects Angular 2 Assembly Codes C # Projects C & C++ Projects C++ Projects Class Diagrams Computer Graphics Database Project Data Mining Projects DataScience Projects Datastructure Assignments Download Visual Basic Projects Electronics project Hadoop Projects Installation Guides Internet of Things Project IOS Projects Java Java Interview Questions Java Projects JavaScript JavaScript Projects java tutorial JSON JSP Projects Mechanical Projects Mongodb Networking Projects Node JS Projects OS Problems php Projects Placement Papers Project Ideas Python Projects seminar and presentation Struts

Search this Website


Footer

Download Java Project
Download Visual Basic Projects
Download .Net Projects
Download VB Projects
Download C++ Projects
Download NodeJs Projects
Download School Projects
Download School Projects
Ask Questions - Forum
Latest Projects Ideas
Assembly Codes
Datastructure Assignments
Computer Graphics Lab
Operating system Lab
australia-and-India-flag
  • Home
  • About me
  • Contact Form
  • Submit Your Work
  • Site Map
  • Privacy Policy