Tuesday, 19 March 2013

How to upload image and read other form data too in jsp

Here we are using the two packages for upload the picture which provides by apache.org.
1)commons-fileupload-1.2.2
2)commons-io-2.4
This two files you can download from google or you can download full example of this program.
after download this two files you have to paste .jar file from this two folder into apche tomate lib files
.these are files
1)commons-fileupload-1.2.2.jar,commons-io-2.4.jar
The first jar files is used for upload your image and second jar file provides functionality for reading the stream data and save data to a file beyond that point.
eg.DeferredFileOutputStream-This class provides utility for store file into disk and this class
available in commons-io-2.4.jar

first your index.html file

<html>
    <head>
        <title>Upload photos</title>
    </head>
    <body>
    <form name="fupload" action="upload.jsp" method="post" enctype="multipart/form-data">
    <table>
    <tr>
    <td>Name:</td>
    <td><input type="text" name="uname" id="uname"></td>
    <tr>
    <tr>
    <td>Address:</td>
    <td><textarea  name="address" id="address"></textarea></td>
    <tr>
    <td>Profile Picture:</td><td><input type="file" name="photo" id="photo"/></td>

    <tr><td><input type="submit" value="upload"/></td>
    </tr>
    </form>
    </body>
</html>

This is above html file which used select the pdf file.and when you uploding any file you have to specify the form attribute  enctype="multipart/form-data" and method="post". after upload your file when you click on submit button its will call the upload.jsp file.

second is upload.jsp fle

<%@ page import="java.util.List" %>
   <%@ page import="java.util.Iterator" %>
   <%@ page import="java.io.File" %>
   <%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
   <%@ page import="org.apache.commons.fileupload.disk.*"%>
   <%@ page import="org.apache.commons.fileupload.*"%>
  
   <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  
<%

     boolean isMultipart = ServletFileUpload.isMultipartContent(request);
     if (!isMultipart)
     {
     }
     else
     {
       FileItemFactory factory = new DiskFileItemFactory();
       ServletFileUpload upload = new ServletFileUpload(factory);
       List items = null;
       try
       {
               items = upload.parseRequest(request);
       }
       catch (FileUploadException e)
       {
               e.printStackTrace();
       }
       Iterator itr = items.iterator();     //this will create iterator object from list..used for traversing the data.
       String uname="",uadd="";
       while (itr.hasNext())
       {
           FileItem item = (FileItem) itr.next();
         
           if (item.isFormField())   //checking if its normal field then we read as normal. no need to store in disc
            {
                        String name = item.getFieldName();
                       String value = item.getString();
                                           
                       if(name.equals("uname"))
                       {
                               uname=value;
                              
                        }
                       else if(name.equals("address"))
                        { 
                                   uadd=value;                       
                           
                        }                                                       
                                
            }
            else                                      //this else part for process about PDF file
             {
                try
                {
       
                   String itemName = item.getName();    //this will return the pdf file name
                   String filename=request.getRealPath("") + "/uploads/";
                   filename=filename+itemName;       //now concatenation the file name with upload  path.
                   File savedFile=new File(filename);
                      
                       item.write(savedFile);    //saving file into disc,item contain which you select the file.
                                                                //here item will copy into the savedFile and store into disk

                       out.println("successfull");
                       response.sendRedirect("index.html");
                }
                catch(Exception ste)
                {
                    out.println(ste);
                }
              }
          }
          out.println("the user name is"+uname);
          out.println("the address is"+uadd);
       }
%>
The above file which is used the
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
This will used for checking the whether your request is contain file data and other data or not.

for save pdf file into disc we need to creare FileItemFactory object and ServletFileUpload object

 FileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);

for reading the request we need to parse and it will return the List types.
items = upload.parseRequest(request);
Now items will contain the all data.

The request.getRealPath() will return the where deploy the your application and in my application i create uploads folder and i want to save pdf file in the uploads folder.


     



You can download full example from here

Friday, 15 March 2013

How Create From and To calander using Jquery

