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>
Related
I am using PrimceFaces and want to render a table, whose number of columns are determined dynamically. I found an example here:
https://www.primefaces.org/showcase/ui/data/datatable/columns.xhtml
and I think I implement it correctly, but the table is not rendered. Actually nothing is rendered at all. I debugged the programm and ascertained that:
CinemaSeatViewBean.getSeatsForShowList()
is getting called, but the method
CinemaSeatViewBean.getDataTableColumns()
is not called at all.
Below my code:
1.) The Managed Bean:
#ManagedBean
#ViewScoped
public class CinemaSeatViewBean implements Serializable {
private static final long serialVersionUID = 1L;
private List<SeatForShow> seatsForShowList = new ArrayList<SeatForShow>();
private List<DataTableColumn> dataTableColumns = new ArrayList<DataTableColumn>();
#PostConstruct
public void init() {
// add SeatForShows
ExternalContext extContext = FacesContext.getCurrentInstance()
.getExternalContext();
Flash flash = extContext.getFlash();
FilmShow selectedFilmShow = (FilmShow)flash.get(FilmAndCinemaChooserBean.SELECTED_FILM_SHOW);
int noOfColumns = selectedFilmShow.getNumberOfColumns();
for (int i = 0; i < noOfColumns; i ++){
// prepare dynamic columns
dataTableColumns.add(new DataTableColumn("Seat " + (i+1), "seatNo"));
}
for ( SeatForShow seatForShow: selectedFilmShow.getSeatsForShow()){
seatsForShowList.add(seatForShow);
}
}
public void setDataTableColumns(List<DataTableColumn> dataTableColumns) {
this.dataTableColumns = dataTableColumns;
}
public List<DataTableColumn> getDataTableColumns() {
return dataTableColumns;
}
public List<SeatForShow> getSeatsForShowList() {
return seatsForShowList;
}
public void setSeatsForShowList(List<SeatForShow> seatsForShowList) {
this.seatsForShowList = seatsForShowList;
}
}
2.) The facelet:
<!DOCTYPE html>
<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"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
</h:head>
<h:body>
<h:form id="seatsFormId">
<p:dataTable id="seatsTableId" value="#{cinemaSeatViewBean.seatsForShowList}" var="seatForShow">
<p:columns value="#{dataTableView.dataTableColumns}" var="column" sortBy="#{seatForShow[column.property]}">
<f:facet name="header">
<h:outputText value="#{column.header}" />
</f:facet>
<h:outputText value="#{seatForShow[column.property]}" />
</p:columns>
</p:dataTable>
</h:form>
</h:body>
</html>
3.) The DataTableColumn class:
public class DataTableColumn implements Serializable{
private static final long serialVersionUID = 1L;
private String header;
private String property;
public DataTableColumn(String header, String property) {
this.header = header;
this.property = property;
}
public String getHeader() {
return header;
}
public String getProperty() {
return property;
}
}
4.) I hope I enabled DEVELOPMENT_MODE correctly:
<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">
<context-param>
<param-name>primefaces.CLIENT_SIDE_VALIDATION</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>facelets.REFRESH_PERIOD</param-name>
<param-value>0</param-value>
</context-param>
<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>
<!-- Map these files with JSF -->
<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>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>selectFilmCinema.xhtml</welcome-file>
</welcome-file-list>
Unless there is a typo,
<p:columns value="#{dataTableView.dataTableColumns}" var="column" sortBy="#{seatForShow[column.property]}">
Should be
<p:columns value="#{cinemaSeatViewBean.dataTableColumns}" var="column" sortBy="#{seatForShow[column.property]}">
But your IDE should warn you for this and I expected a runtime error too (unlesss the bean actually exists in your project and does not do anything in the getter).
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>
A question about JSF 2 implicit navigation. He seeks only page in the root directory? Because I separate my pages in folders on WebContent except index.php page that I let inside the WebContent. My application service begins normally opens the index page that contains a button to the login page, the login page is in a directory called "public" which is inside the WebContent directory. When I click the button on the index page shows that he could not find the login page.
I've tried to change the result of the method of the ManagedBean that directs you to the login page, looked like this: "public / login.xhtml", but neither worked.
I thank anyone who can help me.
EDIT
ManagedBean
package financeiro.web;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import financeiro.usuario.Usuario;
import financeiro.usuario.UsuarioRN;
#ManagedBean(name = "usuarioBean")
#RequestScoped
public class UsuarioBean {
private Usuario usuario;
private String confirmarSenha;
public UsuarioBean() {
}
public String novo() {
this.usuario = new Usuario();
this.usuario.setAtivo(true);
/*
* Solution according to the Xtreme Biker. Works now. Thanks.
* Before: public/usuario
* After: /public/usuario
*/
return "/publico/usuario";
}
public String salvar() {
FacesContext context = FacesContext.getCurrentInstance();
String senha = this.usuario.getSenha();
if (!senha.equals(this.confirmarSenha)) {
FacesMessage facesMessage = new FacesMessage(
"A senha não foi confirmada corretamente.");
context.addMessage(null, facesMessage);
return null;
}
UsuarioRN usuarioRN = new UsuarioRN();
usuarioRN.salvar(usuario);
return "usuarioSucesso";
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public String getConfirmarSenha() {
return confirmarSenha;
}
public void setConfirmarSenha(String confirmarSenha) {
this.confirmarSenha = confirmarSenha;
}
}
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"
version="3.0">
<display-name>FinanceiroWeb</display-name>
<servlet>
<display-name>Faces Servlet</display-name>
<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>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<filter>
<filter-name>conexaoFilter</filter-name>
<filter-class>financeiro.web.filter.ConexaoHibernateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>conexaoFilter</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
index.html
<meta http-equiv="Refresh" content="0;URL=publico/login.xhtml" />
login.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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Login</title>
</h:head>
<h:body>
<h1>Login</h1>
<hr />
<h:form>
<h:commandButton action="#{usuarioBean.novo}" value="Registre-se" />
</h:form>
<hr />
</h:body>
</html>
Directory structure of the project
OBS.: I use Maven Project
Link image: http://postimg.org/image/bm7iwbmxf/
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!