Image is not getting uploaded with JSF 2.0 PrimeFaces [duplicate] - jsf-2
I'm trying to upload a file using PrimeFaces, but the fileUploadListener method isn't being invoked after the upload finishes.
Here is the view:
<h:form>
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
sizeLimit="100000"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<p:growl id="messages" showDetail="true"/>
</h:form>
And the bean:
#ManagedBean
#RequestScoped
public class FileUploadController {
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
I've placed a breakpoint on the method, but it's never called. When using mode="simple" and ajax="false", it is been invoked, but I want it to work in the advanced mode. I'm using Netbeans and Glassfish 3.1.
How to configure and troubleshoot <p:fileUpload> depends on PrimeFaces and JSF version.
All PrimeFaces versions
The below requirements apply to all PrimeFaces versions:
The enctype attribute of the <h:form> needs to be set to multipart/form-data. When this is absent, the ajax upload may just work, but the general browser behavior is unspecified and dependent on form composition and webbrowser make/version. Just always specify it to be on the safe side.
When using mode="advanced" (i.e. ajax upload, this is the default), then make sure that you've a <h:head> in the (master) template. This will ensure that the necessary JavaScript files are properly included. This is not required for mode="simple" (non-ajax upload), but this would break look'n'feel and functionality of all other PrimeFaces components, so you don't want to miss that anyway.
When using mode="simple" (i.e. non-ajax upload), then ajax must be disabled on any PrimeFaces command buttons/links by ajax="false", and you must use <p:fileUpload value> with <p:commandButton action> instead of <p:fileUpload listener>.
So, if you want (auto) file upload with ajax support (mind the <h:head>!):
<h:form enctype="multipart/form-data">
<p:fileUpload listener="#{bean.upload}" auto="true" /> // For PrimeFaces version older than 8.x this should be fileUploadListener instead of listener.
</h:form>
public void upload(FileUploadEvent event) {
UploadedFile uploadedFile = event.getFile();
String fileName = uploadedFile.getFileName();
String contentType = uploadedFile.getContentType();
byte[] contents = uploadedFile.getContents(); // Or getInputStream()
// ... Save it, now!
}
Or if you want non-ajax file upload:
<h:form enctype="multipart/form-data">
<p:fileUpload mode="simple" value="#{bean.uploadedFile}" />
<p:commandButton value="Upload" action="#{bean.upload}" ajax="false" />
</h:form>
private transient UploadedFile uploadedFile; // +getter+setter
public void upload() {
String fileName = uploadedFile.getFileName();
String contentType = uploadedFile.getContentType();
byte[] contents = uploadedFile.getContents(); // Or getInputStream()
// ... Save it, now!
}
Do note that ajax-related attributes such as auto, allowTypes, update, onstart, oncomplete, etc are ignored in mode="simple". So it's needless to specify them in such case.
Also note that the UploadedFile property is declared transient just to raise awareness that this is absolutely not serializable. The whole thing should be placed in a request scoped bean instead of a view or even session scoped one. If this is the case, then you can safely remove the transient attribute.
Also note that you should immediately read and save the file contents inside the abovementioned methods and not in a different bean method invoked by a later HTTP request. This is because technically speaking the uploaded file contents is request scoped and thus unavailable in a later/different HTTP request. Any attempt to read it in a later request will most likely end up with java.io.FileNotFoundException on the temporary file and only cause confusion.
PrimeFaces 8.x or newer
Configuration is identical to the 5.x version info below, but if your listener is not called, check if the method attribute is called listener and not fileUploadListener like as in versions before 8.x.
PrimeFaces 5.x
This does not require any additional configuration if you're using at least JSF 2.2 and your faces-config.xml is also declared conform at least JSF 2.2 version. You do not need the PrimeFaces file upload filter at all and you also do not need the primefaces.UPLOADER context parameter in web.xml. In case it's unclear to you how to properly install and configure JSF depending on the target server used, head to How to properly install and configure JSF libraries via Maven? and "Installing JSF" section of our JSF wiki page.
If you're however not using JSF 2.2 yet and you can't upgrade JSF 2.0/2.1 to 2.2 yet (should be effortless though when already on a Servlet 3.0 compatible container), then you need to manually register the below PrimeFaces file upload filter in web.xml (it will parse the multi part request and fill the regular request parameter map so that FacesServlet can continue working as usual):
<filter>
<filter-name>primeFacesFileUploadFilter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>primeFacesFileUploadFilter</filter-name>
<servlet-name>facesServlet</servlet-name>
</filter-mapping>
The <servlet-name> value of facesServlet must match exactly the value in the <servlet> entry of the javax.faces.webapp.FacesServlet in the same web.xml. So if it's e.g. Faces Servlet, then you need to edit it accordingly to match.
PrimeFaces 4.x
The same story as PrimeFaces 5.x applies on 4.x as well.
There's only a potential problem in getting the uploaded file content by UploadedFile#getContents(). This will return null when native API is used instead of Apache Commons FileUpload. You need to use UploadedFile#getInputStream() instead. See also How to insert uploaded image from p:fileUpload as BLOB in MySQL?
Another potential problem with native API will manifest is when the upload component is present in a form on which a different "regular" ajax request is fired which does not process the upload component. See also File upload doesn't work with AJAX in PrimeFaces 4.0/JSF 2.2.x - javax.servlet.ServletException: The request content-type is not a multipart/form-data.
Both problems can also be solved by switching to Apache Commons FileUpload. See PrimeFaces 3.x section for detail.
PrimeFaces 3.x
This version does not support JSF 2.2 / Servlet 3.0 native file upload. You need to manually install Apache Commons FileUpload and explicitly register the file upload filter in web.xml.
You need the following libraries:
commons-fileupload.jar
commons-io.jar
Those must be present in the webapp's runtime classpath. When using Maven, make sure they are at least runtime scoped (default scope of compile is also good). When manually carrying around JARs, make sure they end up in /WEB-INF/lib folder.
The file upload filter registration detail can be found in PrimeFaces 5.x section here above. In case you're using PrimeFaces 4+ and you'd like to explicitly use Apache Commons FileUpload instead of JSF 2.2 / Servlet 3.0 native file upload, then you need next to the mentioned libraries and filter also the below context param in web.xml:
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value><!-- Allowed values: auto, native and commons. -->
</context-param>
Troubleshooting
In case it still doesn't work, here are another possible causes unrelated to PrimeFaces configuration:
Only if you're using the PrimeFaces file upload filter: There's another Filter in your webapp which runs before the PrimeFaces file upload filter and has already consumed the request body by e.g. calling getParameter(), getParameterMap(), getReader(), etcetera. A request body can be parsed only once. When you call one of those methods before the file upload filter does its job, then the file upload filter will get an empty request body.
To fix this, you'd need to put the <filter-mapping> of the file upload filter before the other filter in web.xml. If the request is not a multipart/form-data request, then the file upload filter will just continue as if nothing happened. If you use filters that are automagically added because they use annotations (e.g. PrettyFaces), you might need to add explicit ordering via web.xml. See How to define servlet filter order of execution using annotations in WAR
Only if you're using the PrimeFaces file upload filter: There's another Filter in your webapp which runs before the PrimeFaces file upload filter and has performed a RequestDispatcher#forward() call. Usually, URL rewrite filters such as PrettyFaces do this. This triggers the FORWARD dispatcher, but filters listen by default on REQUEST dispatcher only.
To fix this, you'd need to either put the PrimeFaces file upload filter before the forwarding filter, or to reconfigure the PrimeFaces file upload filter to listen on FORWARD dispatcher too:
<filter-mapping>
<filter-name>primeFacesFileUploadFilter</filter-name>
<servlet-name>facesServlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
There's a nested <h:form>. This is illegal in HTML and the browser behavior is unspecified. More than often, the browser won't send the expected data on submit. Make sure that you are not nesting <h:form>. This is completely regardless of the form's enctype. Just do not nest forms at all.
If you're still having problems, well, debug the HTTP traffic. Open the webbrowser's developer toolset (press F12 in Chrome/Firebug23+/IE9+) and check the Net/Network section. If the HTTP part looks fine, then debug the JSF code. Put a breakpoint on FileUploadRenderer#decode() and advance from there.
Saving uploaded file
After you finally got it to work, your next question shall probably be like "How/where do I save the uploaded file?". Well, continue here: How to save uploaded file in JSF.
You are using prettyfaces too? Then set dispatcher to FORWARD:
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
One point I noticed with Primefaces 3.4 and Netbeans 7.2:
Remove the Netbeans auto-filled parameters for function handleFileUpload i.e. (event) otherwise event could be null.
<h:form>
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload(event)}"
mode="advanced"
update="messages"
sizeLimit="100000"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<p:growl id="messages" showDetail="true"/>
</h:form>
Looks like javax.faces.SEPARATOR_CHAR must not be equal to _
Putting p:fileUpload inside a h:form solved the problem at my case.
I had same issue with primefaces 5.3 and I went through all the points described by BalusC with no result. I followed his advice of debugging FileUploadRenderer#decode() and I discovered that my web.xml was unproperly set
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto|native|commons</param-value>
</context-param>
The param-value must be 1 of these 3 values but not all of them!! The whole context-param section can be removed and the default will be auto
bean.xhtml
<h:form enctype="multipart/form-data">
<p:outputLabel value="Choose your file" for="submissionFile" />
<p:fileUpload id="submissionFile"
value="#{bean.file}"
fileUploadListener="#{bean.uploadFile}" mode="advanced"
auto="true" dragDropSupport="false" update="messages"
sizeLimit="100000" fileLimit="1" allowTypes="/(\.|\/)(pdf)$/" />
</h:form>
Bean.java
#ManagedBean
#ViewScoped
public class Submission implements Serializable {
private UploadedFile file;
//Gets
//Sets
public void uploadFasta(FileUploadEvent event) throws FileNotFoundException, IOException, InterruptedException {
String content = IOUtils.toString(event.getFile().getInputstream(), "UTF-8");
String filePath = PATH + "resources/submissions/" + nameOfMyFile + ".pdf";
MyFileWriter.writeFile(filePath, content);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
event.getFile().getFileName() + " is uploaded.", null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
web.xml
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<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>
Neither of the suggestions here were helpful for me. So I had to debug primefaces and found the reason of the problem was:
java.lang.IllegalStateException: No multipart config for servlet fileUpload
Then I have added section into my faces servlet in the web.xml. So that has fixed the problem:
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.apache.myfaces.webapp.MyFacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
</servlet>
For people using Tomee or Tomcat and can't get it working, try to create context.xml in META-INF and add allowCasualMultipartParsing="true"
<?xml version="1.0" encoding="UTF-8"?>
<Context allowCasualMultipartParsing="true">
<!-- empty or not depending your project -->
</Context>
With JBoss 7.2(Undertow) and PrimeFaces 6.0 org.primefaces.webapp.filter.FileUploadFilter should be removed from web.xml and context param file uploader should be set to native:
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>native</param-value>
</context-param>
I had the same issue, due to the fact that I had all the configuration that describe in this post, but in my case was because I had two jQuery imports (one of them was PrimeFaces's bundled jQuery) which caused conflicts to upload files.
Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors
Related
How do I get IDE code completion to work with JSF 2.2 non-composite component attributes?
Problem: I get code completion on the tags but not the attributes. I am working on a new web application using Java 8 JSF 2.2.14 PrimeFaces 6.1 Netbeans 8.2 We are using a library that is provided to us in JavaScript (generated from Typescript sources). I have written a non-composite component to wrap this library and keep all that JavaScript code hidden and in one place. It initializes the the library and provides attributes to pass JavaScript callback functions to the library (so we still have to write some JavaScript). snippet from the JSF .xhtml file <script type="text/javascript"> function jscallbackHandler() { alert("function called!");} </script> <myComponent:initialize callback1="jscallbackHandler" /> This tag invokes my class to write a lot of JavaScript into the page to setup and initialize the library. I am using the #FacesComponent annotation to declare my classes as custom components. snippet from 'InitMyComponent.java' file #FacesComponent(createTag = true, tagName = "initialize", namespace = "https://com.my.project/myComponent", value = InitMyComponent.FAMILY) public class InitMyComponent extends UIComponentBase { ... } This is working except for IDE code completion and I can't find documentation or examples for JSF 2.2 components that show how to declare attributes and hook them into the project. I have seen many examples of earlier JSF 2.x components that use a taglib.xml to define the attributes for code completion, but it seems to be 'at odds' with features of the JSF 2.2 style annotation. I have to remove most of the attributes of the annotation (basically revert to a JSF 2.0 style annotation) or I get "Expression Error: Named Object ... not found". I have also gotten Tag Library supports namespace, but no tag was defined for name. If I just provide a component name to the annotation that matches the one in the taglib file it works, but just no code completion. I have a FACELETS_LIBRARIES name/value pair in a context-param tag in the web.xml to declare where my facelet-taglib file is located. snippet from the 'web.xml' file <!-- Enable IDE autocompletion on component attributes --> <context-param> <param-name>javax.faces.FACELETS_LIBRARIES</param-name> <param-value>/WEB-INF/myComponent.taglib.xml</param-value> </context-param> I have a facelet-taglib file named 'myComponent.taglib.xml' in my WEB-INF directory (same place as faces-config.xml and web.xml). UPDATE: Responding to the comment by Kukeltje, I updated my facelet-taglib file to version 2.2, but I still get "No Suggestions" from my IDE... also updated the namespaces in my .xhtml JSF source file (even though this site said the older versions were still supported https://jsflive.wordpress.com/2013/05/16/jsf22-namespaces/) snippet from the 'myComponent.taglib.xml' file <?xml version="1.0"?> <facelet-taglib 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-facelettaglibrary_2_2.xsd"> <namespace>http://java.sun.com/jsf/composite/components</namespace> <composite-library-name>myComposites</composite-library-name> <namespace>https://com.my.project/myComponent</namespace> <tag> <tag-name>initialize</tag-name> <component> <component-type>InitMyComponent</component-type> </component> <attribute> <name>callback1</name> <required>false</required> <type>java.lang.String</type> </attribute> </tag> The faces-config.xml file - defines the javaee and schema namespaces, and version 2.2 but it is otherwise 'empty'. <?xml version="1.0" encoding="UTF-8"?> <faces-config 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" version="2.2"> </faces-config> I am fine with having to type in all the attributes but I just can't seem to find the proper way to hook this feature into my project. Note: I have experimented with using a composite component. The code completion for attributes worked, but then I lost code completion for the tags. I'm just writing out JavaScript to setup and call a JavaScript library's initialize function but also, I would really love to pass a JavaScript object back to a bean on the server when my callback function is invoked. I am currently using a BalusC provided solution that involves p:remoteCommand and updating hidden input fields. I would greatly prefer to provide reference to the bean using EL in an attribute of my custom component.
p:fileUpload doesn't work Primefaces 5.2 [duplicate]
I'm trying to upload a file using PrimeFaces, but the fileUploadListener method isn't being invoked after the upload finishes. Here is the view: <h:form> <p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}" mode="advanced" update="messages" sizeLimit="100000" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/> <p:growl id="messages" showDetail="true"/> </h:form> And the bean: #ManagedBean #RequestScoped public class FileUploadController { public void handleFileUpload(FileUploadEvent event) { FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, msg); } } I've placed a breakpoint on the method, but it's never called. When using mode="simple" and ajax="false", it is been invoked, but I want it to work in the advanced mode. I'm using Netbeans and Glassfish 3.1.
How to configure and troubleshoot <p:fileUpload> depends on PrimeFaces and JSF version. All PrimeFaces versions The below requirements apply to all PrimeFaces versions: The enctype attribute of the <h:form> needs to be set to multipart/form-data. When this is absent, the ajax upload may just work, but the general browser behavior is unspecified and dependent on form composition and webbrowser make/version. Just always specify it to be on the safe side. When using mode="advanced" (i.e. ajax upload, this is the default), then make sure that you've a <h:head> in the (master) template. This will ensure that the necessary JavaScript files are properly included. This is not required for mode="simple" (non-ajax upload), but this would break look'n'feel and functionality of all other PrimeFaces components, so you don't want to miss that anyway. When using mode="simple" (i.e. non-ajax upload), then ajax must be disabled on any PrimeFaces command buttons/links by ajax="false", and you must use <p:fileUpload value> with <p:commandButton action> instead of <p:fileUpload listener>. So, if you want (auto) file upload with ajax support (mind the <h:head>!): <h:form enctype="multipart/form-data"> <p:fileUpload listener="#{bean.upload}" auto="true" /> // For PrimeFaces version older than 8.x this should be fileUploadListener instead of listener. </h:form> public void upload(FileUploadEvent event) { UploadedFile uploadedFile = event.getFile(); String fileName = uploadedFile.getFileName(); String contentType = uploadedFile.getContentType(); byte[] contents = uploadedFile.getContents(); // Or getInputStream() // ... Save it, now! } Or if you want non-ajax file upload: <h:form enctype="multipart/form-data"> <p:fileUpload mode="simple" value="#{bean.uploadedFile}" /> <p:commandButton value="Upload" action="#{bean.upload}" ajax="false" /> </h:form> private transient UploadedFile uploadedFile; // +getter+setter public void upload() { String fileName = uploadedFile.getFileName(); String contentType = uploadedFile.getContentType(); byte[] contents = uploadedFile.getContents(); // Or getInputStream() // ... Save it, now! } Do note that ajax-related attributes such as auto, allowTypes, update, onstart, oncomplete, etc are ignored in mode="simple". So it's needless to specify them in such case. Also note that the UploadedFile property is declared transient just to raise awareness that this is absolutely not serializable. The whole thing should be placed in a request scoped bean instead of a view or even session scoped one. If this is the case, then you can safely remove the transient attribute. Also note that you should immediately read and save the file contents inside the abovementioned methods and not in a different bean method invoked by a later HTTP request. This is because technically speaking the uploaded file contents is request scoped and thus unavailable in a later/different HTTP request. Any attempt to read it in a later request will most likely end up with java.io.FileNotFoundException on the temporary file and only cause confusion. PrimeFaces 8.x or newer Configuration is identical to the 5.x version info below, but if your listener is not called, check if the method attribute is called listener and not fileUploadListener like as in versions before 8.x. PrimeFaces 5.x This does not require any additional configuration if you're using at least JSF 2.2 and your faces-config.xml is also declared conform at least JSF 2.2 version. You do not need the PrimeFaces file upload filter at all and you also do not need the primefaces.UPLOADER context parameter in web.xml. In case it's unclear to you how to properly install and configure JSF depending on the target server used, head to How to properly install and configure JSF libraries via Maven? and "Installing JSF" section of our JSF wiki page. If you're however not using JSF 2.2 yet and you can't upgrade JSF 2.0/2.1 to 2.2 yet (should be effortless though when already on a Servlet 3.0 compatible container), then you need to manually register the below PrimeFaces file upload filter in web.xml (it will parse the multi part request and fill the regular request parameter map so that FacesServlet can continue working as usual): <filter> <filter-name>primeFacesFileUploadFilter</filter-name> <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class> </filter> <filter-mapping> <filter-name>primeFacesFileUploadFilter</filter-name> <servlet-name>facesServlet</servlet-name> </filter-mapping> The <servlet-name> value of facesServlet must match exactly the value in the <servlet> entry of the javax.faces.webapp.FacesServlet in the same web.xml. So if it's e.g. Faces Servlet, then you need to edit it accordingly to match. PrimeFaces 4.x The same story as PrimeFaces 5.x applies on 4.x as well. There's only a potential problem in getting the uploaded file content by UploadedFile#getContents(). This will return null when native API is used instead of Apache Commons FileUpload. You need to use UploadedFile#getInputStream() instead. See also How to insert uploaded image from p:fileUpload as BLOB in MySQL? Another potential problem with native API will manifest is when the upload component is present in a form on which a different "regular" ajax request is fired which does not process the upload component. See also File upload doesn't work with AJAX in PrimeFaces 4.0/JSF 2.2.x - javax.servlet.ServletException: The request content-type is not a multipart/form-data. Both problems can also be solved by switching to Apache Commons FileUpload. See PrimeFaces 3.x section for detail. PrimeFaces 3.x This version does not support JSF 2.2 / Servlet 3.0 native file upload. You need to manually install Apache Commons FileUpload and explicitly register the file upload filter in web.xml. You need the following libraries: commons-fileupload.jar commons-io.jar Those must be present in the webapp's runtime classpath. When using Maven, make sure they are at least runtime scoped (default scope of compile is also good). When manually carrying around JARs, make sure they end up in /WEB-INF/lib folder. The file upload filter registration detail can be found in PrimeFaces 5.x section here above. In case you're using PrimeFaces 4+ and you'd like to explicitly use Apache Commons FileUpload instead of JSF 2.2 / Servlet 3.0 native file upload, then you need next to the mentioned libraries and filter also the below context param in web.xml: <context-param> <param-name>primefaces.UPLOADER</param-name> <param-value>commons</param-value><!-- Allowed values: auto, native and commons. --> </context-param> Troubleshooting In case it still doesn't work, here are another possible causes unrelated to PrimeFaces configuration: Only if you're using the PrimeFaces file upload filter: There's another Filter in your webapp which runs before the PrimeFaces file upload filter and has already consumed the request body by e.g. calling getParameter(), getParameterMap(), getReader(), etcetera. A request body can be parsed only once. When you call one of those methods before the file upload filter does its job, then the file upload filter will get an empty request body. To fix this, you'd need to put the <filter-mapping> of the file upload filter before the other filter in web.xml. If the request is not a multipart/form-data request, then the file upload filter will just continue as if nothing happened. If you use filters that are automagically added because they use annotations (e.g. PrettyFaces), you might need to add explicit ordering via web.xml. See How to define servlet filter order of execution using annotations in WAR Only if you're using the PrimeFaces file upload filter: There's another Filter in your webapp which runs before the PrimeFaces file upload filter and has performed a RequestDispatcher#forward() call. Usually, URL rewrite filters such as PrettyFaces do this. This triggers the FORWARD dispatcher, but filters listen by default on REQUEST dispatcher only. To fix this, you'd need to either put the PrimeFaces file upload filter before the forwarding filter, or to reconfigure the PrimeFaces file upload filter to listen on FORWARD dispatcher too: <filter-mapping> <filter-name>primeFacesFileUploadFilter</filter-name> <servlet-name>facesServlet</servlet-name> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> There's a nested <h:form>. This is illegal in HTML and the browser behavior is unspecified. More than often, the browser won't send the expected data on submit. Make sure that you are not nesting <h:form>. This is completely regardless of the form's enctype. Just do not nest forms at all. If you're still having problems, well, debug the HTTP traffic. Open the webbrowser's developer toolset (press F12 in Chrome/Firebug23+/IE9+) and check the Net/Network section. If the HTTP part looks fine, then debug the JSF code. Put a breakpoint on FileUploadRenderer#decode() and advance from there. Saving uploaded file After you finally got it to work, your next question shall probably be like "How/where do I save the uploaded file?". Well, continue here: How to save uploaded file in JSF.
You are using prettyfaces too? Then set dispatcher to FORWARD: <filter-mapping> <filter-name>PrimeFaces FileUpload Filter</filter-name> <servlet-name>Faces Servlet</servlet-name> <dispatcher>FORWARD</dispatcher> </filter-mapping>
One point I noticed with Primefaces 3.4 and Netbeans 7.2: Remove the Netbeans auto-filled parameters for function handleFileUpload i.e. (event) otherwise event could be null. <h:form> <p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload(event)}" mode="advanced" update="messages" sizeLimit="100000" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/> <p:growl id="messages" showDetail="true"/> </h:form>
Looks like javax.faces.SEPARATOR_CHAR must not be equal to _
Putting p:fileUpload inside a h:form solved the problem at my case.
I had same issue with primefaces 5.3 and I went through all the points described by BalusC with no result. I followed his advice of debugging FileUploadRenderer#decode() and I discovered that my web.xml was unproperly set <context-param> <param-name>primefaces.UPLOADER</param-name> <param-value>auto|native|commons</param-value> </context-param> The param-value must be 1 of these 3 values but not all of them!! The whole context-param section can be removed and the default will be auto
bean.xhtml <h:form enctype="multipart/form-data"> <p:outputLabel value="Choose your file" for="submissionFile" /> <p:fileUpload id="submissionFile" value="#{bean.file}" fileUploadListener="#{bean.uploadFile}" mode="advanced" auto="true" dragDropSupport="false" update="messages" sizeLimit="100000" fileLimit="1" allowTypes="/(\.|\/)(pdf)$/" /> </h:form> Bean.java #ManagedBean #ViewScoped public class Submission implements Serializable { private UploadedFile file; //Gets //Sets public void uploadFasta(FileUploadEvent event) throws FileNotFoundException, IOException, InterruptedException { String content = IOUtils.toString(event.getFile().getInputstream(), "UTF-8"); String filePath = PATH + "resources/submissions/" + nameOfMyFile + ".pdf"; MyFileWriter.writeFile(filePath, content); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, event.getFile().getFileName() + " is uploaded.", null); FacesContext.getCurrentInstance().addMessage(null, message); } } web.xml <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> <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>
Neither of the suggestions here were helpful for me. So I had to debug primefaces and found the reason of the problem was: java.lang.IllegalStateException: No multipart config for servlet fileUpload Then I have added section into my faces servlet in the web.xml. So that has fixed the problem: <servlet> <servlet-name>main</servlet-name> <servlet-class>org.apache.myfaces.webapp.MyFacesServlet</servlet-class> <load-on-startup>1</load-on-startup> <multipart-config> <location>/tmp</location> <max-file-size>20848820</max-file-size> <max-request-size>418018841</max-request-size> <file-size-threshold>1048576</file-size-threshold> </multipart-config> </servlet>
For people using Tomee or Tomcat and can't get it working, try to create context.xml in META-INF and add allowCasualMultipartParsing="true" <?xml version="1.0" encoding="UTF-8"?> <Context allowCasualMultipartParsing="true"> <!-- empty or not depending your project --> </Context>
With JBoss 7.2(Undertow) and PrimeFaces 6.0 org.primefaces.webapp.filter.FileUploadFilter should be removed from web.xml and context param file uploader should be set to native: <context-param> <param-name>primefaces.UPLOADER</param-name> <param-value>native</param-value> </context-param>
I had the same issue, due to the fact that I had all the configuration that describe in this post, but in my case was because I had two jQuery imports (one of them was PrimeFaces's bundled jQuery) which caused conflicts to upload files. Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors
net.sf.jsfcomp.ext.onload.OnLoadPhaseListener not working in JSF 2
We are upgrading from jsf 1.2 to jsf 2. We are using apache myfaces 2.1 and rich faces 4.3. We have onload-phase listener configured like below (for JSF 1.2) web.xml : <context-param> <param-name>onload-config</param-name> <param-value>/WEB-INF/onload-config.xml</param-value> </context-param> and corresponding phase listener configured in faces-config.xml as : <lifecycle> <phase-listener>net.sf.jsfcomp.ext.onload.OnLoadPhaseListener</phase-listener> <lifecycle> We are using same configuration as is for migrating to JSF 2 and as I know we don't need to include any extra jar for above set up to work. (jsf implementation and commons-logging jars are the only pre-requisites) However when a url is clicked which is to invoke an action method for configuration in onload-config.xml as below : <navigation-rule> <view-id>/from-page.xhtml</view-id> <action>#{bean.action}</action> </navigation-rule> bean.action is not getting invoked and resource not found error is returned. Am i missing any configuration ? or do i need to add any extra libs ? Please help. EDIT 1 : Adding more details for the issue : The page being rendered after bean.action method is returned is as below : <ui:composition> <a4j:form id="sample-Form"> <ui:include src="#{bean.panel}"> </ui:include> <h:commandButton id="button1" value="Go" action="#{bean.next}"/> </a4j:form> </ui:composition> where on clicking the next button , same page is rendered with dynamic panel name (bean.panel) returned from back end
Request scope issue in IBM portal 8.0
I have a JSR 286 portlet running in a Websphere Portal Server 8.0. There, I do a file upload and after show the results of processing. Initially my managed bean responsible to process this file has a Request Scope (#RequestScoped). When I Click in command button to upload file, the method in MB process correctly and fills a collection of results (dadosCarga attribute in MB below) that must be showed in JSP page. However, when I the page is rederized I got a stacktrace explaining that my Managed Bean class was not found (ClassNotFoundException) and results are not shown. I got the same results using ViewScoped. Just when I changed scope from Request to Session (#SessionScoped), the results are shown. After I googled for some answer, I found this page explaining about difference between action and render request in Portlets. It was suggested to use JSF Portlet bridge. However, this page is not active anymore. There is a Portlet bridge for Apache Myfaces (IBM portal runs over MyFaces). However, I could not see how use it. Is it just put both jars (api and implementation) in WEB-INF/lib? I tried, but I got a exception when I tried load the pages in application. So I remove them. Below, I show My Portlet configuration, Managed Bean and JSP page. Is there any alternative, a better Idea about how to deal with this? Or may be a explanation about how to use correclty MyFaces Bridge (I could not found none in its home page). Thanks, Rafael Afonso Portlet configuration: <portlet> <portlet-name>CargaUsuarios</portlet-name> <display-name>CargaUsuarios</display-name> <portlet-class>com.ibm.faces20.portlet.FacesPortlet</portlet-class> <init-param> <name>com.ibm.faces.portlet.page.view</name> <value>/pages/carga/cargaUsuarios.jsp</value> </init-param> <init-param> <name>wps.markup</name> <value>html</value> </init-param> <expiration-cache>0</expiration-cache> <supports> <mime-type>text/html</mime-type> <portlet-mode>view</portlet-mode> </supports> <portlet-info> <title>Carga de Usuarios</title> <short-title>Carga deUsuarios</short-title> <keywords>Carga Usuario</keywords> </portlet-info> </portlet> Manged Bean: #ManagedBean(name = "cargaUsuariosMB") #RequestScoped public class CargaUsuariosMB extends AbstractMB { private String nomeArquivo; // FIle name private Collection<CargaUsuarioInfoBean> dadosCarga; // processing result. public String doUploadArquivo() { this.dadosCarga = ... // process file and receives a collection this.nomeArquivo = ... // get uploaded file name return null; // Return to same origin page } // Getters... } JSP page (cargaUsuarios.jsp): <%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%#taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <%#taglib uri="http://java.sun.com/jsf/html" prefix="h"%> <%#taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%> <%#taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v6.1/portlet-client-model" prefix="portlet-client-model"%> <%#page language="java" contentType="text/html" pageEncoding="ISO-8859-1" session="false"%> <portlet:defineObjects /> <portlet-client-model:init> <portlet-client-model:require module="ibm.portal.xml.*" /> <portlet-client-model:require module="ibm.portal.portlet.*" /> </portlet-client-model:init> <f:view> <h2>Carga de Usuários</h2> <h:form enctype="multipart/form-data"> <p> <label for="arquivoCarga"> <span>File:</span> </label> <input type="file" name="arquivoCarga" id="FileCarga" /> </p> <br /> <br /> <h:commandButton value="Salvar File" action="#{cargaUsuariosMB.doUploadArquivo}"></h:commandButton> </h:form> <h:panelGroup id="pnlProcessamento" rendered="#{not empty cargaUsuariosMB.dadosCarga }"> <h:outputText value="Dados do File #{cargaUsuariosMB.nomeArquivo} processados com sucesso."></h:outputText> <br /> <h:dataTable id="tblDadosProcessamento" columnClasses="numLinha,cpf,status" value="#{cargaUsuariosMB.dadosCarga}" var="dadosCarga" styleClass="dadosProcessamento" width="100%" border="1"> <%-- Show processing results. --%> </h:dataTable> </h:panelGroup> <h:messages styleClass="messages" id="msgsPesquisaCadastro" errorClass="mensagensErro" errorStyle="color: red;"></h:messages> </f:view>
Please try adding the following in the portlet.xml and see if it works: <container-runtime-option> <name>javax.portlet.actionScopedRequestAttributes</name> <value>true</value> </container-runtime-option> For more information please download and check the following section in Portlet V2.0 specification: PLT.10.4.4 Runtime Option javax.portlet.actionScopedRequestAttributes
You are right about the render and action request, JSF (or CDI) Request and ViewScoped doesn't work properly. But solution could be using JBoss Portlet Bridge which contains brand new scopes - PortletLifecycleScoped and PortletRedisplayScoped. The first will behave exactly like a RequestScope, you will find more info in the docs. However, I am not sure if will able to use these scopes in other portals except GateIn.
When you use request scope, the data needs to be carried from portlet action to portlet render phase. The data is normally carried for request scoped beans via the portlet render parameters are a String. In order to get your data saved there, your object needs to be Serializable. Besides that, you might want to upgrade your WebSphere Application Server beneath the WebSphere Portal to version 8.0.0.6 to avoid PM79460 and Portal itself to the latest FixPack as well. Hope this helps. BTW: JSR286 and JEE6 do not specify how CDI shall interact with the Portlet programming model. You might want to look at JSR362 for that.
IBM uses its own portlet bridge. It is not recommended to use any bridges in addition to that.
Struts 2.2.1 gives There is no Action mapped for namespace / and action name
I've got a simple Struts 2 application that I build and deploy to glassfish with Netbeans. When I point the web browser to http://localhost:8080/Struts2Hello/login.action/ it gives this error: There is no Action mapped for namespace / and action name . My action is named "login". Why does it think it is named "."? (In order to get this far I've also had to add the javassist-3.7.ga to my lib/ directory. I'm not sure why, but that's what others have done to make Struts 2.2 work.) Here's my web.xml and struts.xml files (yes, the struts.xml gets deployed to WEB-INF/classes): <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>Login.jsp</welcome-file> </welcome-file-list> <package name="default" extends="struts-default" namespace="/"> <action name="login" class="action.LoginAction"> <result name="success">Welcome.jsp</result> <result name="error">Login.jsp</result> </action> </package> Thanks. Dean
My problem was that I had the .jsp files in the WEB-INF/ dir instead of one level higher. Strange error message for that problem, though.
In struts.xml(or any other struts config files included), content of mapping is back to the original Servlet/Jsp, i.e. you CAN NOT put .jsp files under WEB-INF. e.g. if the result in struts config file is: Welcome.jsp then you should put Welcome.jsp under the package root, like Web-pages ...WEB-INF ...Welcome.jsp ...menu ......menu.xhtml
More often that not when struts gets the action name wrong even when there's nothing wrong with struts.xml, the problem is that the tag lib definition is missing from the jsp file.
crazy to answer this one after a year, but I had the same problem and I was pretty sure that I had mapped all my actions accurately, but it was showing the same error above....so I just cleaned the project and then ran it again..it worked perfectly fine...give it a try ! I encountered this so many times...so to avoid such kind of things, I just added "../eclipse.exe -clean" to the shortcut icon property....this works and u can forget about getting such kind of errors which is actually not an error....!