Tuesday 26 February 2013

File Upload



To Upload the File we use <s:file>  struts tag.


Web.xml
  Following is the content of web.xml file:
<?xml version="1.0" encoding="UTF-8" ?>

   Demo
   
    Image.jsp
   
 
   
            struts2
            
                  org.apache.struts2.dispatcher.FilterDispatcher
            
   
      
            struts2
            /*
      

Struts.xml
  struts.xml configuration file as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">


      
      
      
           
   
     
      
       
          2097152
          
            image/png,image/gif,image/jpeg,image/pjpeg
          
       
       
       successFile.jsp
       Image.jsp
        
   

Image.jsp
We have to create  Image.jsp in the WebContent folder, to upload image.
Code-
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
Upload
</head>

<body>

File Upload

</body> </html>
successFile.jsp
When File Upload Successfully then successFile.jsp is called.
Code-
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
Upload Image
</head>
<body>
    

File Upload Example

Content Type: <s:property value="userImageContentType"/> File Name: <s:property value="userImageFileName"/> Uploaded Image: <img src="<s:property value="userImageFileName"/>"/> </body> </html>
FileUploadAction.java
 The next step is to create an Action method that takes care of sending the email. Let us create a new class called FileUploadAction.java.
Code-
package view;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements
       ServletRequestAware {
   private File userImage;
   private String userImageContentType;
   private String userImageFileName;
   private HttpServletRequest servletRequest;

   public String execute() {
       try {
           String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
           System.out.println("Server path:" + filePath);
           File fileToCreate = new File(filePath, this.userImageFileName);
           FileUtils.copyFile(this.userImage, fileToCreate);
       } catch (Exception e) {
           e.printStackTrace();
           addActionError(e.getMessage());
           return INPUT;
       }
       return SUCCESS;
   }
   public File getUserImage() {
       return userImage;
   }
   public void setUserImage(File userImage) {
       this.userImage = userImage;
   }
   public String getUserImageContentType() {
       return userImageContentType;
   }
   public void setUserImageContentType(String userImageContentType) {
       this.userImageContentType = userImageContentType;
   }
   public String getUserImageFileName() {
       return userImageFileName;
   }
   public void setUserImageFileName(String userImageFileName) {
       this.userImageFileName = userImageFileName;
   }
   @Override
   public void setServletRequest(HttpServletRequest servletRequest) {
       this.servletRequest = servletRequest;
   }
}
Output:-

When File successfully Uploaded.

Sending Email


Required Jar

To Send an email using your Struts 2 application. We required mail.jar from JavaMail API 1.4.4 and place the mail.jar file in your WEB-INF\lib folder where other jar files are placed.
You can also Download this jar From Here.


Web.xml
  Following is the content of web.xml file:
<?xml version="1.0" encoding="UTF-8"?>

   Demo
   
    Email.jsp
   
 
   
            struts2
            
                  org.apache.struts2.dispatcher.FilterDispatcher
            
   
      
            struts2
            /*
      
     

Struts.xml
  struts.xml configuration file as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">


      
      
      
           
      
      
         /success.jsp
         /error.jsp
      
     
      


Email.jsp

We have to create  Email.jsp in the WebContent folder, to send the Email.

Code-

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
Email Form
</head>
<body>
 
To send you have enter a Gmail username and password <s:textfield name="from" label="From "/> <br/> <s:password name="password" label="Password"/> <br/> <s:textfield name="to" label="To "/> <br/> <s:textfield name="subject" label="Subject"/> <br/> <s:textfield name="body" label="Body "/> <br/> <input type="submit" value="Send Email"/>
</body> </html>

Success.jsp
When Email send Successfully then success.jsp is called.
Code-
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
Email Success
</head>
<body>
   Your email to <s:property value="to"/> was sent successfully.
</body>
</html> 
Error.jsp

When Email send Successfully then error.jsp is called.

Code-

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
Email Error
</head>
<body>
   There is a problem sending your email to <s:property value="to"/>.
</body>
</html> 

EmailAction.java

 The next step is to create an Action method that takes care of sending the email. Let us create a new class called EmailAction.java.



Code-
package view;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.opensymphony.xwork2.ActionSupport;
public class EmailAction extends ActionSupport {
   private String from;
   private String password;
   private String to;
   private String subject;
   private String body;
   static Properties properties = new Properties();
   static
   {
      properties.put("mail.smtp.host", "smtp.gmail.com");
      properties.put("mail.smtp.socketFactory.port", "465");
      properties.put("mail.smtp.socketFactory.class",
                     "javax.net.ssl.SSLSocketFactory");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.port", "465");
   }
   public String execute()
   {
      String ret = SUCCESS;
      try
      {
         Session session = Session.getDefaultInstance(properties, 
            new javax.mail.Authenticator() {
            protected PasswordAuthentication
            getPasswordAuthentication() {
            return new
            PasswordAuthentication(from, password);
            }});
         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to));
         message.setSubject(subject);
         message.setText(body);
         Transport.send(message);
      }
      catch(Exception e)
      {
         ret = ERROR;
         e.printStackTrace();
      }
      return ret;
   }
   public String getFrom() {
      return from;
   }
   public void setFrom(String from) {
      this.from = from;
   }
   public String getPassword() {
      return password;
   }
   public void setPassword(String password) {
      this.password = password;
   }
   public String getTo() {
      return to;
   }
   public void setTo(String to) {
      this.to = to;
   }
   public String getSubject() {
      return subject;
   }
   public void setSubject(String subject) {
      this.subject = subject;
   }
   public String getBody() {
      return body;
   }
   public void setBody(String body) {
      this.body = body;
   }
   public static Properties getProperties() {
      return properties;
   }
   public static void setProperties(Properties properties) {
      EmailAction.properties = properties;
   }
}     
Output:-

When Email successfully send.

Give Error when unsuccessful.



                                                           Download Source Code
 
 
 
 

    Categories

    Text Widget

    Followers