In RichFaces, inorder to upload a file I used rich:fileUpload. By using rich:fileUpload Add, Upload and Clear All buttons are automatically generating in the richfaces livedemo example but for me Add, Upload and Clear All are appearing as text in my browser where should I change so that Add,upload and clearAll can be clickable. Do I have to change any settings in web.xml / pom.xml file.
I am using RichFaces 4 and JSF 2.
This is my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<display-name>Sample RichFaces 4 Application</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>#{skinBean.skin}</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.fileUpload.maxRequestSize</param-name>
<param-value>1000000000</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.fileUpload.createTempFiles</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<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>*.jsf</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<mime-mapping>
<extension>ecss</extension>
<mime-type>text/css</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>index.jsf</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
Hi, i am getting those add and update buttons now correctly by simply providing h:head and h:body tags but i am getting this exception javax.faces.event.AbortProcessingException and files are not being uploaded as shown in the example provided in the link "FileUpload example".Can anyone plz help me out from this issue
This is my xhtml page
<!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://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich">
<ui:composition>
<h:head>
<h:outputStylesheet>
.top {
vertical-align: top;
}
.info {
height: 202px;
overflow: auto;
}
</h:outputStylesheet>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2" columnClasses="top,top">
<rich:fileUpload fileUploadListener="#{fileUploadBean.listener}" id="upload" acceptedTypes="jpg, gif, png, bmp"
ontyperejected="alert('Only JPG, GIF, PNG and BMP files are accepted');" maxFilesQuantity="5">
<a4j:ajax event="uploadcomplete" execute="#none" render="info" />
</rich:fileUpload>
<h:panelGrid id="info" layout="block">
<rich:panel bodyClass="info">
<f:facet name="header">
<h:outputText value="Uploaded Files Info" />
</f:facet>
<h:outputText value="No files currently uploaded" rendered="#{fileUploadBean.size==0}" />
<rich:dataGrid columns="1" value="#{fileUploadBean.files}" var="file" rowKeyVar="row">
<rich:panel bodyClass="rich-laguna-panel-no-header">
<h:panelGrid columns="2">
<a4j:mediaOutput element="img" mimeType="image/jpeg" createContent="#{fileUploadBean.paint}"
value="#{row}" style="width:100px; height:100px;" cacheable="false">
<f:param value="#{fileUploadBean.timeStamp}" name="time" />
</a4j:mediaOutput>
<h:panelGrid columns="2">
<h:outputText value="File Name:" />
<h:outputText value="#{file.name}" />
<h:outputText value="File Length(bytes):" />
<h:outputText value="#{file.length}" />
</h:panelGrid>
</h:panelGrid>
</rich:panel>
</rich:dataGrid>
</rich:panel>
<br/>
<a4j:commandButton action="#{fileUploadBean.clearUploadData}" render="info, upload" value="Clear Uploaded Data"
rendered="#{fileUploadBean.size>0}" />
</h:panelGrid>
</h:panelGrid>
</h:form>
</h:body>
</ui:composition>
</html>
This is my FileUploadBean Class
package com.acc.upload;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import com.acc.fileupload.utils.FileUploadEvent;
import com.acc.fileupload.utils.UploadedFile;
#ManagedBean(name = "fileUploadBean")
#SessionScoped
public class FileUploadBean{
private ArrayList<File> files = new ArrayList<File>();
private int uploadsAvailable = 5;
private boolean autoUpload = false;
private boolean useFlash = true;
public int getSize() {
if (getFiles().size()>0){
return getFiles().size();
}else
{
return 0;
}
}
public FileUploadBean() {
}
public void paint(OutputStream stream, Object object) throws IOException {
stream.write(getFiles().get((Integer)object).getData());
}
public void listener(FileUploadEvent event) throws Exception{
UploadedFile item = event.getUploadedFile();
File file = new File();
file.setLength(item.getData().length);
file.setName(item.getName());
file.setData(item.getData());
files.add(file);
uploadsAvailable--;
}
public String clearUploadData() {
files.clear();
setUploadsAvailable(5);
return null;
}
public long getTimeStamp(){
return System.currentTimeMillis();
}
public ArrayList<File> getFiles() {
return files;
}
public void setFiles(ArrayList<File> files) {
this.files = files;
}
public int getUploadsAvailable() {
return uploadsAvailable;
}
public void setUploadsAvailable(int uploadsAvailable) {
this.uploadsAvailable = uploadsAvailable;
}
public boolean isAutoUpload() {
return autoUpload;
}
public void setAutoUpload(boolean autoUpload) {
this.autoUpload = autoUpload;
}
public boolean isUseFlash() {
return useFlash;
}
public void setUseFlash(boolean useFlash) {
this.useFlash = useFlash;
}
}
File Class
package com.acc.upload;
public class File {
private String Name;
private String mime;
private long length;
private byte[] data;
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
int extDot = name.lastIndexOf('.');
if(extDot > 0){
String extension = name.substring(extDot +1);
if("png".equals(extension)){
mime="image/png";
}else {
mime = "img/unknown";
}
}
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public String getMime(){
return mime;
}
}
Thanks a lot.Now that error is gone for me .
I set the createTemp files to true in web.xml but i am unable to find the uploaded file in the temp folder in my local system.And also is it possible to store the uploaded file to a desired location in our local system by changing any settings in web.xml file ?
Please help in these two issues.
Regarding your buttons icons problem, I'm pretty sure you don't manage yourself the skin of RichFaces, so you can remove this from your web.xml :
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>#{skinBean.skin}</param-value>
</context-param>
RichFaces will now use the default skin option.
According to your comment, you where missing h:head which is mandatory in order to include necessary resources CSS and JavaScript for RichFaces.
Moreover, your last problem is related to your imports that are bad :
import com.acc.fileupload.utils.FileUploadEvent;
import com.acc.fileupload.utils.UploadedFile;
should be replaced for :
import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;
Other info :
The example you are based on is from RichFaces 3.3.3 (this is shown in the footer). Double check your view code with this example for RichFaces 4.3.2.
I also get this problem with richface 4.0.0 and spring 4. When upload the file I alway get this error message "Request prolog cannot be read".
And I solved this problem by: set multipart resolever to
instead of CommonsMultipartResolver
for DispatcherServlet. Because the CommonsMultipartResolver of spring is not consistent with richface 4.0.0
Hope this help!
Related
This question already has an answer here:
Primefaces selectonemenu displaying data outside the input [duplicate]
(1 answer)
Closed 6 years ago.
I am trying to build a web app that involves a drop down menu which, upon selecting an option, populates a table with data. I had issues, and so tried to isolate the problem by trying to recreate the following example from the Primefaces website. I am having the following problems:
1) The selectOneMenu produces a textbox right above it in the resulting page.
2) The seelctOneMenu also produces a bulleted list of the options that are already on that select menu.
3) The ajax listener on the first select menu does not update the second menu, and does not seem to run any method in the DropdownView class.
In a nutshell, the output is unexpected, especially since I am more or less copy/pasting example code.
I am running this all on JDeveloper12c with Weblogic, JSF 2.2 and Primefaces 6.0.
Here is the code I am running, almost all of which is copy/pasted from the Primefaces site
Here's my dropdown.xhtml:
<!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://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<body>
<h:form>
<h:messages errorStyle="color:red" />
<p:growl id="msgs" showDetail="true" />
<p:panel header="Select a Location" style="margin-bottom:10px;">
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel for="country" value="Country: " />
<p:selectOneMenu id="country" value="#{dropdownView.country}" style="width:150px">
<p:ajax listener="#{dropdownView.onCountryChange()}" update="city" />
<f:selectItem itemLabel="Select Country" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{dropdownView.countries}" />
</p:selectOneMenu>
<p:outputLabel for="city" value="City: " />
<p:selectOneMenu id="city" value="#{dropdownView.city}" style="width:150px">
<f:selectItem itemLabel="Select City" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{dropdownView.cities}" />
</p:selectOneMenu>
</h:panelGrid>
<p:separator />
<p:commandButton value="Submit" update="msgs" actionListener="#{dropdownView.displayLocation()}" icon="ui-icon-check" />
</p:panel>
</h:form>
</body>
</html>
My DropdownView.java, which is the same code from the example site:
package test;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#ViewScoped
public class DropdownView implements Serializable {
private Map<String,Map<String,String>> data = new HashMap<String, Map<String,String>>();
private String country;
private String city;
private Map<String,String> countries;
private Map<String,String> cities;
#PostConstruct
public void init() {
countries = new HashMap<String, String>();
countries.put("USA", "USA");
countries.put("Germany", "Germany");
countries.put("Brazil", "Brazil");
Map<String,String> map = new HashMap<String, String>();
map.put("New York", "New York");
map.put("San Francisco", "San Francisco");
map.put("Denver", "Denver");
data.put("USA", map);
map = new HashMap<String, String>();
map.put("Berlin", "Berlin");
map.put("Munich", "Munich");
map.put("Frankfurt", "Frankfurt");
data.put("Germany", map);
map = new HashMap<String, String>();
map.put("Sao Paolo", "Sao Paolo");
map.put("Rio de Janerio", "Rio de Janerio");
map.put("Salvador", "Salvador");
data.put("Brazil", map);
}
public Map<String, Map<String, String>> getData() {
return data;
}
public void setData(Map<String, Map<String, String>> data) {
this.data = data;
}
public void setCountries(Map<String, String> countries) {
this.countries = countries;
}
public void setCities(Map<String, String> cities) {
this.cities = cities;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Map<String, String> getCountries() {
return countries;
}
public Map<String, String> getCities() {
return cities;
}
public void onCountryChange() {
if(country !=null && !country.equals(""))
cities = data.get(country);
else
cities = new HashMap<String, String>();
}
public void displayLocation() {
FacesMessage msg;
if(city != null && country != null)
msg = new FacesMessage("Selected", city + " of " + country);
else
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid", "City is not selected.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
Here is my web.xml:
<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app 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"
version="3.0">
<servlet>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>
Here is my faces-config.xml:
<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>
Replace the HTML <body> tag by the JSF <h:body> tag. Probably even more important, add an <h:head /> line. It may be empty, but it's important because that's where the JavaScript and CSS files are added.
BTW, the problems you describe indicate that these files are missing. You see how the selectOneMenu is constructed from the HTML building blocks, but without the CSS and JavaScript glue code.
I'm trying to use Bean validation instead of JSF validation since it is a more DRY aproach, i'm using the annotations on my model but when i insert null data on jsf fields it does nothing...
None of the annotations that i'm using is having any effect, its like they are not there....
I'm using Tomcat 8
My xhtml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</h:head>
<h:body>
<h1>Cadastro de funcionario</h1>
<h:form>
<h:messages/>
<h:panelGrid columns="3">
<h:outputLabel value="Salário: R$ " for="campo-salario"/>
<h:inputText id="campo-salario" value="#{funcionarioBean.funcionario.salario}">
<f:convertNumber locale="pt_BR"/>
</h:inputText>
<h:message for="campo-salario" />
<h:outputLabel value="Código: " for="campo-codigo"/>
<h:inputText id="campo-codigo" value="#{funcionarioBean.funcionario.codigo}"/>
<h:message for="campo-codigo"/>
<h:outputLabel value="Data: " for="campo-aniversario"/>
<h:inputText id="campo-aniversario" value="#{funcionarioBean.funcionario.aniversario}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:inputText>
<h:message for="campo-aniversario"/>
<h:commandButton value="Cadastrar" action="#{funcionarioBean.mensagem}"/>
</h:panelGrid>
</h:form>
</h:body>
</html>
My Bean
#ManagedBean
public class FuncionarioBean {
private Funcionario funcionario = new Funcionario();
public void mensagem(){
System.out.println("Pressionado");
}
public Funcionario getFuncionario() {
return funcionario;
}
public void setFuncionario(Funcionario funcionario) {
this.funcionario = funcionario;
}
}
My Funcionario class
import java.util.Date;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class Funcionario {
#NotNull(message="{br.com.k19.Funcionario.nome")
#Min(value = 0)
private Double salario;
#NotNull
#Min(value = 5)
#Max(value = 19)
private Integer codigo;
#NotNull
private Date aniversario;
public Double getSalario() {
return salario;
}
public void setSalario(Double salario) {
this.salario = salario;
}
public Integer getCodigo() {
return codigo;
}
public void setCodigo(Integer codigo) {
this.codigo = codigo;
}
public Date getAniversario() {
return aniversario;
}
public void setAniversario(Date aniversario) {
this.aniversario = aniversario;
}
}
My lib
Can't post pictures yet.
Lib
>
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.6.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-validator-5.0.0.final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
javax.servlet.jsp.jstl-1.2.1.jar
javax.servlet.jsp.jstl-api-1.2.1.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jsf-api-2.2.8.jar
jsf-impl-2.2.8.jar
mysql-connector-java-5.1.23.bin.jar
omnifaces-1.8.1.jar
primefaces-5.0.jar
validation-api-1.0.0.GA.jar
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 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>K19-Conversao-e-Validacao</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>com.sun.faces.writeStateAtFormEnd</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
</web-app>
Downloaded hibernate jars again to match the versions
Download validator: http://hibernate.org/validator/
Download ORM: http://hibernate.org/orm/
My lib
Working as intend now
ref: Bean Validation #NotNull, #NotBlank and #NotEmpty does not work in JSF+Tomcat
I'm trying to upload a file using PrimeFaces, but the fileUploadListener method isn't being invoked after the upload finishes. I add the jar commons-io and commons-fileupload.
I am using
glassifish 3.1
primafaces 5.0
eclipseLink
jsf 2.
I searched a lot but nothing worked. This is my code.
The managed Bean :
package image;
import java.io.IOException;
import java.io.InputStream;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
#ManagedBean(name="uploadBean")
#SessionScoped
public class UploadBean {
private UploadedFile file;
private Fichier fichier;
#EJB
private FichierDao fichierDao;
public UploadBean()
{
fichier = new Fichier();
}
public void handleFileUpload(FileUploadEvent event) {
file= event.getFile();
// System.out.print("gfghfhgf"+file.getSize());
}
// Store file in the database
public void storeImage() {
System.out.println("11111mamlamlmalmalmlkljkjkhkjhjhjghj");
try {
InputStream is =file.getInputstream() ;
fichier.setKey(IOUtils.toByteArray(is));
System.out.println("22222222mamlamlmalmalmlkljkjkhkjhjhjghj");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("33333333333mamlamlmalmalmlkljkjkhkjhjhjghj");
}
System.out.println("44444444444mamlamlmalmalmlkljkjkhkjhjhjghj");
fichierDao.create(fichier);
System.out.println("55555555555mamlamlmalmalmlkljkjkhkjhjhjghj");
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public Fichier getFichier() {
return fichier;
}
}
the page xhtml
<!DOCTYPE html>
<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:p="http://primefaces.org/ui">
<h:head>
<meta charset="utf-8" />
</h:head>
<h:body>
<h:outputText value="PrimeFaces Single Upload"
style="font:30px bold; margin-left:15%;" />
<h:form enctype="multipart/form-data">
<p:fileUpload
fileUploadListener="#{uploadBean.handleFileUpload}" ajax="false"
mode="advanced"
label="Choisir une image"
update="messages"
sizeLimit="100000"
fileLimit="1"
invalidSizeMessage="La taille maximale du fichier est 1 Megabyte !"
invalidFileMessage="Charger des images"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />
<p:growl id="messages" showDetail="true" />
<p:commandButton value="Submit" action="#{uploadBean.storeImage}" />
</h:form>
</h:body>
</html>
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<!-- Changer cette valeur à "Production" lors du déploiement final de l'application -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
<context-param>
<param-name>
javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL
</param-name>
<param-value>true</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>10240</param-value> <!-- 10 Mb -->
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<!-- Déclaration du contrôleur central de JSF : la FacesServlet -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Mapping : association des requêtes dont le fichier porte l'extension
.xhtml à la FacesServlet -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>page1.xhtml</welcome-file>
</welcome-file-list>
</web-app>`
Use ajax="false" on any command component that submits the File Upload or File Download form.
Since Upload/Download are HTTP GET requests don't use Ajax submits which are indeed POST requests.
<p:commandButton value="Submit" ajax="false" action="#{uploadBean.storeImage}" />
Here is an example of how to upload a file using primefaces 5.0; and you do not need commons-fileupload-1.3.1.jar and commons-io-2.4.jar; and also you do not need to change web.xml , and declare growl inside h:form and not inside p:fileUpload for more information see this How to upload files in primefaces
The managed Bean:
package image;
import java.io.IOException;
import java.io.InputStream;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import org.apache.commons.io.IOUtils;
import org.primefaces.model.UploadedFile;
#ManagedBean(name="uploadBean")
#SessionScoped
public class UploadBean {
private UploadedFile file;
private Fichier fichier;
#EJB
private FichierDao fichierDao;
public UploadBean()
{
fichier = new Fichier();
}
// Store file in the database
public void storeImage() {
if(!(file.getContentType().equalsIgnoreCase("image type"))){
FacesMessage message = new FacesMessage("Not Uploaded","Required file types: ");
FacesContext.getCurrentInstance().addMessage(null, message);
}
if(!(file.getSize() <= 10000000)){ // size
FacesMessage message = new FacesMessage("Not Uploaded","file size should be less than or equal to 10mb");
FacesContext.getCurrentInstance().addMessage(null, message);
}
if(file.getSize()==0){
FacesMessage message = new FacesMessage("","select a file");
FacesContext.getCurrentInstance().addMessage(null, message);
}
if((file.getSize() > 0 && file.getSize() <= 10000000) && (file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) ){
//your code here for storing image
System.out.println("11111mamlamlmalmalmlkljkjkhkjhjhjghj");
try {
InputStream is =file.getInputstream() ;
fichier.setKey(IOUtils.toByteArray(is));
System.out.println("22222222mamlamlmalmalmlkljkjkhkjhjhjghj");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("33333333333mamlamlmalmalmlkljkjkhkjhjhjghj");
}
System.out.println("44444444444mamlamlmalmalmlkljkjkhkjhjhjghj");
fichierDao.create(fichier);
System.out.println("55555555555mamlamlmalmalmlkljkjkhkjhjhjghj");
//your code above for storing image
FacesMessage message = new FacesMessage("Succesfull", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public Fichier getFichier() {
return fichier;
}
}
the page xhmtl:
<!DOCTYPE html>
<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:p="http://primefaces.org/ui">
<h:head>
<meta charset="utf-8" />
</h:head>
<h:body>
<h:outputText value="PrimeFaces Single Upload"
style="font:30px bold; margin-left:15%;" />
<h:form enctype="multipart/form-data">
<p:growl id="messages" showDetail="true" />
<p:fileUpload
value="#{uploadBean.file}" mode="simple"/>
<p:commandButton value="Submit" actionListener="#{uploadBean.storeImage}"
ajax="false" disabled="false"/>
</h:form>
</h:body>
</html>
I tried to go through all possible set of questions posted earlier here such as :
#ViewScoped creating new instance on every postback
#ViewScoped calls #PostConstruct on every postback request
As per the suggestions provided there I have tried to apply all set of solutions still its creating a new instance and calling the init(#postConstruct) method every time.
Below are my configurations and version details:
JSF2.1.19
<bean id="connectDashBoardBean" class="com.xyz.ConnectDashBoardBean" scope="view"/>
XHTML:
<h:commandLink id="skills" action="#{connectDashBoardBean.navigateToSkills}"
title="Click To View" class="#{connectDashBoardBean.skillsUpdateFlg ? 'favMenuSelected':'favMenu'}">
<div id="skill" class="favContentHead">
<div class="favContentHeadImg">
<h:graphicImage value="/test/skills.png" height="20" width="20" />
</div>
<div class="favContentHeadText">
<h:outputText value="Skills" />
</div>
<div class="favContentHeadUpdate">
<h:outputText value="1B+" />
</div>
</div>
<f:ajax render="west center" execute="skills" />
</h:commandLink>
In all my xhtml I am not using any JSTL tag , I am using <ui:include/>
I have changed in my web.xml as below as well:
<context-param>
<description>STATE Saving disabled</description>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>false</param-value>
</context-param>
or
<context-param>
<description>STATE Saving disabled</description>
<param-name>javax.faces.FULL_STATE_SAVING_VIEW_IDS</param-name>
<param-value>/connectDashBoard.xhtml,/connectDashBoard_Body.xhtml</param-value>
</context-param>
#PostConstruct
public void prePopulate() {
FacesContext facesContext = FacesContext.getCurrentInstance();
this.sessonKey = facesContext.getExternalContext().getRequestParameterMap().get("sessionKey");
LOG.debug("request---->{}",sessonKey);
if(!intialLoading){
users.add("Jayaram");
createPieModel();//TODO populate the chart details latter
name = "Jayaram Pradhan";
newsUpdateFlg = Boolean.TRUE;
}
LOG.debug("Key Properly Getting passed--->{}",sessonKey);
}
web.xml:
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<description>STATE Saving disabled</description>
<param-name>javax.faces.FULL_STATE_SAVING_VIEW_IDS</param-name>
<param-value>/connectDashBoard.xhtml,/connectDashBoard_Body.xhtml</param-value>
</context-param>
<context-param>
<description>STATE Saving disabled</description>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>javax.faces.INTERPRET_STRING_SUBMITTED_VALUE_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<filter>
<filter-name>gzipResponseFilter</filter-name>
<filter-class>org.omnifaces.filter.GzipResponseFilter</filter-class>
<init-param>
<description>
The threshold size in bytes. Must be a number between 0 and 9999. Defaults to 500.
</description>
<param-name>threshold</param-name>
<param-value>150</param-value>
</init-param>
<init-param>
<description>
The mimetypes which needs to be compressed. Must be a commaseparated string. Defaults to the below values.
</description>
<param-name>mimetypes</param-name>
<param-value>
text/plain, text/html, text/xml, text/css, text/javascript, text/csv, text/rtf,
application/xml, application/xhtml+xml, application/javascript, application/json
</param-value>
</init-param>
XHTML:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:sf="http://www.springframework.org/tags/faces"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
template="/templates/common_layout.xhtml">
<ui:define name="body">
<h:form id="dashBoard" onsubmit="saveScrollPos()" prependId="false">
<h:inputHidden id="scrollPos" />
<ui:remove>
<ui:include src="/templates/connectHome_Banner.xhtml" />
<ui:include src="connectDashBoard_Body.xhtml" />
</ui:remove>
<h:commandLink id="skills" actionListener="#{connectDashBoardBean.navigateToSkills}"
title="Click To View" class="#{connectDashBoardBean.skillsUpdateFlg ? 'favMenuSelected':'favMenu'}">
<div id="skill" class="favContentHead">
<div class="favContentHeadImg">
<h:graphicImage value="/test/skills.png" height="20" width="20" />
</div>
<div class="favContentHeadText">
<h:outputText value="Skills" />
</div>
<div class="favContentHeadUpdate">
<h:outputText value="1B+" />
</div>
</div>
<f:ajax render="skills" execute="skills" />
</h:commandLink>
</h:form>
</ui:define>
</ui:composition>
Managed Bean:
public class ConnectDashBoardBean implements CommonInterface {
private static final long serialVersionUID = 8648865830621770920L;
protected static final Logger LOG = LoggerFactory.getLogger(ConnectDashBoardBean.class);
public ConnectDashBoardBean() {
super();
LOG.debug("Instance of {}, created--->", this.getClass());
connectActivities = new ArrayList<ConnectActivity>(0);
users = new ArrayList<String>(0);
}
private List<ConnectActivity> connectActivities;
private String name;// TODO this can be move to current user
private boolean intialLoading;
private boolean refreshRequiredFlag;
private boolean loadNextSetFlag;
private int loadCount;
private String sessonKey;
private PieChartModel pieModel;
private List<String> users;
private boolean newsUpdateFlg;
private boolean skillsUpdateFlg;
/**
* <p>
* This will load all the deatils used by user
*
* #param expenseName
* #param emailOrPhone
* #param shareUserList
*/
#PostConstruct
public void prePopulate() {
FacesContext facesContext = FacesContext.getCurrentInstance();
this.sessonKey = facesContext.getExternalContext().getRequestParameterMap().get("sessionKey");
LOG.debug("request---->{}",sessonKey);
if(!intialLoading){
users.add("Jayaram");
users.add("Chandan");
users.add("Maynak");
users.add("Madhusmita");
createPieModel();//TODO populate the chart details latter
name = "Jayaram Pradhan";
newsUpdateFlg = Boolean.TRUE;
}
LOG.debug("Key Properly Getting passed--->{}",sessonKey);
}
}
Additional Configurations For Spring way of managing life cycle:
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="com.xyz.custom.scope.ViewScope" />
</entry>
<entry key="threadLocal">
<bean class="com.xyz.custom.scope.ThreadScope"/>
</entry>
</map>
</property>
</bean>
public class ViewScope implements Scope {
#Override
public Object get(String name, ObjectFactory<?> objectFactory) {
if (FacesContext.getCurrentInstance().getViewRoot() != null) {
Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
if (viewMap.containsKey(name)) {
return viewMap.get(name);
} else {
Object object = objectFactory.getObject();
viewMap.put(name, object);
return object;
}
} else {
return null;
}
}
#Override
public Object remove(String name) {
if (FacesContext.getCurrentInstance().getViewRoot() != null) {
return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name);
} else {
return null;
}
}
#Override
public void registerDestructionCallback(String name, Runnable callback) {
// Do nothing
}
#Override
public Object resolveContextualObject(String key) {
return null;
}
#Override
public String getConversationId() {
return null;
}
}
I would Like to understand, is there any way, that I can overcome making this call every time and creating a new instance?
I created this new question as seems other similar questions are already a long ago.
Thanks.
I am studying primefaces themes on Primefaces user guide.
https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/primefaces/primefaces_users_guide_3_3.pdf At pag. 457 you can read: "Once you've downloaded the theme, configure PrimeFaces to use it
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>aristo</param-value>
</context-param>
Where should I put it? Into the webpage file I am developing?
I choosed the jar file of Redmond theme and I imported it into my Eclipse Dynamic web project, but I don't see any improvement.
The Primefaces example I am testing is: https://www.primefaces.org/showcase/ui/data/datatable/basic.xhtml
Car.java
import java.util.Date;
public class Car {
private String model;
private int year;
private String manufacturer;
private String color;
public Car(String model, int year, String manufacturer, String color) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
TableBean.java
package classi;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;
#ManagedBean(name="tableBean")
#SessionScoped
public class TableBean implements Serializable
{
private final static String[] colors;
private final static String[] manufacturers;
private List<Car> carsSmall;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
manufacturers = new String[10];
manufacturers[0] = "Mercedes";
manufacturers[1] = "BMW";
manufacturers[2] = "Volvo";
manufacturers[3] = "Audi";
manufacturers[4] = "Renault";
manufacturers[5] = "Opel";
manufacturers[6] = "Volkswagen";
manufacturers[7] = "Chrysler";
manufacturers[8] = "Ferrari";
manufacturers[9] = "Ford";
}
public TableBean() {
carsSmall = new ArrayList<Car>();
populateRandomCars(carsSmall, 9);
}
private void populateRandomCars(List<Car> list, int size) {
for(int i = 0 ; i < size ; i++)
list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor()));
}
public List<Car> getCarsSmall() {
return carsSmall;
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomManufacturer() {
return manufacturers[(int) (Math.random() * 10)];
}
private String getRandomModel() {
return UUID.randomUUID().toString().substring(0, 8);
}
}
table.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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<h:form>
<p:dataTable var="car" value="#{tableBean.carsSmall}">
<p:column headerText="Model">
<h:outputText value="#{car.model}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Manufacturer">
<h:outputText value="#{car.manufacturer}" />
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}" />
</p:column>
</p:dataTable>
</h:form>
</body>
</html>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>PrimeFaces_DataTable</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>/faces/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>redmond</param-value>
</context-param>
<context-param>
<description>
This parameter tells MyFaces if javascript code should be allowed in
the rendered HTML output.
If javascript is allowed, command_link anchors will have javascript code
that submits the corresponding form.
If javascript is not allowed, the state saving info and nested parameters
will be added as url parameters.
Default is 'true'</description>
<param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<description>
If true, rendered HTML code will be formatted, so that it is 'human-readable'
i.e. additional line separators and whitespace will be written, that do not
influence the HTML code.
Default is 'true'</description>
<param-name>org.apache.myfaces.PRETTY_HTML</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<description>
If true, a javascript function will be rendered that is able to restore the
former vertical scroll on every request. Convenient feature if you have pages
with long lists and you do not want the browser page to always jump to the top
if you trigger a link or button action that stays on the same page.
Default is 'false'
</description>
<param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
</web-app>
Screenshot of project structure
http://i.imgur.com/tgrMH.png
A user told me I have to edit
<head> and </head>
into
<h:head> and </h:head>
It worked :)
You will have to put the theme jar in you WebContent/WEB-INF/lib folder, I don't know how you are deploying the project, so you could have to put primefaces jar there too, so that it will be in be in the deployed project.
With the jar's in place, you then have to edit your web.xml file to indicate what theme you would use. As an example with Redmond would be:
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>redmond</param-value>
</context-param>