Wednesday, 27 March 2013

Check Valid extension of file at client side while uploding file

This following example allow to user upload only pdf file.for this example we need the jquery.js file.
<html>
<head>
<script src="jquery.js"></script>
<style>
body {
    margin:1em;
    font-size:.9em;
}
h1 {
    margin:1em 0;
    font-weight:bold;
}
h1:not(:first-of-type) {
    border-top:1px solid #ccc;
    padding:1em 0 0;
}
p {
    margin:1em 0;
}
p label {
    color:#333;
    font-family:sans-serif;
    display:inline-block;
    padding:.1em .1em .1em .3em;
    background:#f7f7f7;
    border:1px solid #ccc;
}
aside {
    margin-top:-.5em;
}
aside p {
    color:#333;
    font-size:.8em;
    font-family:sans-serif;
}

</style>
<script>
function getExtension(filename)
{

    var parts = filename.split('.');
    return parts[parts.length - 1];
}

function isPDF(filename)
{
    var ext = getExtension(filename);
    switch (ext.toLowerCase())
    {
    case 'pdf':
   
        /*
        etc
        like
        'xsl'
        */
        return true;
    }
    return false;
}

function failValidation(msg)
{
            alert(msg);
            return false;
}
function validate()
{      
        var file = $('#file');    
       
        if (!isPDF(file.val()))
        {
            return failValidation('Please select a valid file');
        }
               
        // indicate success with alert for now
        alert('Valid file');
        return true;
 }

</script>
</head>
<body>

<form name="frmpdf" action="connect.jsp" onsubmit="return validate()">
<h1>Match all pdf  files (application/pdf)</h1>
<p><label>Pdf File <input type="file" id="file" accept="application/pdf"></label></p>
<input type="submit" value="submit">
</form>
</body>
</html>

for checking image you can write following function.
function isImage(filename) 
 {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) 
   {
    case 'jpg':
    case 'gif':
    case 'bmp':
        //etc
        return true;
    }
    return false;
}

Tuesday, 26 March 2013

How to read and write value in List,Map,Set using getter and setter method in java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.*;


public class CollectionEG
{

private Set setv;
private List listv;
private Map<String,String> mapv;


public Set getSetv() {
    return setv;
}
public void setSetv(Set setv) {
    this.setv = setv;
}
public List getListv() {
    return listv;
}
public void setListv(List listv) {
    this.listv = listv;
}
public Map<String, String> getMapv() {
    return mapv;
}
public void setMapv(Map<String, String> mapv) {
    this.mapv = mapv;
}

public static void main(String args[])
{
    CollectionEG cd=new CollectionEG();


    //This example for Map
    Map<String,String> map=new HashMap<String,String>();

        map.put("one","1");
        map.put("two","2");
        map.put("three","3");

        cd.setMapv(map);
        map=null;
        map=cd.getMapv();


        Set s=map.entrySet();
        Iterator mapIterator = s.iterator();
        System.out.println("Map Demo");
        while(mapIterator.hasNext())
        {
            Map.Entry mapEntry = (Map.Entry) mapIterator.next();
            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();
            //getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();
            System.out.println("Key : " + keyValue + "= Value : " + value);

        }



    //This example for List
    System.out.println("List Demo");
    List list=new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    cd.setListv(list);

    list=null;
    list=cd.getListv();
    for(int i=0;i<list.size();i++)
    {
        System.out.println(list.get(i));
    }


    //This example for Set
    System.out.println("Set Demo");
      Set<Integer> set = new TreeSet<Integer>();

    set.add(1);
    set.add(2);
    set.add(3);

    cd.setSetv(set);

    set=null;
    set=cd.getSetv();

    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext())
    {
        Integer setElement = iterator.next();
        System.out.println(setElement);
    }

  }
}

Friday, 22 March 2013

How to set session and destroy session and setInactive time of session in jsp

1)Set the session
<%
String uname="ishwar";
session.setAttribute("name",uname);
%>

2)read the value of session and if user is not login then redirect to login.jsp page
<%
if(session.getAttribute("name")==null)
{
    out.println("<script>alert('please login first')</script>");
    out.println("<script>location.href='login.jsp'</script>");
   
}
else
{
    String uname=(String)session.getAttribute("name");
    out.println("uname is"+uname);
}
%>

3)Destroy or Delete the session
<%
    session.invalidate();
%>

4)set inactive time for session

for programmatically set session
This for 10 seconds
<% session.setMaxInactiveInterval(10); %>

This will set your session to keep everything till the browser is closed
<% session.setMaxInactiveInterval(-1); %>

This should set it for 1 day
<% session.setMaxInactiveInterval(60*60*24); %>

Other way you can set inactive time for session in web-inf file
<web-app>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
</web-app>

Thursday, 21 March 2013

How to disable Browser back button using java script

<html>
<body>
<head>
<SCRIPT type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</SCRIPT>
</head>
<body onload="noBack();"  onpageshow="if (event.persisted) noBack();" onunload="">
<h1>Disable Back Button Demo</h1>
</body>
</html>

Tuesday, 19 March 2013

how to find current location using javascript & jquery

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js">
    </script>
    <script src="http://j.maxmind.com/app/geoip.js"></script>
   <script src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script>

    // wire up button click
    function fun1()
    {
        
        // test for presence of geolocation
        if (navigator && navigator.geolocation)
         {
            // make the request for the user's position
            navigator.geolocation.getCurrentPosition(geo_success, geo_error);
        }
         else
         {
            // use MaxMind IP to location API fallback
            printAddress(geoip_latitude(), geoip_longitude(), true);
        }
    }

function geo_success(position)
 {
    printAddress(position.coords.latitude, position.coords.longitude);
}

function geo_error(err)
{
    // instead of displaying an error, fall back to MaxMind IP to location library
    printAddress(geoip_latitude(), geoip_longitude(), true);
}

// use Google Maps API to reverse geocode our location
function printAddress(latitude, longitude, isMaxMind)
{
        // set up the Geocoder object
    var geocoder = new google.maps.Geocoder();

    // turn coordinates into an object
    var yourLocation = new google.maps.LatLng(latitude, longitude);

     // find out info about our location
    geocoder.geocode({ 'latLng': yourLocation }, function (results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {
            if (results[0])
            {
                $('body').append('<p>Your Address:<br />' +
                    results[0].formatted_address + '</p>');
            } else
            {
                error('Google did not return any results.');
            }
        }
        else
        {
            error("Reverse Geocoding failed due to: " + status);
        }
    });

  
}

function error(msg) {
    alert(msg);
}
</script>

</head>
<body>
<b id="my"></b>
<input type="button" id="go" value="Click Me To Find Your Address" onclick="fun1()">
</body>
<script>
</script>
</html>

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