Thursday, October 20, 2011

Change global_name of oracle

SQL> SELECT * FROM GLOBAL_NAME;

GLOBAL_NAME
--------------------------------------------------------------------------------
ORATEMP.REGRESS.RDBMS.DEV.US.ORACLE.COM

SQL> ALTER DATABASE RENAME GLOBAL_NAME TO oratemp ;

SQL> SELECT * FROM GLOBAL_NAME;

Sunday, October 16, 2011

configure glassfish in myeclipse

http://glassfishplugins.java.net/eclipse34/index.html

Tuesday, October 11, 2011

Java Database Connectivity (JDBC Tutorial)

Java Database Connectivity:
JDBC (Java Database Connectivity) is designed to allow users to use SQL(Structured Query Language) to query databases. It makes the tasks of the developers easy as it handles all low-level concerns about particular database types.

JDBC is similar to Microsoft’s ODBC with the plus point “Platform Independence”. To use JDBC, you need to have database driver to communicate with the database. Normally drivers are installed while installing the database. Like if you install MS SQL Server, Oracle or DB2, database drivers will be installed. If you are working with MySQL, PostgreSQL or some third party database, you need to put its driver (Jar fileI into the class path.

JDBC Drivers
            JDBC drivers can be broadly divided into four categories depending upon the driver implementation. The four categories/types are:

            1: JDBC-ODBC Bridge
            2:  Native-API/partly Java driver
            3: Net-protocol/all-Java driver
            4: Native-protocol/all-Java driver

I will briefly talk about each type:
            JDBC-OBC bridge driver is pure Java and is include in java.sql.*. The client needs ODBC driver manager and ODBC driver for data source. It is ideal in situations, when ODBC driver is available for the database and is already installed on the client machine.

            Type-2 is Native code driver. It implements native JDBC interfaces using language functions in the DBMS product’s API. Type 2 drivers need platform specific library, so client and server both may run on same host. Type 2 drivers offer better performance than Type 1 drivers.

Type 3 drivers are pure Java drivers and they use middleware network protocol. They need DBMS server to implement the standard protocol to be middleware specific. The advantage is that there is no nee for any vendor database library to be present on client machines. Interesting thing is, there is no JDBC standard network protocol yet.

Type 4 drivers are pure Java drivers and they use vendor specific network protocol. These use DBMS specific network protocol (Oracle SQL Net, etc).
For the beginners, Type 1 drivers are suitable. Users simply have to make a DSN and start interacting with the database.

Using JDBC-ODBC Bridge

The beginners should start with JDBC-ODBC Bridge since it is simple and easy to work with. Consider that you have a database with tables and data and you want to connect to it in order to carry out operations.
            First step is to create an ODBC dsn. It is done from Control panel > Data Sources (ODBC).
            Now you have to load the JDBC driver. This is done using static method forName(…) of class called Class. Static method forName(…) takes name of the driver as parameter.

Code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

DriverManager.getConnection() is used to connect to the database. Its signature is as follows:

Code:
static Connection getConnection(String url, String user, String password)



Continue... 
31/01/2011


Connection time:

            Sometimes, it is interesting to know how much time it takes to connect to the database. The code sample below calculates the time it takes to connect to a database referred by dsn.

Code:
long connection_time;
Date start = new Date();  //get start time
String stUrl_= "jdbc:odbc:myDSN";
connection_ = DriverManager.getConnection(stUrl,"sa","sa");
Date end = new java.util.Date();  //get end time
connection_time = end.getTime()-start.getTime();
 
 
Getting the Warnings:

            Sometimes it is a wise decision to retrieve the first warning reported by calls on this Connection object. This can be done using getWarnings() method. The code sample below shows how to print all the warnings with their sates and messages.

Code:
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;
Connection conn = DriverManager.getConnection( "jdbc:odbc:Database" ) ;

// Print all warnings
for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() )
{
System.out.println( "SQL Warning:" ) ;
System.out.println( "State  : " + warn.getSQLState()  ) ;
System.out.println( "Message: " + warn.getMessage()   ) ;
System.out.println( "Error  : " + warn.getErrorCode() ) ;
}

