跳至主要内容

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

评论

此博客中的热门博文

Build a Reactive application with Angular 5 and Spring Boot 2.0

I have created a post to describe Reactive programming supports in Spring 5 and its subprojects, all codes of this article are updated the latest Spring 5 RELEASE, check spring-reactive-sample under my Github account.
In this post, I will create a simple blog system, including:
A user can sign in and sign out.An authenticated user can create a post.An authenticated user can update a post.Only the user who has ADMIN role can delete a post.All users(including anonymous users) can view post list and post details.An authenticated user can add his comments to a certain post. The backend will be built with the latest Spring 5 reactive stack, including:
Spring Boot 2.0, at the moment the latest version is 2.0.0.M7Spring Data MongoDB supports reactive operations for MongoDBSpring Session adds reactive support for WebSessionSpring Security 5 aligns with Spring 5 reactive stack The frontend is an Angular based SPA and it will be generated by Angular CLI.
The source code is hosted on Github, …

Activating CDI in JSF 2.3

Activating CDI in JSF 2.3 When I upgraed my Java EE 7 sample to the newest Java EE 8, the first thing confused me is the CDI beans are not recoganized in Facelects template in a JSF 2.3 based web applicaiton, which is working in the development version, but in the final release version, they are always resolved as null. I filed an issue on Mojarra and discussed it with the developers from communities and the JSF experts.
According to the content of README, In a JSF 2.3 application, to activate CDI support, declaring a 2.3 versioned faces-config.xml and adding javax.faces.ENABLE_CDI_RESOLVER_CHAIN in web.xml is not enough, you have to declare @FacesConfig annotated class to enable CDI.
Here is the steps I created a workable JSF 2.3 applicatoin in Java EE 8.
Create a Java web application, this can be done easily by NetBeans IDE, or generated by Maven archetype, for exmaple.
$ mvn archetype:generate -DgroupId=com.example -DartifactId=demo -DarchetypeArtifactId=maven-archetype-w…

JSF 2.3:Websocket support

Websocket support One of the most attractive features is JSF 2.3 added native websocket support, it means you can write real-time applications with JSF and no need extra effort.
To enable websocket support, you have to add javax.faces.ENABLE_WEBSOCKET_ENDPOINT in web.xml.
<context-param> <param-name>javax.faces.ENABLE_WEBSOCKET_ENDPOINT</param-name> <param-value>true</param-value> </context-param> Hello Websocket Let's start with a simple example.
@ViewScoped@Named("helloBean") publicclassHelloBeanimplementsSerializable { privatestaticfinalLoggerLOG=Logger.getLogger(HelloBean.class.getName()); @Inject@PushPushContext helloChannel; String message; publicvoidsendMessage() { LOG.log(Level.INFO, "send push message"); this.sendPushMessage("hello"); } privatevoidsendPushMessage(Objectmessage) { helloChannel.send(""+ message +" at &…