跳至主要内容

JSF 2.2: File Upload

JSF 2.2: File Upload

Before 2.2, you have to use Richfaces, Primefaces like JSF components to provide file upload feature.
Or you must write a custom file upload component yourself.
Luckily this long waiting feature was finally added in JSF 2.2.

An example

In JSF 2.2, the FacesServlet is annotated with @MultipartConfig, which causes JSF can handle multpart form data correctly.
@MultipartConfig
public final class FacesServlet implements Servlet {}
The following is a simple facelets page, which includes a h:form and h:inputFile components.
<h:form enctype="multipart/form-data">
    <h:inputFile id="file" value="#{fileUploadBean.file}" />
    <h:commandButton value="Upload" action="#{fileUploadBean.upload()}"/>
</h:form>
The new inputFile component is provided for file upload purpose. The usage is simple. Like other input components, put it into a h:form, the enctype attribute must be changed to multipart/form-data explicitly , it is a must for file upload.
@Model
public class FileUploadBean {
    
    @Inject Logger log;
    
    private Part file;
    
    public void upload(){
        log.info("call upload...");      
        log.log(Level.INFO, "content-type:{0}", file.getContentType());
        log.log(Level.INFO, "filename:{0}", file.getName());
        log.log(Level.INFO, "submitted filename:{0}", file.getSubmittedFileName());
        log.log(Level.INFO, "size:{0}", file.getSize());
        try {
            
            byte[] results=new byte[(int)file.getSize()];
            InputStream in=file.getInputStream();
            in.read(results);         
        } catch (IOException ex) {
           log.log(Level.SEVERE, " ex @{0}", ex);
        }
        
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Uploaded!"));
    }

    public Part getFile() {
        return file;
    }

    public void setFile(Part file) {
        this.file = file;
    }
    
}
In the backend bean, use a standard Servlet 3 Part as converted type to warp the uploaded file info.
It is easy to read the uploaded file info from Part API.
NOTE: The getName method will return the client id, and getSubmittedFileName returns the original file name.
Uploaded file content can be read through the getInputStream method of Part.

Add a validator

As an example, a FileValidator is added to limit the uploaded file size.
@FacesValidator
public class FileValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        Part part = (Part) value;
        if(part.getSize()>1024){
           throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "file is too large", "file is too large"));
        }
    }

}
This is a standard JSF validator, which prevents a large-sized file to be uploaded. In the above example, if the size of the file to be uploaded is greater than 1024 bytes, a validation error will be displayed when file is being uploaded.
Update the faceslet page, apply the validtor to the inputFile component.
<h:inputFile id="file" value="#{fileUploadBean.file}" >
    <f:validator validatorId="fileValidator"/>
</h:inputFile>
<h:message for="file"/>
When the form is submitted, if the file size is greater than 1024 bytes, an error will be displayed near the input file field.
As you see, a small improvement is added to @FacesValidator. In JSF 2.2, it is not required to specify a validator id, and a default id will be assigned at runtime according to the validator classname. The improvement is existed in @FacesConverter as well.

Ajax support

Like other JSF component, JSF inputFile component supports Ajax update.
<h:form enctype="multipart/form-data">
    <h:inputFile id="file" value="#{fileUploadBean.file}" >
        <f:validator validatorId="fileValidator"/>
        <f:ajax execute="@this" render="@form"/>
    </h:inputFile>
    <h:message for="file"/>
    <h:commandButton value="Upload" action="#{fileUploadBean.upload()}"/>
</h:form>
Update the facelets page, add an ajax event to the inputFile component, which causes the validation error displayed instantly when the uploaded file is chosen.

The sample codes

The sample codes are hosted on my github.com account, check out and play it yourself.
https://github.com/hantsy/ee7-sandbox

评论

此博客中的热门博文

Create a restful application with AngularJS and Zend 2 framework

Create a restful application with AngularJS and Zend 2 framework This example application uses AngularJS/Bootstrap as frontend and Zend2 Framework as REST API producer. The backend code This backend code reuses the database scheme and codes of the official Zend Tutorial, and REST API support is also from the Zend community. Getting Started with Zend Framework 2 Getting Started with REST and Zend Framework 2 Zend2 provides a   AbstractRestfulController   for RESR API producing. class AlbumController extends AbstractRestfulController { public function getList() { $results = $this->getAlbumTable()->fetchAll(); $data = array(); foreach ($results as $result) { $data[] = $result; } return new JsonModel(array( 'data' => $data) ); } public function get($id) { $album = $this->getAlbumTable()->getAlbum($id); return new JsonModel(array("data" =>

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa