<p:fileUpload> recreates #ViewScoped bean on every request - jsf

I am using Primefaces fileUpload component in advanced mode to upload multiple images. When i select few files and press upload button, my #ViewScoped managed bean recreates multiple times. That is a problem for me, because i want to store all files uploaded within one view interaction in separate folder, but I'm getting multiple folders - one for each file. When I made my managed bean #SessionScoped the problem is gone, also i found that this bug appears only after server restart for the first uploading, so when i reload view and upload data second time everything is ok.
I am using Tomcat 7, jsf 2.2 and prime faces 5.1
Here is jsf page:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<f:facet name="first">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</f:facet>
<title>Jsf Upload</title>
</h:head>
<h:body>
<h:form id="growlForm">
<p:growl id="growl" showDetail="true" showSummary="true" />
</h:form>
<h:form id="uploadForm" enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{uploadController.upload}"
mode="advanced" multiple="true" label="Choose"
uploadLabel="Upload" cancelLabel="Cancel" />
</h:form>
</h:body>
</html>
Managed Bean:
#ManagedBean
#ViewScoped
public class UploadController implements Serializable {
private static final long serialVersionUID = 5711090879027971547L;
private static final Logger logger = LoggerFactory
.getLogger(UploadController.class);
private List<UploadedFile> files;
public UploadController() {
logger.info("UploadController constructor call");
files = new ArrayList<UploadedFile>();
}
#PostConstruct
public void init() {
logger.info("Post Construct init() method call");
}
public void upload(FileUploadEvent event) {
logger.info("upload() method call, file = {}", event.getFile()
.getFileName());
files.add(event.getFile());
logger.info("Added file = {}", event.getFile().getFileName());
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>JsfUpload</display-name>
<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>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>bootstrap</param-value>
</context-param>
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
Here is my logging output, showing that constructor and #PostConstruct method called multiple times:
2014-12-08 18:57:24,629 [http-bio-8380-exec-7] INFO ru.duytsev.test.upload.UploadController - UploadController constructor call
2014-12-08 18:57:24,629 [http-bio-8380-exec-7] INFO ru.duytsev.test.upload.UploadController - Post Construct init() method
2014-12-08 18:57:24,645 [http-bio-8380-exec-7] INFO ru.duytsev.test.upload.UploadController - upload() method call, file = brick-yellow.png
2014-12-08 18:57:24,645 [http-bio-8380-exec-7] INFO ru.duytsev.test.upload.UploadController - Added file = brick-yellow.png
2014-12-08 18:57:24,666 [http-bio-8380-exec-6] INFO ru.duytsev.test.upload.UploadController - UploadController constructor call
2014-12-08 18:57:24,666 [http-bio-8380-exec-6] INFO ru.duytsev.test.upload.UploadController - Post Construct init() method
2014-12-08 18:57:24,666 [http-bio-8380-exec-6] INFO ru.duytsev.test.upload.UploadController - upload() method call, file = brick-purple.png
2014-12-08 18:57:24,666 [http-bio-8380-exec-6] INFO ru.duytsev.test.upload.UploadController - Added file = brick-purple.png
2014-12-08 18:57:24,678 [http-bio-8380-exec-4] INFO ru.duytsev.test.upload.UploadController - UploadController constructor call
2014-12-08 18:57:24,679 [http-bio-8380-exec-4] INFO ru.duytsev.test.upload.UploadController - Post Construct init() method
2014-12-08 18:57:24,679 [http-bio-8380-exec-4] INFO ru.duytsev.test.upload.UploadController - upload() method call, file = brick-green.png
2014-12-08 18:57:24,679 [http-bio-8380-exec-4] INFO ru.duytsev.test.upload.UploadController - Added file = brick-green.png
2014-12-08 18:57:24,693 [http-bio-8380-exec-5] INFO ru.duytsev.test.upload.UploadController - upload() method call, file = brick-orange.png
2014-12-08 18:57:24,694 [http-bio-8380-exec-5] INFO ru.duytsev.test.upload.UploadController - Added file = brick-orange.png
2014-12-08 18:57:24,715 [http-bio-8380-exec-8] INFO ru.duytsev.test.upload.UploadController - upload() method call, file = brick-blue.png
2014-12-08 18:57:24,715 [http-bio-8380-exec-8] INFO ru.duytsev.test.upload.UploadController - Added file = brick-blue.png
My pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.duytsev.test.upload</groupId>
<artifactId>JsfUpload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<!-- PrimeFaces -->
<dependencies>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.1</version>
</dependency>
<dependency>
<groupId>org.primefaces.extensions</groupId>
<artifactId>all-themes</artifactId>
<version>1.0.8</version>
<type>pom</type>
</dependency>
<!-- JSF -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.8-02</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.8-02</version>
</dependency>
<!-- Java EE -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- EL -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>el-impl</artifactId>
<version>2.2.1-b05</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<!-- APACHE COMMONS -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
<build>
<finalName>${pom.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>

Change to #ViewScoped.
This causes the constructor to be called only once

Related

JSF 2.3 first time, viewScoped managedBean not found [duplicate]

This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 4 years ago.
Hi i have this kind of error when i try to click on button "Submit"
An Error Occurred:
/mail.xhtml #14,72 value="#{emailBean.email}": Target Unreachable, identifier 'emailBean' resolved to null
- Stack Trace
javax.el.PropertyNotFoundException: /mail.xhtml #14,72 value="#{emailBean.email}": Target Unreachable, identifier 'emailBean' resolved to null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:106)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:95)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1122)
at javax.faces.component.UIInput.validate(UIInput.java:1030)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1334)
at javax.faces.component.UIInput.processValidators(UIInput.java:757)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1298)
at javax.faces.component.UIForm.processValidators(UIForm.java:269)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1298)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1298)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1332)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:201)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:670)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.el.PropertyNotFoundException: Target Unreachable, identifier 'emailBean' resolved to null
at com.sun.el.parser.AstValue.getTarget(AstValue.java:173)
at com.sun.el.parser.AstValue.getType(AstValue.java:85)
at com.sun.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:201)
at org.jboss.weld.el.WeldValueExpression.getType(WeldValueExpression.java:93)
at org.jboss.weld.el.WeldValueExpression.getType(WeldValueExpression.java:93)
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:104)
... 51 more
I use JSF 2.3, use #Named instead #ManagedBean and CDI for all Scopes except for ViewScope:
import javax.faces.view.ViewScoped;
import javax.inject.Named;
mail.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
>
<h:head>
<title>check mail validation</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel value="E-mail:" for="emailId"/>
<h:inputText id="nameemailId" value="#{emailBean.email}" validator="emailValidator"/>
<h:message for="emailId"/>
</h:panelGrid>
<h:commandButton value="Submit" action="#{emailBean.sendEmail()}"/>
</h:form>
</h:body>
</html>
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.Serializable;
#Named
#ViewScoped
public class EmailBean implements Serializable{
private static final long serialVersionUID = 3247395658736113405L;
private Email email;
#PostConstruct
public void initialize(){
this.email = new Email("prova");
}
public EmailBean(Email email) {
this.email = email;
}
public Email getEmail() {
return email;
}
public void setEmail(Email email) {
this.email = email;
}
public void sendEmail(){
System.out.println("Email sended");
}
}
beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_2_3.xsd"
version="2.0" bean-discovery-mode="all">
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bluelotussoftware</groupId>
<artifactId>scope-examples-jsf-2-3</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>scope-examples-jsf-2-3</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>javax.faces-api</artifactId>
<version>2.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>${version.wildfly.maven.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<attachClasses>true</attachClasses>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>java.net</id>
<name>Java.net Repository</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
</project>
I deploy on Wildfly 10 and i replace jsf-api and jsf-impl reading this guides:
step 1 (how to packages jars):
How to install one jar variant of JSF (javax.faces.jar) on WildFly
step 2 (how to install):
Upgrade JSF / Mojarra in JBoss AS / EAP / WildFly
thanks you
Roberto
SAME ERROR IN ANOTHER QUESTION
There should be a bean.xml
and
a faces-config.xml for faces application (JSF)
Changing faces-config.xml from 2.2 to 2.3 causes javax.el.PropertyNotFoundException: Target Unreachable, identifier 'bean' resolved to null
ALSO
Of the error and the property value being null.
check the bean "state" configuration session or page... (should be session)
if it not session then it will be dropped each time a request is made.
It is a mapping to the bean class gone wrong for the error
javax.el.PropertyNotFoundException: /mail.xhtml #14,72 value="#{emailBean.email}": Target Unreachable, identifier 'emailBean' resolved to null
==== old info -
I believe your faces navigation rules for JSF configuration from and to a page should have names and should be clarified in your web.xml
Here is a link to "simple" a tutorial page for a J2EE server for JSF to explain.
http://tomee.apache.org/examples-trunk/jsf-managedBean-and-ejb/README.html
(note careful of the call syntax in the code too)

Method Not Found ? This not made sense [duplicate]

This question already has answers here:
How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable
(11 answers)
Closed 5 years ago.
I'm trying to implement a FileUpload feature in a simple JSF/CDI project, with correct dependencies(i think) and the same code that i found in the primefaces showcase.
But for some reason, the FileUpload event does not found the listener in my ManagedBean.
I hope i can see something that i'm missing here, i already inspected the code a lot of times but i dont find anything that could be causing the problem.
My Xhtml page:
<html>
<h:head>
</h:head>
<body>
<h:form>
<p:fileUpload fileUploadListener="#{file.uploadHandler()}"
mode="advanced" dragDropSupport="false" update="messages"
sizeLimit="100000" fileLimit="3"
allowTypes="/(\.|\/)(gif|jpe?g|txt)$/" />
<p:growl id="messages" showDetail="true" />
</h:form>
</body>
</html>
My ManagedBean:
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.primefaces.event.FileUploadEvent;
#Named
#ViewScoped
public class File implements Serializable {
private static final long serialVersionUID = -6644472075906217176L;
private String fileName;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void uploadHandler(FileUploadEvent event) {
System.out.println("Nome do Arquivo: " + event.getFile().getFileName());
}
}
My pom.file :
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.14</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.1</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
Console:
15:59:36,935 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-27) /index.xhtml #16,45 fileUploadListener="#{file.uploadHandler()}": Method not found: class timesheet.business.bean.File.uploadHandler(): javax.el.MethodNotFoundException: /index.xhtml #16,45 fileUploadListener="#{file.uploadHandler()}": Method not found: class timesheet.business.bean.File.uploadHandler()
You should specify the method reference in fileUpload component
<p:fileUpload fileUploadListener="#{file.uploadHandler}"
Please note that there should be no () after the method name.

