I have a problem implementing a simple CRUD application, I have read nearly all the items found in google, stackoverflow and roseindia, but my problem persists. I made this simple facelet:
<ui:composition template="./../../templates/adminTemplate.xhtml">
<ui:define name="tope">
<h1>Ingreso de Noticias</h1>
</ui:define>
<ui:define name="content">
<h:form id="newsForm">
<h:panelGrid columns="2">
<h:outputLabel value="Lugar: "/>
<h:inputText value="#{noticiasBean.entity.lugar}"/>
<h:outputLabel value="Fecha: "/>
<h:inputText value="#{noticiasBean.entity.fecha}">
<f:convertDateTime pattern="dd/MM/yyyy HH:mm"/>
</h:inputText>
<h:outputLabel value="Autor: "/>
<h:inputText value="#{noticiasBean.entity.autor}"/>
<h:outputLabel value="PreTítulo: "/>
<h:inputText value="#{noticiasBean.entity.pretitulo}"/>
<h:outputLabel value="Título: "/>
<h:inputText value="#{noticiasBean.entity.titulo}"/>
<h:outputLabel value="Comentario: "/>
<h:inputText value="#{noticiasBean.entity.comentario}"/>
<h:outputLabel value="Cuerpo: "/>
<h:inputTextarea value="#{noticiasBean.entity.cuerpo}"/>
</h:panelGrid>
<h:commandButton value="Guardar" action="#{noticiasBean.create}"/>
</h:form>
<h:messages style="color: red;"/>
</ui:define>
</ui:composition>
Here is the adminTemplate:
<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:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="./../resources/css/default.css" rel="stylesheet" type="text/css" />
<link href="./../resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
<h:outputStylesheet name="primeStyles.css" library="css"/>
<title>Facelets Template</title>
</h:head>
<h:body>
<p:layout fullPage="true">
<p:layoutUnit position="north" size="70" resizable="true" closable="true" collapsible="true">
<ui:insert name="tope"> Sección de Administración</ui:insert>
</p:layoutUnit>
<p:layoutUnit position="south" size="70">
<ui:insert> Pie de página </ui:insert>
</p:layoutUnit>
<p:layoutUnit position="west" size="160" header="Menu" resizable="true" collapsible="true">
<h:form id="formMenu">
<p:panelMenu style="width: 158px;">
<p:submenu label="Home">
<p:menuitem value="Admin" action="/admin/admin"/>
<p:menuitem value="Salir" action="#{loginController.logout}"/>
</p:submenu>
<p:submenu label="Contenido">
<p:menuitem value="Cargar Noticia" action="/admin/noticias/Create"/>
</p:submenu>
</p:panelMenu>
</h:form>
</p:layoutUnit>
<p:layoutUnit position="center">
<ui:insert name="content">
Aqui va el contenido
</ui:insert>
</p:layoutUnit>
</p:layout>
</h:body>
Here is the managedBean:
#ManagedBean(name="noticiasBean")
#RequestScoped
public class NoticiasBean {
private NoticiaJpaController jpaController = null;
private DataModel items = null;
private Noticia entity;
/**
* Creates a new instance of NoticiasBean
*/
public NoticiasBean() {
System.out.println("Instanciado el bean");
}
private NoticiaJpaController getJpaController() {
if(jpaController == null){
jpaController = new NoticiaJpaController(Utils.getEntityManagerFactory());
}
return jpaController;
}
public Noticia getEntity() {
if(entity == null){
entity = new Noticia();
}
return entity;
}
public String prepareCreate() {
entity = new Noticia();
return "Create";
}
public String create() {
System.out.println("Llegó al método create");
try {
getJpaController().create(entity);
String mensaje = "Noticia creada exitósamente";
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, mensaje, mensaje);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
return prepareCreate();
} catch (Exception e) {
String mensaje = "Error de Persistencia";
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, mensaje, mensaje);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
return null;
}
}
public String prepareList() {
recreateModel();
return "List";
}
public DataModel getItems() {
if (items == null) {
items = new ListDataModel(getJpaController().findNoticiaEntities());
}
return items;
}
private void recreateModel() {
items = null;
}
}
and here is the web.xml file:
<?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">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<description>Usado para evitar que ingresen sin estar autenticado</description>
<param-name>org.apache.myfaces.SERIALIZE_STATE_IN_SESION</param-name>
<param-value>false</param-value>
</context-param>
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/faces/index.xhtml</location>
</error-page>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
As you can see, there´s nothing special, but every time I press the h:commandButton, to save the data, always returns to the same page Create.xhtml without any error messages nor saves the information in the database, and worse, lose the reference to the style file syle.css.
After several readings and investigation, i fixed the problem reading this information of #BalusC. I never use two h:form elements in my facelet, so I dont why now is working. Just I changed the h:commandButton for the Primefaces' p:commandButton and "voila", everyyhing works fine now.
Related
index.xhtml
This page lists the product information where user can edit or delete products. When I click on edit link, the page gets redirected to editProduct.xhtml but the values are not loaded on the form. An empty form gets loaded. Values for selected productId gets printed in netbeans console but not in the jsf form.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:fcore="http://java.sun.com/jsf/core">
<h:head>
<title>Product </title>
</h:head>
<h:body>
<br/>
<center>
<h2> Product Lists</h2>
<fcore:view>
<h:form>
<h:dataTable var="lists" value="#{productController.getAllProduct()}" border="1" cellpadding="10">
<h:column>
<fcore:facet name="header">Product Id</fcore:facet>
<h:outputText value="#{lists.productId}" />
</h:column>
<h:column>
<fcore:facet name="header">Product Name</fcore:facet>
<h:outputText value="#{lists.productName}" />
</h:column>
<h:column>
<fcore:facet name="header">Product Price</fcore:facet>
<h:outputText value="#{lists.productPrice}" />
</h:column>
<h:column>
<fcore:facet name="header">Product Quantity</fcore:facet>
<h:outputText value="#{lists.productQty}" />
</h:column>
<h:column>
<fcore:facet name="header">Product Description</fcore:facet>
<h:outputText value="#{lists.productDesc}" />
</h:column>
<h:column>
<fcore:facet name="header">Purchase Date</fcore:facet>
<h:outputText value="#{lists.purchaseDate}" />
</h:column>
<h:column>
<fcore:facet name="header">Edit</fcore:facet>
<h:commandLink action="editProduct" actionListener="#{productController.findProductById(lists.productId)}" value="Edit">
<fcore:param name="id" value="#{lists.productId}"/>
</h:commandLink>
</h:column>
<h:column>
<fcore:facet name="header">Delete</fcore:facet>
<h:commandLink action="index" actionListener="#{productController.deleteCategory(lists.productId)}" onclick="return confirm('Are You Sure ?')" value="Delete">
<fcore:param name="id" value="#{lists.productId}"/>
</h:commandLink>
</h:column>
</h:dataTable>
<h:commandLink value="Add New Product" action="addProduct" />
</h:form>
</fcore:view>
</center>
</h:body>
</html>
here is the java bean along with getters and setters.
ProductManagedBean.java
#ManagedBean
#RequestScoped
public class ProductManagedBean {
private int productId;
private String productName;
private double productPrice;
private int productQty;
private String productDesc;
private Date purchaseDate;
//getters and setter here ...
}
here is the controller for fetching the values. The selected productId's value gets printed in console but not in the jsf form.
#ManagedBean(name = "productController")
public class ProductController {
public ProductManagedBean findProductById(int productId) {
ProductManagedBean productManagedBean = new ProductManagedBean();
String query = "SELECT * FROM product WHERE proId = ?";
try {
DbConnection.DbDriver();
pstat = DbConnection.con.prepareStatement(query);
pstat.setInt(1, productId);
resultSet = pstat.executeQuery();
System.out.println("\n--- Product Id = " + productId);
while (resultSet.next()) {
productManagedBean.setProductId(resultSet.getInt("proId"));
productManagedBean.setProductName(resultSet.getString("proName"));
productManagedBean.setProductPrice(resultSet.getDouble("proPrice"));
productManagedBean.setProductQty(resultSet.getInt("proQty"));
productManagedBean.setProductDesc(resultSet.getString("proDesc"));
productManagedBean.setPurchaseDate(resultSet.getDate("proDate"));
System.out.println(productManagedBean.getProductId() + "\t" + productManagedBean.getProductName()
+ "\t" + productManagedBean.getProductPrice() + "\t" + productManagedBean.getProductQty()
+ "\t" + productManagedBean.getProductDesc() + "\t" + productManagedBean.getPurchaseDate());
}
} catch (SQLException ex) {
Logger.getLogger(ProductController.class.getName()).log(Level.SEVERE, null, ex);
}
public void update(ProductManagedBean productManagedBean) {
String query = "UPDATE product SET proName = ?, proPrice = ?, proQty = ?, proDesc = ?, proDate = ? "
+ "WHERE proId = ?";
try {
DbConnection.DbDriver();
pstat = DbConnection.con.prepareStatement(query);
pstat.setString(1, productManagedBean.getProductName());
pstat.setDouble(2, productManagedBean.getProductPrice());
pstat.setInt(3, productManagedBean.getProductQty());
pstat.setString(4, productManagedBean.getProductDesc());
pstat.setDate(5, new Date(productManagedBean.getPurchaseDate().getTime()));
pstat.setInt(6, productManagedBean.getProductId());
int save = pstat.executeUpdate();
if (save > 0) {
System.out.println("\n\n---- New Product Saved ---- " + productManagedBean.getProductName() + " --- \n");
}
} catch (SQLException ex) {
Logger.getLogger(ProductController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
here is the editProduct.xhtml page
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:fcore="http://java.sun.com/jsf/core">
<h:head>
<title>Update Product</title>
</h:head>
<h:body>
<center>
<fcore:view>
<h:form>
<h:panelGrid border="1" cellpadding="10" columns="2">
<h:outputLabel value="Product Id"/>
<h:inputText value="#{productManagedBean.productId}" >
</h:inputText>
<h:outputLabel value="Product Name"/>
<h:inputText value="#{productManagedBean.productName}" required="true">
</h:inputText>
<h:outputLabel value="Product Price"/>
<h:inputText value="#{productManagedBean.productPrice}" required="true">
</h:inputText>
<h:outputLabel value="Product Qty"/>
<h:inputText value="#{productManagedBean.productQty}" required="true">
</h:inputText>
<h:outputLabel value="Product Desc"/>
<h:inputText value="#{productManagedBean.productDesc}" required="true">
</h:inputText>
<h:outputLabel value="Product Date"/>
<h:inputText value="#{productManagedBean.purchaseDate}" required="true">
<f:convertDateTime pattern="yyyy-MM-dd"/>
</h:inputText>
<h:commandLink value="Update" action="index" actionListener="#{productController.update(productManagedBean)}" />
</h:panelGrid>
</h:form>
</fcore:view>
</center>
</h:body>
here is web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
The ProductManagedBean must be SessionScop to load the values on the editProduct.xhtml.
In my jsf page there are search and insert functions.
However after I start insert process, I can start search process.
So I have to do firstly insert to search person otherwise search button doesn't work how can I solve this problem ?
public void search() {
getOsList(getUsername(), getSurname(), getTcidno());
System.out.println("osList : " + osList);
}
public List<KisiBean> getOsList(String ad, String soyad, String tckimlikno) {
Session session = null;
Transaction tx = null;
List<KisiBean> osList = new ArrayList<KisiBean>();
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
String sql = "select upper(k.ad),upper(k.soyad),k.temelkimlik.mernisno "
+ "from com.revir.domain.Kisi as k "
+ "where k.kisituru.kisiturid in (1,9,29,30)";
if (!ad.isEmpty()) {
sql = sql + " AND ((upper(ltrim(rtrim(k.ad))) like upper(:ad))"
+ " OR "
+ " (lower(ltrim(rtrim(k.ad))) like lower(:ad)))";
}
if (!soyad.isEmpty()) {
sql = sql
+ " AND ((upper(ltrim(rtrim(k.soyad))) like upper(:soyad))"
+ " OR "
+ " (lower(ltrim(rtrim(k.soyad))) like lower(:soyad)))";
}
if (!tckimlikno.isEmpty()) {
sql = sql
+ " AND upper(k.temelkimlik.mernisno) like upper(:mernisno) ";
}
sql = sql
+ " order by NLSSORT(lower(k.soyad),'nls_sort=xturkish') asc,"
+ "NLSSORT(lower(k.ad),'nls_sort=xturkish') asc ";
try {
Query queryObject = session.createQuery(sql).setMaxResults(100);
if (!ad.isEmpty())
queryObject.setString("ad", "%" + ad.trim() + "%");
if (!soyad.isEmpty())
queryObject.setString("soyad", "%" + soyad.trim() + "%");
if (!tckimlikno.isEmpty())
queryObject
.setString("mernisno", "%" + tckimlikno.trim() + "%");
System.out.println("SQL : " + sql);
List list = queryObject.list();
Object[] o;
for (Iterator it = list.iterator(); it.hasNext();) {
o = (Object[]) it.next();
KisiBean osBean = new KisiBean();
if (o[0] != null) {
osBean.setAd((String) o[0].toString().trim());
System.out.println("Ad : "
+ (String) o[0].toString().trim());
}
if (o[1] != null) {
osBean.setSoyad((String) o[1].toString().trim());
System.out.println("Soyad : "
+ (String) o[1].toString().trim());
}
if (o[2] != null) {
osBean.setMernisno((String) o[2].toString());
System.out.println("Kimlik No : "
+ (String) o[2].toString());
}
System.out
.println("----------------------------------------------");
osList.add(osBean);
}
tx.commit();
log.debug("KisiInfoProcess - getStudentList - End DAO and Process Work");
} catch (Exception e) {
log.error("KisiInfoProcess - getStudentList - Error");
tx.rollback();
throw e;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
log.debug("KisiInfoProcess - getStudentList - End / Returning");
return osList;
}
public void savePerson() {
saveOsList(getPusername(), getPsurname(), getPtcidno(),
getPdogumtarihi(), getPcinsiyet());
System.out.println("saveperson" + " - " + getPusername() + " - "
+ getPsurname() + " - " + getPtcidno() + " - "
+ getPdogumtarihi() + " - " + getPcinsiyet());
}
public void saveOsList(String ad, String soyad, String tcno,
Date dogumtarihi, char cinsiyet) {
System.out.println("saveOSList");
Session session = null;
Transaction tx = null;
try {
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
TrvrKisi tkisi = new TrvrKisi();
TrvrKisiDAO tkisiDAO = new TrvrKisiDAO();
tkisi.setAd(ad);
tkisi.setSoyad(soyad);
tkisi.setTcno(tcno);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";
dogumtarihi = formatter.parse(dateInString);
System.out.println(dogumtarihi);
System.out.println(formatter.format(dogumtarihi));
tkisi.setDogumtarihi(dogumtarihi);
tkisi.setCinsiyet(cinsiyet);
tkisiDAO.save(tkisi);
tx.commit();
log.debug("KisiInfoProcess - getStudentList - End DAO and Process Work");
} catch (Exception e) {
log.error("KisiInfoProcess - getStudentList - Error");
tx.rollback();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
log.debug("KisiInfoProcess - getStudentList - End / Returning");
}
layout.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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:form id="form">
<h:head>
<f:facet name="first">
<meta http-equiv="X-UA-Compatible" content="EmulateIE8" />
<meta content='text/html; charset=UTF-8' http-equiv="Content-Type" />
<title>REVİR HASTA KAYIT</title>
</f:facet>
<link type="text/css" rel="stylesheet"
href="#{request.contextPath}/css/default.css" />
<style type="text/css">
.ui-layout-north {
z-index: 20 !important;
overflow: visible !important;;
}
.ui-layout-north .ui-layout-unit-content {
overflow: visible !important;
}
</style>
</h:head>
<h:body>
<p:layout fullPage="true">
<p:layoutUnit position="north">
<p:layout>
<p:layoutUnit position="north">
<h:outputText value="Middle top unit content." />
</p:layoutUnit>
<p:layoutUnit position="south">
<p:layout>
<p:layoutUnit position="north">
<p:menubar>
<p:submenu label="Duyurular" outcome="duyurular.xhtml"></p:submenu>
<p:submenu label="Hasta Arama" url="#"></p:submenu>
</p:menubar>
</p:layoutUnit>
<p:layoutUnit position="center" size="200">
<ui:include src="/search.xhtml" />
</p:layoutUnit>
</p:layout>
</p:layoutUnit>
<p:layoutUnit position="west">
<h:outputText value="Middle left unit content." />
</p:layoutUnit>
<p:layoutUnit position="east">
<h:panelGrid columns="1">
<h:outputText value="Hoşgeldin #{loginBean.username}"></h:outputText>
<h:outputLink
value="#{request.contextPath}/j_spring_security_logout">Oturumu Kapat</h:outputLink>
</h:panelGrid>
</p:layoutUnit>
<p:layoutUnit position="center">
<h:outputText value="REVİR HASTA OTOMASYON SİSTEMİ" />
</p:layoutUnit>
</p:layout>
</p:layoutUnit>
<p:layoutUnit position="south" size="50">
<h:outputText value="South unit content." />
</p:layoutUnit>
<p:layoutUnit position="west" size="900">
<ui:include src="/searchresults.xhtml" />
</p:layoutUnit>
<p:layoutUnit position="center">
</p:layoutUnit>
</p:layout>
</h:body>
<p:dialog id="modalDialog" header="Yeni Hasta Kayıt" widgetVar="dlg2"
modal="true" height="300" width="300">
<p:panel id="panel">
<p:messages id="messages" />
<h:panelGrid columns="2" columnClasses="column1">
<h:outputText value="Ad: *" />
<p:inputText id="username" value="#{userOS.pusername}"
required="true" label="Ad">
<f:validateLength minimum="2" />
</p:inputText>
<br />
<p:message for="username" />
<h:outputText value="Soyad: *" />
<p:inputText id="surname" value="#{userOS.psurname}"
required="true" label="Soyad" />
<br />
<p:message for="surname" />
<h:outputText value="TC Kimlik: *" />
<p:inputText id="tcidno2" value="#{userOS.ptcidno}" required="true"
label="TC Kimlik" />
<br />
<p:message for="tcidno" />
<h:outputText value="Doğum Tarihi:" />
<p:inputMask value="#{userOS.pdogumtarihi}" mask="99/99/9999" />
<h:outputText value="Cinsiyet: " />
<p:selectOneRadio id="options" value="#{userOS.pcinsiyet}">
<f:selectItem itemLabel="Erkek" itemValue="E" />
<f:selectItem itemLabel="Kadın" itemValue="K" />
<br></br>
</p:selectOneRadio>
</h:panelGrid>
</p:panel>
<p:commandButton value="Ekle" id="ajax"
actionListener="#{userOS.savePerson}" />
</p:dialog>
</h:form>
</f:view>
</html>
search.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"
xmlns:ui="http://java.sun.com/jsf/facelets">
<body>
<ui:composition>
<p:panel header="Arama" style="margin-bottom:10px;">
<h:panelGrid columns="2">
<h:outputText value="Ad : "></h:outputText>
<p:inputText id="ad" value="#{userOS.username}" label="Keyword" />
<h:outputText value="Soyad : "></h:outputText>
<p:inputText id="soyad" value="#{userOS.surname}" label="Keyword" />
<h:outputText value="TC Kimlik no : "></h:outputText>
<p:inputText id="tcidno" value="#{userOS.tcidno}" label="Keyword" />
<p:watermark for="ad" value="Ad giriniz" />
<p:watermark for="soyad" value="Soyad giriniz" />
<p:watermark for="tcidno" value="TC Kimlik no giriniz" />
<p:commandButton actionListener="#{userOS.search}" value="Arama"
update=":form:users" />
</h:panelGrid>
</p:panel>
</ui:composition>
</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_3_0.xsd"
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">
<display-name>Revir Kayit</display-name>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/css/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml,
/WEB-INF/applicationContext.xml,
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Production</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>casablanca</param-value>
</context-param>
<welcome-file-list>
<welcome-file>login.jsf</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
<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>
<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>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<resource-ref>
<description>REVIR DB Connection</description>
<res-ref-name>jdbc/REVIR</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
I develop a java application with jsf and eclispeLink with netbeans 7.3.1 but my character don't save correctly. I look at request variable and saw that my character are not correctly show in the request object.
My Jsf sample :
<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">
<ui:composition template="/template.xhtml">
<ui:define name="title">
<h:outputText value="#{bundle.CreateTblAccessTitle}"></h:outputText>
</ui:define>
<ui:define name="body">
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
</h:panelGroup>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="#{bundle.CreateTblAccessLabel_id}" for="id" />
<h:inputText id="id" value="#{tblAccessController.selected.id}" title="#{bundle.CreateTblAccessTitle_id}" required="true" requiredMessage="#{bundle.CreateTblAccessRequiredMessage_id}"/>
<h:outputLabel value="#{bundle.CreateTblAccessLabel_userName}" for="userName" />
<h:inputText id="userName" value="#{tblAccessController.selected.userName}" title="#{bundle.CreateTblAccessTitle_userName}" />
<h:outputLabel value="#{bundle.CreateTblAccessLabel_userTypeId}" for="userTypeId" />
<h:selectOneMenu id="userTypeId" value="#{tblAccessController.selected.userTypeId}" title="#{bundle.CreateTblAccessTitle_userTypeId}" >
<f:selectItems value="#{tblUserTypeController.itemsAvailableSelectOne}"/>
</h:selectOneMenu>
<h:outputLabel value="#{bundle.CreateTblAccessLabel_formId}" for="formId" />
<h:selectOneMenu id="formId" value="#{tblAccessController.selected.formId}" title="#{bundle.CreateTblAccessTitle_formId}" required="true" requiredMessage="#{bundle.CreateTblAccessRequiredMessage_formId}">
<f:selectItems value="#{tblFormController.itemsAvailableSelectOne}"/>
</h:selectOneMenu>
<h:outputLabel value="#{bundle.CreateTblAccessLabel_activitesId}" for="activitesId" />
<h:selectOneMenu id="activitesId" value="#{tblAccessController.selected.activitesId}" title="#{bundle.CreateTblAccessTitle_activitesId}" required="true" requiredMessage="#{bundle.CreateTblAccessRequiredMessage_activitesId}">
<f:selectItems value="#{tblAccessActivitiesController.itemsAvailableSelectOne}"/>
</h:selectOneMenu>
</h:panelGrid>
<br />
<h:commandLink action="#{tblAccessController.create}" value="#{bundle.CreateTblAccessSaveLink}" />
<br />
<br />
<h:commandLink action="#{tblAccessController.prepareList}" value="#{bundle.CreateTblAccessShowAllLink}" immediate="true"/>
<br />
<br />
<h:link outcome="/index" value="#{bundle.CreateTblAccessIndexLink}"/>
</h:form>
</ui:define>
</ui:composition>
</html>
MY Filter to change encoding :
public class EncodingFilter implements Filter{
private String encoding;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
encoding = filterConfig.getInitParameter("requestEncoding");
if( encoding==null ) encoding="UTF-8";
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.setCharacterEncoding(encoding);
httpResponse.setCharacterEncoding(encoding);
response.setContentType("text/html;charset=utf-8");
chain.doFilter(httpRequest, httpResponse);
}
#Override
public void destroy() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
My Template.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><ui:insert name="title">Default Title</ui:insert></title>
<h:outputStylesheet name="css/jsfcrud.css"/>
</h:head>
<h:body>
<h1>
<ui:insert name="title">Default Title</ui:insert>
</h1>
<p>
<ui:insert name="body">Default Body</ui:insert>
</p>
</h:body>
</html>
My web.xml
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>business.EncodingFilter</filter-class>
<init-param>
<param-name>requestEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<jsp-config>
<jsp-property-group>
<url-pattern>*.xhtml</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
</web-app>
what is the problem? how could i solve it?
Every things look fine! You should check the following:
a) Check whether your Glassfish Resources has following inside :
<property name="useUnicode" value="true"/>
<property name="characterEncoding" value="UTF8"/>
b) Whether your database and the table are UTF-8 CHARCTER SET
for mysql use following code:
ALTER DATABASE dbname DEFAULT CHARACTER SET utf8;
USE dbname;
ALTER TABLE tblname CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
This question already has answers here:
How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable
(11 answers)
Closed 7 years ago.
I searched and tried every example on web that i found but my example still doesn't work.
My web.xml
...(headers)
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<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>
<listener>
<listener-class>registration.cleanRegisterDB</listener-class>
</listener>
<listener>
<listener-class>main.poolChecker</listener-class>
</listener>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
<listener>
<listener-class>Utils.SessionAtributeListener.MyAtributeListener</listener-class>
</listener>
<context-param>
<param-name>primefaces.PRIVATE_CAPTCHA_KEY</param-name>
<param-value>...</param-value>
</context-param>
<context-param>
<param-name>primefaces.PUBLIC_CAPTCHA_KEY</param-name>
<param-value>...</param-value>
</context-param>
<error-page>
<error-code>404</error-code>
<location>/faces/404.xhtml</location>
</error-page>
My xhtml page:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
lang="#{main_bean.authLang()}"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<f:view locale="#{main_bean.locale}" encoding="ISO-8859-1" >
<h:head>
<h:outputStylesheet library="theme1" name="css/style.css"/>
<h:outputScript library="theme1" name="js/jquery.validate.js"/>
</h:head>
<h:body>
<f:event type="preRenderComponent" listener="#{postbean.loadMasterCategories()}" ></f:event>
<h:panelGroup id="layout-for-image" layout="block">
<h:link outcome="index.xhtml?faces-redirect=true">
<h:graphicImage name="theme1/images/logo.png" />
</h:link>
</h:panelGroup>
<h:panelGroup class="layout-titles" layout="block">
<h2>#{msg.postInt}</h2>
</h:panelGroup>
<h:form id="formPostpool" enctype="multipart/form-data" >
<p:growl id="growlaa" autoUpdate="true"/>
<p:confirmDialog id="confirmDialog" message="#{msg.dialogConfPostInt}"
header="#{msg.confirmDialogHeader}" severity="alert" widgetVar="confirmation" >
<h:panelGroup id="dialog-captcha-layout" layout="block" >
<h:panelGroup layout="block" style="display: inline-block; *display: inline; zoom: 1;">
<p:captcha label="Captcha" validatorMessage="#{msg.invalidCaptcha}" required="true" requiredMessage="#{msg.CaptchaNull}" language="#{main_bean.authLang()}"/>
</h:panelGroup>
</h:panelGroup>
<p:commandButton id="confirm" styleClass="h-button-search" icon="iconDialogYes" actionListener="#{captchaBean.submit}"
action="index" ajax="false" onclick="confirmation.hide();" style="background-image: url('../resources/theme1/images/icons/yes.png')" >
<f:actionListener binding="#{postbean.publicatePool()}" />
</p:commandButton>
<p:commandButton id="notconfirm" styleClass="h-button-search" icon="iconDialogNo"
ajax="false" type="button" onclick="confirmation.hide();"/>
</p:confirmDialog>
<h:panelGroup class="layout-item-details" layout="block">
<h2>#{msg.infoProd}</h2>
<h:panelGroup class="details-element" layout="block">
<h:outputLabel value="#{msg.categoryPost}" for="cat"/>
<h:panelGroup class="element-inputs" layout="block">
<p:selectOneListbox style="height: 150px;" id="cat" value="#{postbean.masterCategoria}" converter="omnifaces.SelectItemsConverter" required="true" requiredMessage="#{msg.message_radiobutton_choose}">
<f:selectItems value="#{postbean.categorias}" var="cat" itemLabel="#{cat.descricao}" itemValue="#{cat}" />
</p:selectOneListbox>
</h:panelGroup>
</h:panelGroup>
<h:panelGroup class="details-element" layout="block">
<h:panelGroup class="element-labels" layout="block">
<h:outputLabel value="#{msg.titlePost}" for="titulo"/>
</h:panelGroup>
<h:panelGroup layout="block">
<p:inputText id="titulo" value="#{postbean.titulo}" styleClass="inputs-login" required="true" requiredMessage="#{msg.message_titulo_null}"/>
</h:panelGroup>
</h:panelGroup>
<h:panelGroup class="details-element" layout="block">
<h:panelGroup class="element-labels" layout="block">
<h:outputLabel value="#{msg.descricaoPost}" for="desc"/>
</h:panelGroup>
<h:panelGroup layout="block">
<p:inputTextarea id="desc" value="#{postbean.descricao}" rows="6" cols="70" styleClass="inputs-textarea" required="true" requiredMessage="#{msg.message_descricao_null}"/>
</h:panelGroup>
</h:panelGroup>
<h:panelGroup class="details-element" layout="block">
<h:panelGroup class="element-labels" layout="block">
<h:outputLabel value="#{msg.marcaPost}" for="marca"/>
</h:panelGroup>
<h:panelGroup layout="block">
<p:inputText id="marca" value="#{postbean.marca}" styleClass="inputs-login" />
</h:panelGroup>
</h:panelGroup>
<h:panelGroup class="details-element" layout="block">
<h:panelGroup class="element-labels" layout="block">
<h:outputLabel value="#{msg.modeloPost}" for="Modelo"/>
</h:panelGroup>
<h:panelGroup layout="block">
<p:inputText id="Modelo" value="#{postbean.modelo}" styleClass="inputs-login" />
</h:panelGroup>
</h:panelGroup>
<h:panelGroup class="details-element" layout="block">
<h:panelGroup class="element-labels" layout="block">
<h:outputLabel value="#{msg.quantidadePost}" for="qtdDesejada"/>
</h:panelGroup>
<h:panelGroup layout="block">
<p:inputText id="qtdDesejada" value="#{postbean.quantidadePretendida}" styleClass="inputs-login" style="width: 100px !important;" required="true" requiredMessage="#{msg.message_quantidade_null}" validatorMessage="#{msg.message_quantidade_invalid}">
<f:validateDoubleRange minimum="0.00000001" />
<!--<f:validateRegex pattern="([1-9][0-9]*\.?[0-9]*)" for="qtdDesejada" />-->
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<h:panelGroup class="details-element" layout="block">
<h:panelGroup class="element-labels" layout="block">
<h:outputLabel value="#{msg.precoTargetPost}" for="precoTarget"/>
</h:panelGroup>
<h:panelGroup layout="block">
<p:inputText id="precoTarget" value="#{postbean.preco}" styleClass="inputs-login" style="width: 100px !important;" required="true" requiredMessage="#{msg.message_precoTarget_null}" validatorMessage="#{msg.message_precoTarget_invalid}">
<f:validateDoubleRange minimum="0.00000001" />
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<h:panelGroup class="details-element" layout="block">
<h:panelGroup class="element-labels" layout="block">
<h:outputLabel value="#{msg.fotosPost}" for="foto"/>
</h:panelGroup>
<!-- <h:panelGroup layout="block" style="display: inline-block; *display: inline; zoom: 1;" id="addFotoPanel">
<h:inputFile id="idinputFile" value="#{postbean.file}" />
</h:panelGroup>-->
<p:fileUpload value="#{postbean.upfile}" auto="true" fileUploadListener="#{postbean.handleFileUpload}" widgetVar="asd" />
</h:panelGroup>
<h:panelGroup class="details-element" layout="block" style="margin-bottom: 15px; width: 250px; padding-left: 175px;">
<p:commandButton id="btn" value="#{msg.label_buttonsubmit}" styleClass="h-button-search" onclick="confirmation.show();"/>
</h:panelGroup>
</h:panelGroup>
<script type="text/javascript">
$(document).ready(function() {
$('#formPostpool').keypress(function(e) {
if (e.keyCode == 13) {
event.preventDefault();
$("#btn").click();
}
})
});
</script>
</h:form>
</h:body>
</f:view>
And the bean:
//...some imports
#ManagedBean(name = "postbean")
#ViewScoped
public class postbean implements Serializable {
//////////////////////////////////
// FACADES
/////////////////////////////////
#EJB
ProdutoFacade produtofacade = new ProdutoFacade();
#EJB
UsersFacade userfacade = new UsersFacade();
#EJB
ImageFacade imagefacade = new ImageFacade();
#EJB
categoriasFacade categoriafacade = new categoriasFacade();
#EJB
buyerPoolFacade buyerPoolFacade = new buyerPoolFacade();
#EJB
LanguageFacade languageFacade = new LanguageFacade();
#EJB
Lingua_ProdutoFacade langProFacade = new Lingua_ProdutoFacade();
#EJB
MessagesFacade messagesFacade = new MessagesFacade();
/////////////////////////////////////
// VARIAVEIS
////////////////////////////////////
//Destino onde vão ser guardadas as imagens relativas a pool
private String destination = "C:";
private List<String> urls;
private String titulo;
private String descricao;
private String marca;
private String modelo;
private float preco;
private short estado;
private int quantidadePretendida;
private List<categorias> categoria; // lista das categorias
private Timestamp dataActual;
private Users publicationUser;
private categorias masterCategoria;
private categorias option2;
private List<categorias> text;
private List<categorias> subcat2;
private boolean rend;
private boolean rend2;
private Part file;
private UploadedFile upfile;
public Part getFile() {
return file;
}
public void setFile(Part file) {
this.file = file;
}
public UploadedFile getUpfile() {
return upfile;
}
public void setUPfile(UploadedFile upfile) {
this.upfile = upfile;
}
public postbean() {...}
//...getters and setters
//...some methods
public void handleFileUpload(FileUploadEvent event) {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
FacesContext ctx = FacesContext.getCurrentInstance();
Locale l = ctx.getViewRoot().getLocale();
ResourceBundle rb = ResourceBundle.getBundle("languages.welcome", l);
FacesContext aFacesContext = FacesContext.getCurrentInstance();
ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
FacesMessage msg = new FacesMessage(rb.getString("Success"), event.getFile().getFileName() + rb.getString("wasUploaded"));
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (IOException e) {
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
String username = userfacade.findUserByIDSessao(FacesUtils.getSessionID());
OutputStream out = null;
try {
// write the inputStream to a FileOutputStream
File dir = new File(destination + username);
if (!dir.exists()) {
dir.mkdir();
}
File f = new File(dir + "\\" + fileName);
out = new FileOutputStream(f);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
urls.add(username + "//" + f.getName());
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
in.close();
out.flush();
out.close();
} catch (IOException ex) {
}
}
}
//..some methods
}
Well, I changed parameters, I removed the filter from web.xml file, I changed the bean... I know I've got to have a "multipart/form-data" form, a filter in web.xml file and a fileUploader to receive the event in the bean. However nothing is triggered. I click to choose and then to upload (if parameter is not auto="true") and nothing happens. I do have commons-io-2.4, commons-fileupload-1.3, primefaces-3.5 and I use GlassFish Server 4.
Thank you!
**Note:if you are using Spring-web-flow then it will work**
My web.xml file
*Add this Configuration in web.xml file**
<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>Spring MVC Dispatcher Servlet</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet- class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet- name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
Fileupload.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<p:fileUpload id="image"
fileUploadListener="#{loadFileForm.handleFileUpload}"
mode="advanced" dragDropSupport="true" multiple="true"
update="messages" sizeLimit="100000" fileLimit="3"
allowTypes="/(\.|\/)(xls)$/" />
<p:growl id="messages" showDetail="true" />
</html>
LoadFileBean.java
#ManagedBean(name = "loadFileForm")
public class LoadFileFormBean implements Serializable {
/**
* handleFileUpload
* #param event
*/
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile()
.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
I haven't tried GlassFish but found that using PrimeFaces 4 on WebLogic we had to add this parameter to the web.xml:
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
We're using this Maven dependency:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
We also had to make sure that the PrimeFaces FileUpload Filter was the first filter entry in the web.xml. But it looks like yours is already.
Also, the file upload should have a form of its own.
Im trying to test a sample JSF project but for some reason the command button are not being displayed that is given in the below page,
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h2>Implicit Navigation</h2>
<hr />
<h:form>
<h3>Using Managed Bean</h3>
<h:commandButton action="#{navigationController.moveToPage1}"
value="Page1" />
<h3>Using JSF outcome</h3>
<h:commandButton action="page2" value="Page2" />
</h:form>
<br/>
<h2>Conditional Navigation</h2>
<hr />
<h:form>
<h:commandLink action="#{navigationController.showPage}"
value="Page1">
<f:param name="pageId" value="1" />
</h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Page2">
<f:param name="pageId" value="2" />
</h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Home">
<f:param name="pageId" value="3" />
</h:commandLink>
</h:form>
<br/>
<h2>"From Action" Navigation</h2>
<hr />
<h:form>
<h:commandLink action="#{navigationController.processPage1}"
value="Page1" />
<h:commandLink action="#{navigationController.processPage2}"
value="Page2" />
</h:form>
<br/>
<h2>Forward vs Redirection Navigation</h2>
<hr />
<h:form>
<h3>Forward</h3>
<h:commandButton action="page1" value="Page1" />
<h3>Redirect</h3>
<h:commandButton action="page1?faces-redirect=true"
value="Page1" />
</h:form>
</h:body>
</html>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web 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.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtm</url-pattern>
</servlet-mapping>
</web-app>
faces.config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
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-facesconfig_2_0.xsd"
version="2.0">
<navigation-rule>
<from-view-id>home.xhtml</from-view-id>
<navigation-case>
<from-action>#{navigationController.processPage1}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page1.jsf</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{navigationController.processPage2}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page2.jsf</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
view source html file
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h2>Implicit Navigation</h2>
<hr />
<h:form>
<h3>Using Managed Bean</h3>
<h:commandButton action="#{navigationController.moveToPage1}"
value="Page1" />
<h3>Using JSF outcome</h3>
<h:commandButton action="page2" value="Page2" />
</h:form>
<br/>
<h2>Conditional Navigation</h2>
<hr />
<h:form>
<h:commandLink action="#{navigationController.showPage}"
value="Page1">
<f:param name="pageId" value="1" />
</h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Page2">
<f:param name="pageId" value="2" />
</h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Home">
<f:param name="pageId" value="3" />
</h:commandLink>
</h:form>
<br/>
<h2>"From Action" Navigation</h2>
<hr />
<h:form>
<h:commandLink action="#{navigationController.processPage1}"
value="Page1" />
<h:commandLink action="#{navigationController.processPage2}"
value="Page2" />
</h:form>
<br/>
<h2>Forward vs Redirection Navigation</h2>
<hr />
<h:form>
<h3>Forward</h3>
<h:commandButton action="page1" value="Page1" />
<h3>Redirect</h3>
<h:commandButton action="page1?faces-redirect=true"
value="Page1" />
</h:form>
</h:body>
</html>
Navigationcontroller
package com.tutorialspoint.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
#ManagedBean(name = "navigationController", eager = true)
#RequestScoped
public class NavigationController implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty(value="#{param.pageId}")
private String pageId;
public String moveToPage1(){
return "page1";
}
public String moveToPage2(){
return "page2";
}
public String moveToHomePage(){
return "home";
}
public String processPage1(){
return "page";
}
public String processPage2(){
return "page";
}
public String showPage(){
if(pageId == null){
return "home";
}
if(pageId.equals("1")){
return "page1";
}else if(pageId.equals("2")){
return "page2";
}else{
return "home";
}
}
public String getPageId() {
return pageId;
}
public void setPageId(String pageId) {
this.pageId = pageId;
}
}
page1.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">
<h:body>
<h2>This is Page1</h2>
<h:form>
<h:commandButton action="home?faces-redirect=true"
value="Back To Home Page" />
</h:form>
</h:body>
</html>
page2.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">
<h:body>
<h2>This is Page2</h2>
<h:form>
<h:commandButton action="home?faces-redirect=true"
value="Back To Home Page" />
</h:form>
</h:body>
</html>
It's already been answered above, but I'll be specific. In your web.xml the <url-pattern> is specified as *.xhtm and your jsf files have a .xhtml extension. Note the missing letter in the pattern specification. Because of that your files aren't recognized and routed through the faces servlet. Just add the 'l' to the url-pattern in the web.xml and it should start working.