<html>
<head>
<link rel="stylesheet" href="css/jquery-ui.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
 $(function()
 {
$( "#from" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
</script>
</head>

<body>
<label for="from">From</label>
<input type="text" id="from" name="from" />
<label for="to">to</label>
<input type="text" id="to" name="to" />

</body>
</html>
The view of above file is.


You can download above example from here

Monday, 11 March 2013

how to fill select option tag value base on other select option tag without realoading page using jQuery in jsp page.

 Hi friends.before jQuery was not introduce that time we filling the other select tag option value base on reloading  the page but in this situation the entire page reload and if user is selected data that also lost so overcome this problem jQuery is come so i am writing following example which is filling select tag option value base on select option value of other select tag without reloading entire page.

In this example when user change value of one select tag the second select tag option value will  fill base on value user select in first select tag. i am filling the select tag value from database so i need to connect with database also.

->first you need to create jsp file for establish connection with database.
Connection.jsp
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*" %>
<%!
    Connection con;
    String sql="";
    ResultSet rs;
    Statement stmt;
%>
  
<%  
   try
    {      
         Class.forName("com.mysql.jdbc.Driver").newInstance();
          con = DriverManager.getConnection("jdbc:mysql://localhost/cricketdb", "root", "");   
          stmt=con.createStatement();
       

   }
  catch(SQLException sa)
  {
     out.println("Error loading driver:" + sa.getMessage());  
  }
%>
This above file only used for establishing connection between jsp program and the MySQL database. so after creating this file we need to just  include this file whenever we need to connect with database.

->second step create jsp file which contain select tag
Cricket.jsp
<html>
<head>
    <title>Cricket View Data</title>
<script  src="jquery.js"></script>
<script>

    function fillplayer()
    {
      
        var countryv=document.getElementById("country").value;
      
        var url="connectCricket.jsp?country="+countryv;
      
        $.ajax({
            url:url,
            type:"POST",
            success:function(results)
            {
               
                document.getElementById('player').innerHTML=results;

            },
            error:function(data)
            {
                alert('error'+data);
            }
            });

    }
    </script>
    </head>
    <body>
    <form name="nm">
     Country<select  name="country" id="country" onchange="fillplayer()">
            <option value="">Select</option>
            <option value="india">india</option>
            <option value="pakistan">Pakistan</option>
            </select>
            <br/>
      
       Player:  <select name="player" id="player">
                  <option value="">Select players</option>
                </select>
      
    </form>
    </body>
    </html>

This above file Contain the two select tag one Country and second is Player. when user change the Country name then fillplayer() function will invokes and the fillplayer() function will send request to connectCricket.jsp file and also i am passing the parameter which is value selected in Country select tag so base on Country select tag value the connectCricket.jsp will give back response and if its successful then 
success:function(results) will invoke. if in case connectCricket.jsp file return error then it will invoke the error:function(data) and display error.

if its success then i am writing in success funtion
document.getElementById('player').innerHTML=results;
here
'player'=this is an id of Player select tag
The innerHTML is an property of document which is replace the content of select tag so here 'results' which is response comes from the connectCricket.jsp file i am assigning to player.so it will replace the value of select tag option.



->Third step create connectCricket.jsp file which file called by the jQuery(internally by the AJAX) and send back response.
connectCricket.jsp
<%@ include file="connect.jsp"%>
<%
   String country=request.getParameter("country");
      
  
   sql="select *from players where country='"+country+"'";
   rs=stmt.executeQuery(sql);
 
   String buffer="";
   while(rs.next())
   {
     
       buffer=buffer+"<option value='"+rs.getString("pname")+"'>"+rs.getString("pname")+"</option>";
   }
   out.println(buffer);
 %>

This file which read the 'country' name which send by the Ajax and base on this country value i am fetching data from database and dynamically creating option tag and storing into the one String buffer variable.after assigning all option to buffer variable i am just printing it using  'out.println(buffer)' so here i am printing the buffer variable which is contain the list of option so this output send back as a response.

after finish the execution of the above file its go back and base of response its will invoke either error function or success funtion.

if above file return list of option value then following function will invoke in the Cricket.jsp file

success:function(results)
now 'results' will contain the list of option

if above file  return error message then the error function will invoke in the Cricket.jsp file
error:function(data)
now 'data' is contain the error details.

 for above example you need to create database name cricketdb and table names players  which have follwoing fields.
country varchar2(10)
pname varchar2(10))

How to disabled and change color of particular date and display tooltips in datepicker

<html>
<head>

<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>

<style>

.wrapper {
    padding: 10px;
}
td.red span.ui-state-default {
    color: #f00;
}
td.green span.ui-state-default {
    color: #0f0;
}
td.yellow span.ui-state-default {
    color: #700;
}


</style>

<script type="text/javascript">
$(function() {

$('input').datepicker({
dateFormat: "yy-mm-dd",
minDate: "-0d",
    maxDate: "+90d",
    firstDay: 0,
    beforeShowDay: noWeekendsOrHolidaysOrBlockedDates

});

});


function noWeekendsOrHolidaysOrBlockedDates(date)
 {
    //var noWeekend = jQuery.datepicker.noWeekends(date);
    return setHoliDays(date);
}

// set holidays function which is configured in beforeShowDay

function setHoliDays(date)
{
    var day = date.getDay();
    if(day == 5 || day == 6)
        return [false, ''];

    if(date.getDate() == 11 || date.getDate() == 23)
        return [ false, 'holiday red', 'Red!' ];
    if(date.getDate() == 12 || date.getDate() == 22)
        return [ false, 'holiday green', 'Green!' ];
    if(date.getDate() == 24)
        return [ false, 'holiday yellow', 'all ready booked!' ];
    return [true, ''];
}
</script>
</head>


<body>

<div class="wrapper">
    <input type="text" id="b">
</div>
</body>
</html>
If you want to add more date then you can add in  the setHoliDays function as showing in above example.
You can download from here

Friday, 8 March 2013

How to Convert Date fomate in java or jsp

<%@ page import="java.text.*;"%>
        <%!
            String billdate="";
            SimpleDateFormat sdfSource,sdfDestination;
                    //there is sql Date is also availbe so u have to write following way
            java.util.Date date;
                    //this method convert user date to database formate
            public String UITODB(String bdate)
            {
                try
                {
                     sdfSource = new SimpleDateFormat("dd/MM/yyyy");
                     date = sdfSource.parse(bdate);
                     sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
                     billdate=sdfDestination.format(date);
                    
                }
                catch(Exception e)
                {
                   
                }
                return billdate;
               
            }
           
            //this method convert databse mysql formate to user date
            public String DBTOUI(String bdate)
            {
                try
                {
                     sdfSource = new SimpleDateFormat("yyyy-MM-dd");
                     date = sdfSource.parse(bdate);
                     sdfDestination = new SimpleDateFormat("dd/MM/yyyy");
                     billdate=sdfDestination.format(date);
                    
                }
                catch(Exception e)
                {
                   
                }
                return billdate;
               
            }
                      
          
        %>
        //how to call above function
       
    <%=UITODB("04/02/1987")%> //this will print:1987-02-04
   
    <%=DBTOUI("1987-02-04")%>  //this will print:04/02/1987

How to get todays day name using java

<%@ page import="java.util.*" %>
<%
        Calendar c = Calendar.getInstance();
        int day = c.get(Calendar.DAY_OF_WEEK);
        String dname="";
       
         switch(day)
          {
          case 1: dname="Sunday";
          break;
          case 2: dname="Monday";
          break;
          case 3: dname="Tueseday";
          break;
          case 4: dname="Wednesday";
          break;
          case 5: dname="Thursday";
          break;
          case 6: dname="Friday";
          break;
          case 7: dname="Saturday";
          break;
          }
          System.out.print("Todays Days is"+dname);
   
%>

Thursday, 7 March 2013

How to Read your email of gmail account using java mail api

import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;
import javax.activation.*;

public class FetchMail
{

    public static void main(String[] args) {

        // SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!!
        String host = "pop.gmail.com";
        // SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!!
        String user = "your user name";   //eg.  "ishwar"
        String password = "your gmail password";   //e.g "ishwar123"
        // SUBSTITUTE YOUR SUBJECT SUBSTRING TO SEARCH HERE!!!
        String subjectSubstringToSearch = "Test E-Mail through Java";

       
        Properties props = new Properties();
        props.put("mail.pop3s.starttls.enable", "true");
         Session session = Session.getDefaultInstance(props,null);

        try
         {

            // Get a Store object
            Store store = session.getStore("pop3s");
            store.connect(host,995,user, password);

            // Get "INBOX"
            Folder fldr = store.getFolder("INBOX");
            fldr.open(Folder.READ_WRITE);
            int count = fldr.getMessageCount();
            System.out.println(count  + " total messages");

            // Message numebers start at 1
            for(int i = 1; i <= count; i++)
            {
                        // Get  a message by its sequence number
                Message m = fldr.getMessage(i);

                // Get some headers
                Date date = m.getSentDate();
                Address [] from = m.getFrom();
                String subj = m.getSubject();
                String mimeType = m.getContentType();
                System.out.println(date + "\t" + from[0] + "\t" + subj + "\t" + mimeType);
            }

            // Search for e-mails by some subject substring.
            String pattern = subjectSubstringToSearch;
            SubjectTerm st = new SubjectTerm(pattern);
            // Get some message references
            Message [] found = fldr.search(st);

            System.out.println(found.length +" messages matched Subject pattern \"" +pattern + "\"");

            for (int i = 0; i < found.length; i++)
            {
                Message m = found[i];
                // Get some headers of email
                Date date = m.getSentDate();
                Address [] from = m.getFrom();
                String subj = m.getSubject();
                String mimeType = m.getContentType();
                System.out.println(date + "\t" + from[0] + "\t" + subj + "\t" + mimeType);

                Object o = m.getContent();
               
                if (o instanceof Multipart)
                {
                    System.out.print("**This is a Multipart Message.  ");
                    Multipart mp = (Multipart)o;
                    int count3 = mp.getCount();
                    System.out.println("It has " + count3 +
                        " BodyParts in it**");
                    for (int j = 0; j < count3; j++)
                    {
                        // Part are numbered starting at 0
                        BodyPart b = mp.getBodyPart(j);
                        String mimeType2 = b.getContentType();
                        System.out.println( "BodyPart " + (j + 1) +
                                            " is of MimeType " + mimeType);

                        Object o2 = b.getContent();
                        if (o2 instanceof String)
                        {
                            System.out.println("**This is a String BodyPart**");
                            System.out.println((String)o2);
                        }
                        else if (o2 instanceof Multipart)
                        {
                            System.out.print(
                                "**This BodyPart is a nested Multipart.  ");
                            Multipart mp2 = (Multipart)o2;
                            int count2 = mp2.getCount();
                            System.out.println("It has " + count2 +
                                "further BodyParts in it**");
                        }
                        else if (o2 instanceof InputStream) {
                            System.out.println(
                                "**This is an InputStream BodyPart**");
                        }
                    } //End of for
                }
                else if (o instanceof String)
                {
                    System.out.println("**This is a String Message**");
                    System.out.println((String)o);
                }
                else if (o instanceof InputStream)
                {
                    System.out.println("**This is an InputStream message**");
                    InputStream is = (InputStream)o;
                    // Assumes character content (not binary images)
                    int c;
                    while ((c = is.read()) != -1)
                    {
                        System.out.write(c);
                    }
                }

             

            } //End of for

           
            fldr.close(true);
            store.close();

        }
        catch (MessagingException mex)
        {
           
            mex.printStackTrace();
        }
        catch (IOException ioex)
        {
            ioex.printStackTrace();
        }

    }


}
for above program you need to download two jar file
1)jaf-1.1.1
2)javamail-1.4.5
One more things you need to enable the POP protocol in your gmail account .

  1. You login in your gmail account.
  2. Click on the Gear icon in the top right-hand corner of your screen and select Mail settings.
  3. Click on Forwarding and POP/IMAP.
  4. Under POP Download/Status select the Enable option that you prefer.
  5. Under POP Download/When messages are accessed with POP select the option that you prefer. We recommend that you select one of the options that leaves a copy of your messages on the server. This allows you to view your e-mails from more than one location and also insures that you always have a backup on the Gmail servers.
  6. Click Save Changes.