Adding records in the database tables:

            Statement object is used to add enteries into the tables. The method used is executeUpdate(…).


Code:
Statement st = conn.createStatement();
st.executeUpdate("INSERT INTO customers VALUES (100, 'Laiq', 'Mr.', 'Paris', 2008)");


Using Resultset:
            ResultSet is an interface found in java.sql package. It actually represents a table in the memory containing all the records fetched from the database in result of a query.

Code:
String name, brand ;
float price;

ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
while ( rs.next() ) {
name = rs.getString("name");
brand = rs.getString("brand");
price = rs.getFloat("price");
}

Getting number of rows updated
            Statement’s executeUpdate(…) method return no of row modified. So you can easily know how many rows were modified by your update query.

Code:
int rows = stmt.executeUpdate( "UPDATE customer SET
cust_name = ‘Laiq’ WHERE cust_id = 100" ) ;
System.out.println( rows + " Rows modified" ) ;

Change( Screen) Windows display resolution.

'Using this code to change Screen Resolution......... or your computer
' this code is use for VB 6.0

'********************** Module*****************
Declarations
Public Const EWX_LOGOFF = 0
Public Const EWX_SHUTDOWN = 1
Public Const EWX_REBOOT = 2
Public Const EWX_FORCE = 4
Public Const CCDEVICENAME = 32
Public Const CCFORMNAME = 32
Public Const DM_BITSPERPEL = &H40000
Public Const DM_PELSWIDTH = &H80000
Public Const DM_PELSHEIGHT = &H100000
Public Const CDS_UPDATEREGISTRY = &H1
Public Const CDS_TEST = &H4
Public Const DISP_CHANGE_SUCCESSFUL = 0
Public Const DISP_CHANGE_RESTART = 1

Type typDevMODE
    dmDeviceName       As String * CCDEVICENAME
    dmSpecVersion      As Integer
    dmDriverVersion    As Integer
    dmSize             As Integer
    dmDriverExtra      As Integer
    dmFields           As Long
    dmOrientation      As Integer
    dmPaperSize        As Integer
    dmPaperLength      As Integer
    dmPaperWidth       As Integer
    dmScale            As Integer
    dmCopies           As Integer
    dmDefaultSource    As Integer
    dmPrintQuality     As Integer
    dmColor            As Integer
    dmDuplex           As Integer
    dmYResolution      As Integer
    dmTTOption         As Integer
    dmCollate          As Integer
    dmFormName         As String * CCFORMNAME
    dmUnusedPadding    As Integer
    dmBitsPerPel       As Integer
    dmPelsWidth        As Long
    dmPelsHeight       As Long
    dmDisplayFlags     As Long
    dmDisplayFrequency As Long
End Type

Declare Function EnumDisplaySettings Lib "user32" Alias "EnumDisplaySettingsA" (ByVal lpszDeviceName As Long, ByVal iModeNum As Long, lptypDevMode As Any) As Boolean
Declare Function ChangeDisplaySettings Lib "user32" Alias "ChangeDisplaySettingsA" (lptypDevMode As Any, ByVal dwFlags As Long) As Long
Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long

'********************************************************************************************************************************************************************
'**************************Form******************************

Dim ScreenWidth As Integer
Dim ScreenHeight As Integer



Private Sub Command1_Click()
'Code:
'Following Text Boxes is the parameters for the screen resulution
'eg. 800*600
Dim typDevM As typDevMODE
Dim lngResult As Long
Dim intAns    As Integer
ScreenWidth = Val(Text1.Text) '800
ScreenHeight = Val(Text2.Text) '600

' Retrieve info about the current graphics mode
' on the current display device.
lngResult = EnumDisplaySettings(0, 0, typDevM)

' Set the new resolution. Don't change the color
' depth so a restart is not necessary.
With typDevM
    .dmFields = DM_PELSWIDTH Or DM_PELSHEIGHT
    .dmPelsWidth = ScreenWidth  'ScreenWidth (640,800,1024, etc)
    .dmPelsHeight = ScreenHeight 'ScreenHeight (480,600,768, etc)
End With

' Change the display settings to the specified graphics mode.
lngResult = ChangeDisplaySettings(typDevM, CDS_TEST)
Select Case lngResult
    Case DISP_CHANGE_RESTART
        intAns = MsgBox("You must restart your computer to apply these changes." & _
            vbCrLf & vbCrLf & "Do you want to restart now?", _
            vbYesNo + vbSystemModal, "Screen Resolution")
        If intAns = vbYes Then Call ExitWindowsEx(EWX_REBOOT, 0)
    Case DISP_CHANGE_SUCCESSFUL
        Call ChangeDisplaySettings(typDevM, CDS_UPDATEREGISTRY)
        Message = MsgBox("Screen resolution changed", vbInformation, "Resolution Changed ")
    Case Else
        Message = MsgBox("Mode not supported", vbSystemModal, "Error")
End Select

End Sub

Digital clock by using timer (swing) in Java

Here is a piece of code to build a Java clock, using swing,


        Timer t = new Timer(1000, updateClockAction);
        t.start();



ActionListener updateClockAction = new ActionListener() {
  public void actionPerformed(ActionEvent e) {
      // Assumes clock is a custom component
     lblTime.setText(System.currentTimeMillis()+"");
      // OR
    
      // Assumes clock is a JLabel
      lblTime.setText(new Date().toString());
    }
};




Digital clock by using Java

Here is a piece of code to build a Java clock, that uses threads, gets the data for time automatically and is not interrupted if you click something else on the window. There are some comments around the code to help you understand what's happening.

import java.awt.*;
import javax.swing.*;      
import java.util.*;

class Clock extends JFrame implements Runnable
{
  Thread runner; //declare global objects
  Font clockFont;

     public Clock()
     {
       super("Java clock");
       setSize( 350, 100);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setVisible(true);
       setResizable(false);                             //create window
  
       clockFont = new Font("Serif", Font.BOLD, 40);    //create font instance
      
       Container contentArea = getContentPane();
       ClockPanel timeDisplay = new ClockPanel();


       contentArea.add(timeDisplay);                    //add components
       setContentPane(contentArea);
       start();                                         //start thread running
    
     }
        
     class ClockPanel extends JPanel
     {
      public void paintComponent(Graphics painter )
        {
        Image pic =
          Toolkit.getDefaultToolkit().getImage("background.jpg");
        
         if(pic != null)
          
            painter.drawImage(pic, 0, 0, this);     //create image
                     
//if I didn't use a background image I would have used the setColor and fillRect methods to set background
    
          painter.setFont(clockFont);                   //create clock components
          painter.setColor(Color.black);
          painter.drawString( timeNow(), 60, 40);
        }
     }
    
     //get current time
     public String timeNow()
     {
       Calendar now = Calendar.getInstance();
       int hrs = now.get(Calendar.HOUR_OF_DAY);
       int min = now.get(Calendar.MINUTE);
       int sec = now.get(Calendar.SECOND);
      
       String time = zero(hrs)+":"+zero(min)+":"+zero(sec);
      
       return time;
     }
   
     public String zero(int num)
     {
       String number=( num < 10) ? ("0"+num) : (""+num);
       return number;                                    //Add leading zero if needed
      
     }
         
     public void start()
     {
       if(runner == null) runner = new Thread(this);
       runner.start();                                  //method to start thread
     }


     public void run()
     {
       while (runner == Thread.currentThread() )
       {
        repaint();
                                                         //define thread task
           try
             {
               Thread.sleep(1000);
             }
              catch(InterruptedException e)
                  {
                    System.out.println("Thread failed");
                  }                
       }
     }
    
     //create main method
     public static void main(String [] args)
     {
       Clock eg = new Clock();
     }
}


Convert Number to String

Convert Number to String in Java using Swing..... (Editor use: Net Bean)





firstly create new project. in this project add one Java class file and name this file "EnglishNumberToWords.Java"
 and copy following line of code in this file.....

*************************Code********************************



package number;
import java.text.DecimalFormat;

public class EnglishNumberToWords {

  private static final String[] tensNames = {
    "",
    " ten",
    " twenty",
    " thirty",
    " forty",
    " fifty",
    " sixty",
    " seventy",
    " eighty",
    " ninety"
  };

  private static final String[] numNames = {
    "",
    " one",
    " two",
    " three",
    " four",
    " five",
    " six",
    " seven",
    " eight",
    " nine",
    " ten",
    " eleven",
    " twelve",
    " thirteen",
    " fourteen",
    " fifteen",
    " sixteen",
    " seventeen",
    " eighteen",
    " nineteen"
  };

  private static String convertLessThanOneThousand(int number) {
    String soFar;

    if (number % 100 < 20){
      soFar = numNames[number % 100];
      number /= 100;
    }
    else {
      soFar = numNames[number % 10];
      number /= 10;

      soFar = tensNames[number % 10] + soFar;
      number /= 10;
    }
    if (number == 0) return soFar;
    return numNames[number] + " hundred" + soFar;
  }


  public static String convert(long number) {
    // 0 to 999 999 999 999
    if (number == 0) { return "zero"; }

    String snumber = Long.toString(number);
   String snumber1 = Long.toString(number);
    // pad with "0"
    String mask = "000000000000";
    String mask1 =  "000000000";
    DecimalFormat df = new DecimalFormat(mask);
    DecimalFormat df1 = new DecimalFormat(mask1);

    snumber = df.format(number);
    snumber1 = df1.format(number);
  
    // XXXnnnnnnnnn
    int billions = Integer.parseInt(snumber.substring(0,3));
    int coror = Integer.parseInt(snumber1.substring(0, 2));

    // nnnXXXnnnnnn
    int millions  = Integer.parseInt(snumber.substring(3,6));
    int lakh = Integer.parseInt(snumber1.substring(2,4));
    int thousand = Integer.parseInt(snumber1.substring(4,6));
    int hundred = Integer.parseInt(snumber1.substring(6,9));
    //System.out.println("---1---"+coror+"-------2--------"+lakh+"-----3--------"+thousand+"-------4-------"+hundred);
    String corors;
    switch(coror){
         case 0:
             corors = "";
             break;
        case 1:
            corors = convertLessThanOneThousand(coror)+" corror";
            break;
         default:
            corors = convertLessThanOneThousand(coror)+" corror";
      
    }
    String result1 =  corors;
    String lakhs;
    switch(lakh){
        case 0 :
            lakhs = "";
            break;
        case 1  :
            lakhs = convertLessThanOneThousand(lakh)+" lakh";
            break;
            default:
                lakhs = convertLessThanOneThousand(lakh)+" lakh";
              
    }
    result1 = result1+lakhs;
    String thou;
    switch(thousand){
        case 0 :
            thou = "";
            break;
        case 1:
            thou =lakhs = convertLessThanOneThousand(thousand)+" thausands";
            break;
            default:
                thou =lakhs = convertLessThanOneThousand(thousand)+" thausands";
    }
    result1 = result1+thou;
    result1 = result1+convertLessThanOneThousand(hundred);

    // nnnnnnXXXnnn
    int hundredThousands = Integer.parseInt(snumber.substring(6,9));
    // nnnnnnnnnXXX
    int thousands = Integer.parseInt(snumber.substring(9,12));  

    String tradBillions;
    switch (billions) {
    case 0:
      tradBillions = "";
      break;
    case 1 :
      tradBillions = convertLessThanOneThousand(billions)
      + " billlions ";
      break;
    default :
      tradBillions = convertLessThanOneThousand(billions)
      + " Billions ";
    }
    String result =  tradBillions;

    String tradMillions;
    switch (millions) {
    case 0:
      tradMillions = "";
      break;
    case 1 :
      tradMillions = convertLessThanOneThousand(millions)
      + " million ";
      break;
    default :
      tradMillions = convertLessThanOneThousand(millions)
      + " million ";
    }
    result =  result + tradMillions;

    String tradHundredThousands;
    switch (hundredThousands) {
    case 0:
      tradHundredThousands = "";
      break;
    case 1 :
      tradHundredThousands = "one thousand ";
      break;
    default :
      tradHundredThousands = convertLessThanOneThousand(hundredThousands)
      + " thousand ";
    }
    result =  result + tradHundredThousands;

    String tradThousand;
    tradThousand = convertLessThanOneThousand(thousands);
    result =  result + tradThousand;

    // remove extra spaces!
    return result1.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
  }

  /**
   * testing
   * @param args
   */
  public static void main(String[] args) {
      System.out.println("my one"+EnglishNumberToWords.convert(237898555));
    System.out.println("*** " + EnglishNumberToWords.convert(0));
    System.out.println("*** " + EnglishNumberToWords.convert(1));
    System.out.println("*** " + EnglishNumberToWords.convert(16));
    System.out.println("*** " + EnglishNumberToWords.convert(100));
    System.out.println("*** " + EnglishNumberToWords.convert(118));
    System.out.println("*** " + EnglishNumberToWords.convert(200));
    System.out.println("***219 " + EnglishNumberToWords.convert(219));
    System.out.println("*** " + EnglishNumberToWords.convert(800));
    System.out.println("*** " + EnglishNumberToWords.convert(801));
    System.out.println("*** " + EnglishNumberToWords.convert(1316));
    System.out.println("*** " + EnglishNumberToWords.convert(1000000));
    System.out.println("*** " + EnglishNumberToWords.convert(2000000));
    System.out.println("*** " + EnglishNumberToWords.convert(3000200));
    System.out.println("*** " + EnglishNumberToWords.convert(700000));
    System.out.println("*** " + EnglishNumberToWords.convert(9000000));
    System.out.println("*** " + EnglishNumberToWords.convert(9001000));
    System.out.println("*** " + EnglishNumberToWords.convert(123456789));
    System.out.println("*** " + EnglishNumberToWords.convert(2147483647));
    System.out.println("*** " + EnglishNumberToWords.convert(3000000010L));
}
}


****************************************************************


after that create one Java Frame with one Text Box, one Button and labels, design same like as above image

after that at Button Click Event (ActionPerformed event) add following code.....


*************************Code***********************************

 int Number = Integer.parseInt(txtNumber.getText());
        String No2String = EnglishNumberToWords.convert(Number)+"";
        txtString.setText(No2String);

in this code assign text box value to a "Number" variable and pass this value to the Function in above code "EnglishNumberToWords.Convert(Number)" and after that print the value

***************************Thanks************************************
Note : this project is available at  http://www.planet-source-code.com site

Upload and Retrieve image using JSP.

Upload and Retrieve image using JSP.
          
  Hello friends,  I am write this blog for those programmer are required a code for “how to upload and retrieve images (photos) from server using JSP.”

There is two jsp files are used in this project, and this project following libraries are required.   
     commons-fileupload.jar
        commons-fileupload-1.2.1.jar
        commons-io-1.4

this project done using NetBeans IDE 6.9.1 IDE. and jdk1.6.0_23

Screen:





Code:
upload_file_multipale.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" errorPage="" %> 
<%@ page import="java.util.List"%> 
<%@ page import="java.util.Iterator"%> 
<%@ page import="java.io.File"%> 
<%@ page import="org.apache.commons.fileupload.*"%> 
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> 
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.lang.Exception"%>


<center>
            <table border="2">
            <tr><td><h1>Your files are uploading.....</h1></td></tr>
            <%
       
                 String itemName="";
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                       
                 if (!isMultipart){
                         out.println("The Form is not Multipart!!!!!");
                 }
                else
                {
                         FileItemFactory  factory = new DiskFileItemFactory();
                         ServletFileUpload upload = new ServletFileUpload(factory);
                         List items = null;
                         try {
                                        items = upload.parseRequest(request);
                         } catch (FileUploadException  e) {
                                        out.println(e.toString());
                         }
                                                Iterator itr = items.iterator();
                                   
                                                while (itr.hasNext()) {
                                                            FileItem item = (FileItem) itr.next();
                                                            if (item.isFormField()){
                                                                         String name = item.getFieldName();
                                                                         String value = item.getString();
                                                            }
                                                            else {
                                                                        try {
                                                                                     itemName = item.getName();
                                                                                    itemName = FilenameUtils.getName(itemName);
                                                                                    //out.println(itemName);

    File savedFile = new File(config.getServletContext().getRealPath("/")+"uploadedFiles/"+itemName);
                       item.write(savedFile);
                       session.setAttribute("FileName",itemName);
                                                                                   
                                                                       } catch (Exception e) {
                                                                                                out.println(e.toString());
                                                                        }
                                                            }
                                                }
                                    }
                        
            response.sendRedirect("/FileUpload/upload_file_multipale_html.jsp");
   %>
    </table>
   </center>




upload_file_multipale_html.jsp

<%@page import="java.io.File"%>
<html>

 <head>
     <title>Multipale file upload by using apache.commons.fileupload</title>
</head>
<body>
 <form action="upload_file_multipale.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">
   <center>
   <table border="2">
       <tr>
                   <td align="center"><b> Upload and Retrieve Image (Photo)by using apache.commons.fileupload in JSP &nbsp;</td>
       </tr>
       <tr>
           <td>&nbsp;</td>
       </tr>
       <tr>
           <td align="center">
                               Specify file:  <input name="file" type="file" id="file">
            </td>
        </tr>
         <tr>
                 <td>&nbsp;</td>
         </tr>
          <tr>
                <td align="center">
                <input type="submit" name="Submit" value="Submit files"/>
            </td>
             </tr>
         <tr>
             <td>&nbsp;</td>
         </tr>
          <tr>
             <td align="center">By Ajay Shilwant <br> Email: xijay.ss@gmail.com <br> My blog: ajayshilwant.blogspot.com</td>
          </tr>
    </table>
       <br><br><br>
    <table align="center" border="1">
           <td>
               <%
                   
                     String FileName = (String)session.getAttribute("FileName");
                     File savedFile = new File(config.getServletContext().getContextPath() +"/uploadedFiles/"+FileName  );
                   
                %>
                <img src="<%=savedFile %>" width="100" height="100">

           </td>
       </table>
   <center>
 </form>
 </body>
 </html>


This project is available at following links…
any problem, suggestion please send me, my email id  balaram36@gmail.com

Send mail using Jsp and Servlet.

 Hello firends,

using this blog you can send mail using JSP and Servlets, follow the following steps to design this application


Send mail using Jsp and Servlet.
  1.    Create new web project using netbean. 
  2.       For this project following 5 labraries are requered.
a.       activation.jar
b.      mail.jar
c.       mailapi.jar
d.      pop3.jar
e.      smtp.jar
3.       After adding this library in project bellow code is copy and paste in index.jsp file.

index.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Java Mail</title>
    </head>
    <body>
        <form action="sendMail.jsp" method="POST">
            <table border="0" align="center" cellpadding="5">
                <tbody>
                    <thead><tr> <td colspan="3" align="center">
                    <b> Send Mail </b> </td> </tr> </thead>
                    <tr>
                        <td> To </td> <td> : </td>
                        <td> <input type="text" name="to" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Subject </td> <td> : </td>
                        <td> <input type="text" name="subject" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Message </td> <td> : </td>
                        <td> <textarea name="message" rows="8" cols="30">
                        </textarea></td>
                    </tr>
                    <tr>
                        <td colspan="3" align="center">
                        <input type="submit" value="Send Mail" />

                        <input type="reset" value="Reset" />
                        <td>
                    </tr>
                </tbody>
            </table>
        </form>
    </body>
</html>


Screen of index.jsp


sendMail.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Send Mail</title>
    </head>
    <body>
        <jsp:useBean id="mail" scope="session" class="jMail.Mail" />
        <jsp:setProperty name="mail" property="to" param="to" />
        <jsp:setProperty name="mail" property="from"  value="smaple@gmail.com" />

                <!-- Note:  value = add your email id hear -->

        <jsp:setProperty name="mail" property="smtpServ" value="smtp.gmail.com" />
        <jsp:setProperty name="mail" property="subject" param="subject" />
        <jsp:setProperty name="mail" property="message" param="message" />

        <%
String to = mail.getTo();
int result;
result = mail.sendMail();
if(result == 0){
    out.println(" Mail Successfully Sent to "+to);
}
else{
    out.println(" Mail NOT Sent to "+to);
}
       %>
    </body>
</html>






Java File: 

Mail.java


package jMail;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail {
    private String to;
    private String from;
    private String message;
    private String subject;
    private String smtpServ;


    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }
    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getSmtpServ() {
        return smtpServ;
    }
    public void setSmtpServ(String smtpServ) {
        this.smtpServ = smtpServ;
    }

public int sendMail(){
        try
        {
            Properties props = System.getProperties();
              // -- Attaching to default Session, or we could start a new one --
              props.put("mail.transport.protocol", "smtp" );
              props.put("mail.smtp.starttls.enable","true" );
              props.put("mail.smtp.host",smtpServ);
              props.put("mail.smtp.auth", "true" );
              Authenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              // -- Create a new message --
              Message msg = new MimeMessage(session);
              // -- Set the FROM and TO fields --
              msg.setFrom(new InternetAddress(from));
              msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
              msg.setSubject(subject);
              msg.setText(message);
              // -- Set some other header information --
              msg.setHeader("MyMail", "Mr. XYZ" );
              msg.setSentDate(new Date());
              // -- Send the message --
              Transport.send(msg);
              System.out.println("Message sent to"+to+" OK." );
              return 0;
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
          System.out.println("Exception "+ex);
          return -1;
        }
  }

// Also include an inner class that is used for authentication purposes

private class SMTPAuthenticator extends javax.mail.Authenticator {
        @Override
  public PasswordAuthentication getPasswordAuthentication() {
         String username =  "sender@gmail.com";           // specify your email id here (sender's email id)
         String password = "password";                             // specify your password here
        return new PasswordAuthentication(username, password);
     }
  }
}




