JSF File Upload Example

Here is one simple example to upload files in JSF with tomahawk framework

Software Used

1. JSF 1.2

2. Java 1.6

3. Tomahawk 1.1

3. Eclipse Juno

4. Tomcat 7

Libraries required

  1. Apache common-fileupload
  2. jsf-api
  3. jsf-impl
  4. jstl
  5. tomahawk.1.1.6
  6. tomahawk-facelets.1.1.6

Download tomahawk jars from http://myfaces.apache.org/tomahawk/download.html         

1.Create a Web application and JSF Page(FileuploadJSF.jsp)

<%@page import="java.io.FileFilter"%>
<%@page import="java.io.FilenameFilter"%>
<%@page import="java.io.File"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib uri="http://myfaces.apache.org/tomahawk" prefix="x"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<f:view>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
            <title>JSP Page</title>
        </head>
        <body>
            <h:form enctype="multipart/form-data">
                <h:panelGrid border="1" columns="2">
                    <h:outputText value="ID"></h:outputText>
                    <h:outputText value="File upload"></h:outputText>
                    <x:inputFileUpload id="file" value="#{fileUpload.upload}" required="false" size="40" />
                    <h:commandButton action="#{fileUpload.uploadFile}"  value="Add Files"></h:commandButton>
               </h:panelGrid>
            </h:form>        </body>
    </html>
</f:view>

2. Update Faces-config.xml

<navigation-rule>
              <from-view-id>/FileuploadJSF.jsp</from-view-id>
              <navigation-case>
                    <from-outcome>Success</from-outcome>
                     
                     <to-view-id>/FileuploadJSF.jsp</to-view-id>
                     <redirect></redirect>
              </navigation-case>
              <navigation-case>
                     <from-outcome>Failure</from-outcome>
                     <to-view-id>/FileuploadJSF.jsp</to-view-id>
              </navigation-case>
       </navigation-rule>
<managed-bean>
        <managed-bean-name>fileUpload</managed-bean-name>
        <managed-bean-class>com.jsf.FileUpload</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>

3. Create Managed Bean

package com.jsf;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.myfaces.custom.fileupload.UploadedFile;
 
public class FileUpload {
    private UploadedFile upload;
 
    public UploadedFile getUpload() {
        return upload;
    }
 
    public void setUpload(UploadedFile upload) {
        this.upload = upload;
    }
 
    public FileUpload() {
 
    }
 
    public String uploadFile() {
        File savedFileName;
        String dirPath = "D:\\vinod\\";
        InputStream fileContent = null;
        if (upload == null) {
            return "success";
        }
        try {
            fileContent = upload.getInputStream();
 
        } catch (IOException e) {
            e.printStackTrace();
        }
        String uploadFileName = trimFilePath(upload.getName());
        savedFileName = new File(dirPath + uploadFileName);
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(savedFileName));
        } catch (FileNotFoundException e) {
        }
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = fileContent.read(buffer)) >= 0) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
        }
        try {
            fileContent.close();
            bos.close();
        } catch (IOException e) {
        }
        return "success";
    }
 
    public static String trimFilePath(String fileName) {
        return fileName.substring(fileName.lastIndexOf("/") + 1).substring(
                fileName.lastIndexOf("\\") + 1);
    }
}

4. Update Web.xml

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <filter>
        <filter-name>extensionsFilter</filter-name>
        <filter-class>
            org.apache.myfaces.webapp.filter.ExtensionsFilter
        </filter-class>
        <init-param>
            <param-name>uploadMaxFileSize</param-name>
            <param-value>1000m</param-value>
        </init-param>
        <init-param>
            <param-name>uploadThresholdSize</param-name>
            <param-value>10000k</param-value>
        </init-param>
    </filter>
       <filter-mapping>
        <filter-name>extensionsFilter</filter-name>
        <url-pattern>*.jsf</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>extensionsFilter</filter-name>
        <url-pattern>/faces/*</url-pattern>
    </filter-mapping>
 

5. Deploy application on Tomcat

image

Download Source code

JSF File Upload Example

Java program to send email

Here is one simple example to send email from Java using gmail. Make sure that you added the java mail jars and change the from to address
 

Example

 
Add below dependency in your pom.xm
 
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4</version>
</dependency>
 
 

Create Java program to send email

Change email id and password accordingly.

package com.vinod.test;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
    public SendEmail() {
        SendMail("admin@gmail.com", "This is test message");
    }
    public void SendMail(String toAddress, String contentmessage) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.googlemail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("xxxxx@gmail.com",
                                "password");
                    }
                });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("xxxxxxx@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(toAddress));
            message.setSubject("my email");
            message.setText(contentmessage);
            Transport.send(message);
            System.out.println("Email Done");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String args[]) {
        new SendEmail();
    }
}

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts