Tuesday, October 11, 2011

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();
}
}

}



Saturday, October 8, 2011

MyEclipse Shortcuts

Navigational Shortcuts
F10 Main menu
Shift F10 Context menu
Ctrl F10 View menu
   
Workspace navigation
F12 Activate editor
Ctrl+Shift+W Switch editor
Ctrl F6 Next editor
Ctrl Shift F6 Prev editor
Ctrl F7 Next workspace
Ctrl Shift F7 Prev workspace
Ctrl F8 Next perspective
Ctrl Shift F8 Prev perspective
Alt Left Back
Alt Right Forward
   
Files
Alt Shift S Show in…
Ctrl Shift R Jump to file
Ctrl N New file
Ctrl S Save file
Ctrl Shift S Save all files
Ctrl F4 Close file
Ctrl Shift F4 Close all files
   
Find
Ctrl L Goto line
Ctrl F Find
Ctrl J Incremental find
Ctrl Shift J Incremental find prev
Ctrl K Find next
Ctrl Shift K Find prev
Ctrl H Search workspace
Ctrl (dot) Navigate next
Ctrl (comma) Navigate prev
   
Java navigation
F3 Goto declaration
Ctrl Shift U Find references in file
Ctrl Shift G Find references in workspace
Ctrl G Find declarations in workspace
Ctrl Shift P Navigate to matching bracket/brace
Ctrl T Popup type hierarchy
Ctrl Shift T Open Type
Ctrl O Outline of current source
Ctrl F3 Outline of current cursor position
Ctrl Shift Arrow Jump beetween methods up or down
F2 Show Javadoc
F4 Show hierarchy
Ctrl Alt H Open call hierarchy
   
   
General editing
Alt Arrow Move line(s) up or down
Alt Shift Up Expand selection to enclosing element
Alt Shift Right Expand selection to next element
Alt Shift Left Expand selection to previous element
Alt Shift Down Restore previous selection
Ctrl Alt Arrow Duplicate line(s) up or down
Shift Enter Insert line below
Ctrl Shift Enter Insert line above
Ctrl D Delete line
Ctrl Shift Q Toggle Quick Diff
Ctrl Shift Y Convert to lowercase
Ctrl Shift X Convert to uppercase
   
Java editing
Alt Shift U Remove occurrence annotations
Ctrl 1 Quick fix (works even when there are no errors
Ctrl Shift M Add import
Ctrl Shift F Reformat
Ctrl Shift O Organize Imports
Ctrl / Comment
Ctrl \ UnComment
Ctrl Shift Space Parameter hints
Ctrl Hyperlink identifier
Ctrl I Correct indentation
Shift Space Incremental content assist
   
Debugger
F5 Step into
F6 Step over
F7 Run to return
F8 Resume
F9 Relaunch last
F11 Run/debug last
Ctrl F11 Run
Ctrl Shift B Toggle breakpoint
Ctrl D Display
Ctrl Q Inspect
Ctrl R Run to line
Ctrl U Run snippet
   
Refactoring
Alt T Refactoring menu
Ctrl Shift Z Undo refactor
Ctrl Shift Y Redo refactor
Alt Shift R Rename
Alt Shift V Move
Alt Shift I Inline
Alt Shift M Extract method
Alt Shift L Extract local
Alt Shift C Change method signature
   
Misc
F5 Refresh
F1 Infopop
F2 Show resizeable hover