After complete the coding run the project.
                If any problem face then contact me at  “ xijay.ss@gmail.com “ and this project is also available at  www.project –source-code.com download and use.
Linlks:

http://zetcode.com/tutorials/jeetutorials/sendingemail/
http://ajayshilwant.blogspot.com/2011/05/send-mail-using-jsp-and-servlet.html

Send email with Attachments:



import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendAttachment extends HttpServlet {


public SendAttachment() {
super();
}


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String to = "balaram36@gmail.com";// change accordingly
final String user = "balaram.amma@gmail.com";// change accordingly
final String password = "hibernate";// change accordingly

// 1) get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com");// change
// accordingly
properties.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});

// 2) compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject("Message Aleart");

// 3) create MimeBodyPart object and set your message content
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");

// 4) create new MimeBodyPart object and set DataHandler object to
// this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();

String file = "C:\\Documents and Settings\\suresh\\My Documents\\Downloads\\Compressed\\SendAttachment.java";// change accordingly

DataSource source = new FileDataSource(file);
messageBodyPart2.setDataHandler(new DataHandler(source));
String filename=file.substring(file.lastIndexOf("\\")+1);
messageBodyPart2.setFileName(filename);

// 5) create Multipart object and add MimeBodyPart objects to this
// object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);

// 6) set the multiplart object to the message object
message.setContent(multipart);

// 7) send message
Transport.send(message);

System.out.println("message sent....");
} catch (MessagingException ex) {
ex.printStackTrace();
}
}

}