#ViewScoped managed bean gets destroyed when using h:inputFile

I have problems using h:inputFile to upload Files in JSF 2.2.7 and Glassfish 4.1. I'm trying to get h:inputFile to work, but whenever I use the uploaded Part object from h:inputFile, the Backing bean gets destroyed and created again. Also the setter for the Part object is never called. I tried to isolate the problem by creating a page just with the upload (copied from a jsf example project), but the problem is still there. I also tried to use the Primefaces p:fileUpload, but the problem was still there. I also couldn't find any solutions by googling. Thanks for the help.
The JSF page testMinUpload.xhtml (removed prependId="false" from the form)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<f:view>
<h:form id="form" enctype="multipart/form-data">
<h:messages/>
<h:panelGrid columns="2">
<h:outputText value="File:"/>
<h:inputFile id="file" value="#{uploadController.file}"
validator="#{uploadController.validateFile}"/>
</h:panelGrid>
<h:commandButton value="Upload File" action="#{uploadController.upload}"/>
<h:commandButton value="Upload File (Ajax)" action="#{uploadController.upload}">
<f:ajax execute="file" render="#all"/>
</h:commandButton>
<h:panelGrid id="content" columns="1">
<h:outputText value="Content:"/>
<h:inputTextarea readonly="true" value="#{uploadController.fileContent}"
rows="10" cols="100"/>
</h:panelGrid>
</h:form>
</f:view>
</html>
The Backing Bean
#ManagedBean(name = "uploadController")
#ViewScoped
public class TestFileUploadController implements Serializable {
private Part file;
private String fileContent;
#PostConstruct
public void init() {
System.out.println("init() called");
}
public Part getFile() {
return file;
}
public void setFile(Part file) {
System.out.println("setFile() has been called");
this.file = file;
}
/**
* Gets the file contents of the file.
*/
public void upload() {
try {
fileContent = new Scanner(file.getInputStream())
.useDelimiter("\\A").next();
} catch (IOException e) {
// Error handling
}
}
/**
* Validates the file.
*/
public void validateFile(FacesContext ctx,
UIComponent comp,
Object value) {
System.out.println("validateFile() called");
List<FacesMessage> msgs = new ArrayList<FacesMessage>();
Part file = (Part)value;
if (file.getSize() > 1024) {
msgs.add(new FacesMessage("file too big"));
}
if (!"text/plain".equals(file.getContentType())) {
msgs.add(new FacesMessage("not a text file"));
}
if (!msgs.isEmpty()) {
throw new ValidatorException(msgs);
}
}
public String getFileContent() {
return fileContent;
}
public void setFileContent(String fileContent) {
this.fileContent = fileContent;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>MyApp</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<welcome-file-list>
<welcome-file>testMinUpload.xhtml</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<application>
<locale-config>
<default-locale>de</default-locale>
<supported-locale>en</supported-locale>
</locale-config>
</application>
</faces-config>
pom.xml (updated to only include javaee-web-api as dependency)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>bar.foo</groupId>
<artifactId>myapp</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>myapp</name>
<url>http://foo.bar</url>
<licenses>
<license>
<name>GNU Affero General Public License, Version 3</name>
<url>https://gnu.org/licenses/agpl-3.0.txt</url>
</license>
</licenses>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<compilerArgument>-Xlint:all</compilerArgument>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.glassfish.embedded</groupId>
<artifactId>maven-embedded-glassfish-plugin</artifactId>
<version>4.1.1</version>
<configuration>
<autoDelete>true</autoDelete>
<port>8080</port>
</configuration>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>4.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>deploy</goal>
</goals>
<configuration>
<app>target/${project.artifactId}-${project.version}.war</app>
<name>${project.artifactId}</name>
<contextRoot>/${project.artifactId}</contextRoot>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.17</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<consoleOutput>true</consoleOutput>
<failOnViolation>true</failOnViolation>
</configuration>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>3.0.3</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
glassfish-web.xml (I alread tried to set the class-loader delegate to true, but this didn't fix the issue)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 4.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
<class-loader delegate="false" />
</glassfish-web-app>

Primefaces push - not reaching endpoint

I have problems with my maven web application implementing primefaces push. I can't figure out why, but I'm not reaching my endpoint.
I'm running on,
Tomcat 7.0.59
Java EE 6 Web
PrimeFaces 5.0
Atmosphere 2.1.3
JSF 2.2
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>feestnet_v3</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>feestnet_v3</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.5.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-runtime</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>all-themes</artifactId>
<version>1.0.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<url>http://repository.primefaces.org/</url>
<id>PrimeFaces-maven-lib</id>
<layout>default</layout>
<name>Repository for library PrimeFaces-maven-lib</name>
</repository>
<repository>
<id>prime-repo</id>
<name>Prime Repo</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
MailObserver.java (pushing the message)
package nv.messaging;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import org.primefaces.push.EventBus;
import org.primefaces.push.EventBusFactory;
#ManagedBean
#SessionScoped
public class MailObserver implements Serializable{
private int toId;
private int fromId;
private String title;
private String message;
public String inboxText;
public String htmlMessage;
public MailObserver(){
inboxText = "Inbox";
htmlMessage = "Test message";
}
public void pushMessage(ActionEvent event){
EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish("/message", htmlMessage);
System.out.println("Message sent");
}
public void update() {
}
public String getInboxText() {
return inboxText;
}
public void setInboxText(String inboxText) {
this.inboxText = inboxText;
}
public int getToId() {
return toId;
}
public void setToId(int toId) {
this.toId = toId;
}
public int getFromId() {
return fromId;
}
public void setFromId(int fromId) {
this.fromId = fromId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getHtmlMessage() {
return htmlMessage;
}
public void setHtmlMessage(String htmlMessage) {
this.htmlMessage = htmlMessage;
}
}
MailEndpoint.java
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.impl.JSONEncoder;
#PushEndpoint(value = "/message")
public class MailEndpoint {
#OnMessage(encoders = {JSONEncoder.class})
public String onMessage(String message) {
System.out.println("Mail endpoint reached : " + message);
return message;
}
}
for completeness
layout.xhtml
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
<style>
.ui-layout-resizer{
background-color: black;
}
</style>
<f:facet name="first">
<meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
<title>PrimeFaces</title>
</f:facet>
</h:head>
<h:body>
<f:metadata>
<f:event type="preRenderView" listener="#{security.securePage()}"/>
<f:event type="preRenderView" listener="#{security.authorisation('ALL')}"/>
</f:metadata>
<p:layout fullPage="true">
<p:layoutUnit position="north" size="100" resizable="true" closable="true" collapsible="true" gutter="1">
Header
<p:socket channel="/message" onMessage="handleMessage" ></p:socket>
</p:layoutUnit>
<p:layoutUnit position="south" size="100" closable="true" collapsible="true" gutter="1">
Footer
</p:layoutUnit>
<p:layoutUnit position="west" size="auto" header="Left" collapsible="true" gutter="1">
<p:menu>
<p:submenu label="Resources">
<p:menuitem value="Message" url="/secure/messages/message.xhtml" />
<p:menuitem value="Documentation" url="http://www.primefaces.org/documentation.html" />
<p:menuitem value="Forum" url="http://forum.primefaces.org/" />
<p:menuitem value="Themes" url="http://www.primefaces.org/themes.html" />
</p:submenu>
</p:menu>
</p:layoutUnit>
<p:layoutUnit position="center">
<ui:insert name="content">Put default content here, if any.</ui:insert>
</p:layoutUnit>
</p:layout>
<script type="text/javascript" >
function handleMessage(data) {
console.log(data);
}
</script>
</h:body>
</f:view>
</html>
I think I should see a message in the output from MailEndpoint but, I only get the message from MailObserver.pushMessage. Any ideas on what is going on?
I found the problem. I changed the wrong web.xml. To make it work, you need to add this to web.xml
<servlet>
<servlet-name>Push Servlet</servlet-name>
<servlet-class>org.primefaces.push.PushServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>Push Servlet</servlet-name>
<url-pattern>/primepush/*</url-pattern>
</servlet-mapping>

JSF viewAction called twice

I have a simple JSF project where I use <f:viewaction action="#{backingBean.init}"/> and the backing bean is being constructed twice. I trace out the session id and I get different session ids for each call.
index.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<f:metadata>
<f:viewAction action="#{backingBean.init}"/>
</f:metadata>
<h:body>
<h:outputLabel value="#{backingBean.text}"/>
</h:body>
</html>
BackingBean.java
package com.test.bean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#SessionScoped
public class BackingBean {
public BackingBean() {
System.out.println("Constructor called");
}
public void init() {
FacesContext fCtx = FacesContext.getCurrentInstance();
String sessionId = fCtx.getExternalContext().getSessionId(false);
System.out.println("Init called - session id: "+sessionId);
}
public String getText() {
return "Some text";
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>PrerenderViewTest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<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>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
</faces-config>
I have tried other methods of calling the init() like using the #PostConstruct annotation or <f:event type="prerenderview" listener="#{backingBean.init}"/> but I get the same results. The init method is always called twice the first time when I access the page. On subsequent calls it is only called once.

Resources