JSF : java.lang.IllegalArgumentException: can't parse argument number - jsf

Can someone help me figure out the problem i'm new on JSF. I have built a Spring WebMVC App with Primefaces. This app contains a list of nodes which can be dragged into the spreadSheet (I m working with SpreadJS). Behind each node there is a model and a bean. Evey node has a name and an input type. I need to do the synchronization between the node value and its value in the spreadSheet and aim-versa. So in every changeEvent i call a remoteCommand and i pass five parameters to my managedBean. The problem is whenever i load my page and i get this error : here is my code :
#ManagedBean
#SessionScoped
public class HelloBean implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty("#{param.nodeId}")
private String nodeId;
#ManagedProperty("#{param.paramId}")
private String paramId;
#ManagedProperty("#{param.row}")
private int row;
#ManagedProperty("#{param.cel}")
private int cel;
#ManagedProperty("#{param.value}")
private String value;
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public String getParamId() {
return paramId;
}
public void setParamId(String paramId) {
this.paramId = paramId;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getCel() {
return cel;
}
public void setCel(int cel) {
this.cel = cel;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void execCmd() {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String nodeId = params.get("nodeId");
}
and my xhtml file look like :
<h:body>
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<h:form id="myForm">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Test Submit Value</label>
<h:inputText name="text1" id="text1" value="#{helloBean.value}" >
</h:inputText>
</div>
</div>
<p:remoteCommand name="callRemoteMethod" actionListener="#{helloBean.execCmd()}" />
</h:form>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div name="right_frame" id="ss" style="height: 600px; width: 100%;"></div>
</div>
</div>
</div>
<h:form>
<br />
</h:form>
</h:body>
<script type="text/javascript">
var nodeId = null;
var paramId = null;
var row = null;
var cell= null;
var value = null;
var spread;
window.onload = function() {
spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
var sheet = spread.getActiveSheet();
sheet.setValue(0, 1, 123, GC.Spread.Sheets.SheetArea.viewport);
sheet.bind(GC.Spread.Sheets.Events.CellChanged , function (e, args) {
if (args.propertyName === "value") {
if(sheet.getTag(0,1) != null){
var obj = JSON.parse(sheet.getTag(0,1));
nodeId = obj.nodeId;
paramId = obj.paramId;
row = args.row;
cell = args.col;
callRemoteMethod({name: 'nodeId', value: ""}, {name: 'paramId', value: ""}, {name: 'row', value: 1}, {name: 'cel', value: 1}, {name: 'value', value: "Test"}]);
}
}
});
};
</script>
</html>
and this is the Stack Trace :
Caused by: java.lang.IllegalArgumentException: can't parse argument number: param.nodeId
at java.text.MessageFormat.makeFormat(MessageFormat.java:1420)
at java.text.MessageFormat.applyPattern(MessageFormat.java:479)
at java.text.MessageFormat.<init>(MessageFormat.java:363)
at java.text.MessageFormat.format(MessageFormat.java:835)
at com.sun.faces.util.MessageUtils.getExceptionMessageString(MessageUtils.java:396)
at com.sun.faces.mgbean.BeanBuilder$Expression.validateLifespan(BeanBuilder.java:604)
at com.sun.faces.mgbean.BeanBuilder$Expression.<init>(BeanBuilder.java:553)
at com.sun.faces.mgbean.ManagedBeanBuilder.bakeBeanProperty(ManagedBeanBuilder.java:363)
at com.sun.faces.mgbean.ManagedBeanBuilder.bake(ManagedBeanBuilder.java:107)
... 49 more
Caused by: java.lang.NumberFormatException: For input string: "param.nodeId"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at java.text.MessageFormat.makeFormat(MessageFormat.java:1418)
... 57 more
any help ??

You are setting a value of an Integer to a String variable as the exception says
java.lang.NumberFormatException: For input string: "param.nodeId"
The nodeId variable should be an Integer variable .
OR
You can parse the Integer value using toString() method

Instead of #ManagedProperty ("# {param.nodeId}"), I made #ManagedProperty ("# {nodeId}") and it works:
#ManagedProperty("#{nodeId}")
private String nodeId;
#ManagedProperty("#{paramId}")
private String paramId;
#ManagedProperty("#{row}")
private int row;
#ManagedProperty("#{cel}")
private int cel;
#ManagedProperty("#{value}")
private String value;

Related

How to refresh ViewScoped(Omnifaces) page on data change?

I have some Category model, that is organized as adjacency list. So when i am adding new one, i format current list so it has viewable hierarchy. For this i use Omnifaces ViewScoped bean. Upon loading data i format it and display it in selectOneMenu. When i add new category that has parent to it i redirect to category list. If i open form page again it doesn't display new hierarchy but puts new category on the end as if it doesn't have parent. If i restart server for example and load page again it is displayed as it should.
So my question is how do i refresh it properly since obviouslu i am not doing it right.
form.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
template="#{adminConfig.templatePath}"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:define name="title">#{categoryFormMB.title}</ui:define>
<ui:define name="description"></ui:define>
<ui:define name="body">
<f:metadata>
<f:viewParam name="id" value="#{categoryFormMB.id}" converter="javax.faces.Long"/>
<f:event type="preRenderView" listener="#{categoryFormMB.initForm()}"/>
</f:metadata>
<div class="row">
<div class="col-md-6">
<p:panel styleClass="box box-primary">
<h:form styleClass="form-horizontal">
<div class="form-group ui-flat">
<p:outputLabel
for="name"
value="#{label.categoryName}"
styleClass="control-label col-md-4"/>
<div class="col-md-8">
<p:inputText
id="name"
value="#{categoryFormMB.category.name}"
styleClass="form-control"
required="true" />
</div>
</div>
<div class="form-group ui-flat">
<p:outputLabel
for="slug"
value="#{label.categorySlug}"
styleClass="control-label col-md-4"/>
<div class="col-md-8">
<p:inputText
id="slug"
value="#{categoryFormMB.category.slug}"
styleClass="form-control"
required="true" />
</div>
</div>
<div class="form-group ui-flat">
<p:outputLabel
for="parent"
value="#{label.parentCategory}"
styleClass="control-label col-md-4"/>
<div class="col-md-8">
<p:selectOneMenu
value="#{categoryFormMB.category.parent}"
id="parent"
converter="categoryConv">
<f:selectItem
itemLabel="#{label.noParent}"
itemValue=""/>
<f:selectItems
value="#{categoryFormMB.formattedList}"
var="category"
itemValue="#{category}"
itemLabel="#{category.name}"/>
</p:selectOneMenu>
</div>
</div>
<div class="form-group ui-flat">
<p:outputLabel
for="description"
value="#{label.categoryDescription}"
styleClass="control-label col-md-4"/>
<div class="col-md-8">
<p:inputTextarea
id="description"
value="#{categoryFormMB.category.description}"
styleClass="form-control"/>
</div>
</div>
<div class="form-group ui-flat">
<p:outputLabel
for="title-tag"
value="#{label.titleTag}"
styleClass="control-label col-md-4"/>
<div class="col-md-8">
<p:inputText
id="title-tag"
value="#{categoryFormMB.category.titleTag}"
styleClass="form-control"/>
</div>
</div>
<div class="form-group ui-flat">
<p:outputLabel
for="description-tag"
value="#{label.descriptionTag}"
styleClass="control-label col-md-4"/>
<div class="col-md-8">
<p:inputTextarea
id="description-tag"
value="#{categoryFormMB.category.descriptionTag}"
styleClass="form-control"/>
</div>
</div>
<div class="form-group">
<div class="col-md-4"></div>
<div class="col-md-8">
<div class="pull-right">
<p:commandButton
value="#{label.saveCategory}"
ajax="false"
rendered="#{ ! categoryFormMB.editing}"
action="#{categoryFormMB.save()}"
styleClass="btn btn-success btn-flat"
icon="fa fa-floppy-o"/>
<p:commandButton
value="#{label.updateCategory}"
ajax="false"
rendered="#{categoryFormMB.editing}"
action="#{categoryFormMB.update()}"
styleClass="btn btn-success btn-flat"
icon="fa fa-floppy-o"/>
<p:commandButton
value="#{label.cancel}"
action="#{categoryFormMB.close()}"
styleClass="btn btn-danger btn-flat"
ajax="false"
icon="fa fa-times"
immediate="true"/>
</div>
</div>
</div>
</h:form>
<p:messages
globalOnly="false"
showDetail="true"
showSummary="false"
showIcon="true" />
</p:panel>
</div>
</div>
</ui:define>
</ui:composition>
CategoryFormMB
package com.github.cvetan.bookstore.mb.category;
import static com.github.adminfaces.template.util.Assert.has;
import com.github.cvetan.bookstore.model.Category;
import com.github.cvetan.bookstore.sb.category.CategorySBLocal;
import com.github.cvetan.bookstore.util.Redirector;
import com.github.cvetan.bookstore.util.StringRepeater;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
/**
*
* #author cvetan
*/
#Named(value = "categoryFormMB")
#RequestScoped
public class CategoryFormMB {
#EJB
private CategorySBLocal categorySB;
private List<Category> list;
private List<Category> formattedList;
private String title;
private Integer id;
private boolean editing;
private Category category;
private String message;
/**
* Creates a new instance of CategoryFormMB
*/
public CategoryFormMB() {
}
public CategorySBLocal getCategorySB() {
return categorySB;
}
public void setCategorySB(CategorySBLocal categorySB) {
this.categorySB = categorySB;
}
public List<Category> getList() {
return list;
}
public void setList(List<Category> list) {
this.list = list;
}
public List<Category> getFormattedList() {
return formattedList;
}
public void setFormattedList(List<Category> formattedList) {
this.formattedList = formattedList;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public boolean isEditing() {
return editing;
}
public void setEditing(boolean editing) {
this.editing = editing;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void initForm() {
formattedList = new ArrayList<>();
getListFromDB();
formatList(list, 0);
if (has(id)) {
// TODO
} else {
title = "New category";
editing = false;
category = new Category();
message = "Category has been saved.";
}
}
private void getListFromDB() {
list = categorySB.getAll();
}
private void formatList(List<Category> list, int level) {
for (Category c: list) {
if (formattedList.contains(c)) {
continue;
}
c.setName(StringRepeater.repeat(" - ", level) + c.getName());
formattedList.add(c);
if ( ! c.getChildCategories().isEmpty()) {
formatList(c.getChildCategories(), level + 1);
}
}
}
public String save() {
try {
categorySB.save(category);
return Redirector.redirectWithInfo("Category has been saved.", "/admin/category-list.xhmtl?faces-redirect=true");
} catch (Exception ex) {
return Redirector.redirectWithError(ex.getMessage(), "/admin/category-form.xhtml?faces-redirect=true");
}
}
}
CategorySB(EJB)
package com.github.cvetan.bookstore.sb.category;
import com.github.cvetan.bookstore.model.Category;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author cvetan
*/
#Stateless
public class CategorySB implements CategorySBLocal {
#PersistenceContext (unitName = "BookstorePU")
private EntityManager entityManager;
#Override
public List<Category> getAll() {
return entityManager.createNamedQuery("Category.findAll").getResultList();
}
#Override
public void save(Category category) {
entityManager.persist(category);
}
#Override
public Category getById(int id) {
Query query = entityManager.createNamedQuery("Category.findById");
query.setParameter("id", id);
Category category = (Category) query.getSingleResult();
return category;
}
#Override
public void update(Category category) {
}
#Override
public void delete(int id) {
Category category = entityManager.find(Category.class, id);
entityManager.remove(category);
}
}
Category entity
package com.github.cvetan.bookstore.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author cvetan
*/
#Entity
#Table(name = "categories")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c")
, #NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id")
, #NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name = :name")
, #NamedQuery(name = "Category.findBySlug", query = "SELECT c FROM Category c WHERE c.slug = :slug")
, #NamedQuery(name = "Category.findByDescription", query = "SELECT c FROM Category c WHERE c.description = :description")
, #NamedQuery(name = "Category.findByTitleTag", query = "SELECT c FROM Category c WHERE c.titleTag = :titleTag")
, #NamedQuery(name = "Category.findByDescriptionTag", query = "SELECT c FROM Category c WHERE c.descriptionTag = :descriptionTag")
, #NamedQuery(name = "Category.findByCreatedAt", query = "SELECT c FROM Category c WHERE c.createdAt = :createdAt")
, #NamedQuery(name = "Category.findByUpdatedAt", query = "SELECT c FROM Category c WHERE c.updatedAt = :updatedAt")})
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "slug")
private String slug;
#Size(max = 255)
#Column(name = "description")
private String description;
#Size(max = 255)
#Column(name = "title_tag")
private String titleTag;
#Size(max = 255)
#Column(name = "description_tag")
private String descriptionTag;
#Basic(optional = false)
#NotNull
#Column(name = "created_at")
#Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
#Column(name = "updated_at")
#Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
#OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private List<Category> childCategories;
#JoinColumn(name = "parent", referencedColumnName = "id")
#ManyToOne
private Category parent;
public Category() {
}
public Category(Integer id) {
this.id = id;
}
public Category(Integer id, String name, String slug, Date createdAt) {
this.id = id;
this.name = name;
this.slug = slug;
this.createdAt = createdAt;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitleTag() {
return titleTag;
}
public void setTitleTag(String titleTag) {
this.titleTag = titleTag;
}
public String getDescriptionTag() {
return descriptionTag;
}
public void setDescriptionTag(String descriptionTag) {
this.descriptionTag = descriptionTag;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
#XmlTransient
public List<Category> getChildCategories() {
return childCategories;
}
public void setChildCategories(List<Category> childCategories) {
this.childCategories = childCategories;
}
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof Category)) {
return false;
}
Category other = (Category) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return name;
}
#PrePersist
public void setCreatedAt() {
createdAt = new Date();
}
#PreUpdate
public void setUpdatedAt() {
updatedAt = new Date();
}
}
There is caching on the JPA/EclipseLink side, which i didn't know. When i clear cache with: entityManager.getEntityManagerFactory().getCache().evictAll(); it refreshes data. So problem was not on the bean or it's scope.

Javascript alert in JSF

I have a method called bilgidorumu() in a managed bean class to check input. If there is a match with database (username and password), the application should go to the welcome page anasayfa.xhtml, else, it stays at the same page (index.xhtml). My problem is that I want to show an alert before staying on the same page (index.xhtml). So if there is no match for username/password, it should display an alert first, and stays then at index.xhtml. But I have no idea how to do that because Javascript runs on client side and Java code in server side. I have tried to display the alert with onclick event but it's not working:
<h:commandButton value="GİRİŞ" styleClass="button" action="#{kntrl.bilgidorumu()}" onclick="onBack()"/>
My input elements to reach via JS function:
<h:inputText id="username" value="#{kntrl.kulad}"
pt:placeholder="username" required="true"
requiredMessage="Kullanıcı adı girilmesi zorunlu"/> <h:inputSecret
id="pw" value="#{kntrl.kulsifre}" pt:placeholder="password"
required="true" requiredMessage="Şifre girilmesi zorunlu"/>
JS function:
function onBack(){
var kulad=document.getElementById("login-form:username").value;
var kulsifre=document.getElementById("login-form:pw").value;
alert(kulad+kulsifre);
}
index.xhtml:
<div class="login-page">
<div class="form">
<h:form class="register-form">
<h:inputText pt:placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p class="message">Already registered? Sign In</p>
</h:form>
<h:form class="login-form">
<h:inputText id="username" value="#{kntrl.kulad}" pt:placeholder="username" required="true" requiredMessage="Kullanıcı adı girilmesi zorunlu"/>
<h:message for="username" style="color: red"></h:message>
<h:inputSecret id="pw" value="#{kntrl.kulsifre}" pt:placeholder="password" required="true" requiredMessage="Şifre girilmesi zorunlu"/>
<h:message for="pw" style="color: red; " ></h:message>
<h:commandButton value="GİRİŞ" styleClass="button" action="#{kntrl.bilgidorumu()}" onclick="onBack()"/>
<p class="message">Not registered? Create an account</p>
</h:form>
</div>
</div>
<f:verbatim>
<script type="text/javascript">
function onBack(){
var kulad=document.getElementById("login-form:username").value;
var kulsifre=document.getElementById("login-form:pw").value;
alert(kulad+kulsifre);
}
</script>
</f:verbatim>
Managed bean:
#ManagedBean(name = "kntrl")
#RequestScoped
public class kontrolet {
private int id;
private String adsoyad;
private String birim;
private String bolum;
private String unvan;
private int puan;
private String kulad;
private String kulsifre;
public kontrolet() {
}
public String bilgidorumu() throws ScriptException {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/akademiktesvik", "root", "");
String query = "Select * from kisiler";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
if (rs.getString("kulad").equals(kulad) && rs.getString("kulsifre").equals(kulsifre)) {
return "anasayfa?faces-redirect=true";
}
}
} catch (Exception e) {
System.out.println("Baglanti kuurulmadı hata var" + e.getMessage());
}
return "index";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAdsoyad() {
return adsoyad;
}
public void setAdsoyad(String adsoyad) {
this.adsoyad = adsoyad;
}
public String getBirim() {
return birim;
}
public void setBirim(String birim) {
this.birim = birim;
}
public String getBolum() {
return bolum;
}
public void setBolum(String bolum) {
this.bolum = bolum;
}
public String getUnvan() {
return unvan;
}
public void setUnvan(String unvan) {
this.unvan = unvan;
}
public int getPuan() {
return puan;
}
public void setPuan(int puan) {
this.puan = puan;
}
public String getKulad() {
return kulad;
}
public void setKulad(String kulad) {
this.kulad = kulad;
}
public String getKulsifre() {
return kulsifre;
}
public void setKulsifre(String kulsifre) {
this.kulsifre = kulsifre;
}
}
I would not recommend to use a JavaScript alert to do so. But, if you really want to, your question would be a duplicate of:
Calling a JavaScript function from managed bean
I would suggest to simply set a message when the username and password do not match and indicate that the validation failed:
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Your message",
"Message details");
context.addMessage(null, message);
context.validationFailed();
Note the null in addMessage, this means we don't set a client ID to the message. This makes the message global. To display it on your page, simply use:
<h:messages globalOnly="true"/>
See also:
How to display my application's errors in JSF?

How to get file upload path location for database by setter and getter in jsf

I m having trouble to set value for entity bean. the problem is that when i populate form file will be upload but i need file path to store in data base. In my bean i have used setter of employee entity to set file url but And I think the code is enough to set file path for database but data is storing on database leaving employeePicture as null..
#Named
#RequestScoped
public class EmployeeAddController {
private Employees employees;
private String fileNameForDataBase;
private Part file;
#Inject
private EmployeeUpdateService updateService;
#PostConstruct
public void init() {
employees = new Employees();
}
public Employees getEmployees() {
return employees;
}
public void setEmployees(Employees employees) {
this.employees = employees;
}
public String getFileNameForDataBase() {
return fileNameForDataBase;
}
public void setFileNameForDataBase(String fileNameForDataBase) {
this.fileNameForDataBase = fileNameForDataBase;
}
public Part getFile() {
return file;
}
public void setFile(Part file) {
this.file = file;
}
public void upload() throws IOException {
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
.getExternalContext().getContext();
String realPath = ctx.getRealPath("/");
int random =(int) (Math.random() * 10000 + 1);
String fileString= realPath + File.separator + "resources/image/employee"+random+".jpg";
employees.setEmployeePicture(fileString);
try (InputStream input = file.getInputStream()) {
Files.copy(input, new File(fileString).toPath());
}
}
public String addEmployee() {
try {
this.updateService.add(employees);
return "index?faces-redirect=true";
} catch (Exception e) {
return null;
}
}
}
in My jsf page
"<div class="form-group">
<h:outputText value=" Employee Picture" class="col-sm-3 control-label"/>
<div class="col-sm-9">
<h:inputFile value="#{employeeAddController.file}">
<f:ajax listener="#{employeeAddController.upload()}"/>
</h:inputFile>
<h:outputText value="#{employeeAddController.fileNameForDataBase}"/>
</div>
<div>
<h:message for="fileUpload" class="text-primary"/>
</div>
</div>"***strong text***

action p:command button doesn't set property into managed bean [duplicate]

This question already has answers here:
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
(12 answers)
Closed 7 years ago.
I have an issue, I have a carousel, and I load dynamically some data into it, when I press into a carousel object it have to set a value into a manangedbean (CurrentSong) and show a dialog, now the dialog appear but the set property doesn't work. why?
xhtml page:
<h:body style="background: url(../resources/images/knapsack_background_light.jpg); background-attachment:fixed;">
<div id="contentContainer" class="trans3d">
<section id="carouselContainer" class="trans3d">
<ui:repeat value="#{retrieve.mostPopularSongs}" var="carouselSelectedSong">
<figure id="item" class="carouselItem">
<div class="itemInfo">
<h:commandButton id="selectedButton"
action="#{currentSong.setSong(carouselSelectedSong)}"
styleClass="btn"
onclick="parent.showSongDialog();"
style="
background-image: url('#{carouselSelectedSong.coverPath}');
background-size:100%;
width:300px;
height:300px;
border: black;">
<f:ajax render="songDialogContent"/>
</h:commandButton>
</div>
</figure>
</ui:repeat>
</section>
</div>
managed bean #ManagedBean #SessionScoped:
public class CurrentSong implements Serializable {
#EJB
private CustomerManagementLocal customerManagement;
#EJB
private SocialManagementLocal socialManagement;
private Customer customer;
private Song song;
private String textComment;
public CurrentSong() {
}
public Customer getCustomer() {
return customer;
}
public Song getSong() {
return song;
}
public void setSong(Song song) {
System.out.println("----------------------------------------- current song: " + song.getTitle());
this.song = song;
}
public void putLike () {
putValutation(true);
}
public void putDislike () {
putValutation(false);
}
public String getTextComment() {
return textComment;
}
public void setTextComment(String textComment) {
this.textComment = textComment;
}
public void putComment () {
FacesContext context = FacesContext.getCurrentInstance();
try {
Comment newComment = new Comment(customer, new Date(), textComment, song);
song.getCommentList().add(newComment);
socialManagement.putComment(newComment);
Notifier.notifyInfoMessage(context, Constants.INSERTION_COMMENT_SUCCESSFULLY);
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("clearTextComment();");
} catch (CustomerNotFoundException ex) {
Notifier.notifyErrorMessage(context, Constants.INTERNAL_ERROR);
} catch (SongNotFoundException ex) {
Notifier.notifyErrorMessage(context, Constants.INTERNAL_ERROR);
}
}
private void putValutation (boolean valutation) {
FacesContext context = FacesContext.getCurrentInstance();
try {
socialManagement.putValutation(new LikeValutation(customer, song, valutation, new Date()));
Notifier.notifyInfoMessage(context, Constants.INSERTION_VALUTATION_SUCCESSFULLY);
} catch (CustomerNotFoundException | SongNotFoundException ex) {
Notifier.notifyErrorMessage(context, Constants.INTERNAL_ERROR);
}
}
#PostConstruct
public void init() {
customer = customerManagement.getCurrentCustomer();
}
}
thanks!
Define one selectedSong variable in your managed bean with getters and setters.
Use JSF setPropertyActionListener similar to below code.
Remove the argument from your action method.
<h:commandButton id="selectedButton"
action="#{currentSong.setSong()}"
styleClass="btn"
onclick="parent.showSongDialog();"
style="
background-image: url('#{carouselSelectedSong.coverPath}');
background-size:100%;
width:300px;
height:300px;
border: black;">
<f:ajax render="songDialogContent"/>
<f:setPropertyActionListener target="#{currrentSong.selectedSong}" value="#{carouselSelectedSong}" />
</h:commandButton>
Assign the selectedSong to carouselSelectedSong in your managed bean action class
private Song selectedSong;
//getters and setters for selectedSong
public String setSong() {
System.out.println("----------------------------------------- current song: " + selectedSong.getTitle());
this.song = selectedSong;
return null;
}
I think the method setSong is not executed, that is the problem.
public void setSong(Song song) {
System.out.println("----------------------------------------- current song: " + song.getTitle());
this.song = song;
}
Normally the action method expects the method should return the String return value. Can you change the method definition like below code then it will work
public String setSong(Song song) {
System.out.println("----------------------------------------- current song: " + song.getTitle());
this.song = song;
return null;
}

apply request phase not being called

I am running the duke guess number example , I don't see the life cycle executing as expected. I have an inputText which expects a number. We also have a converter and a validator. Once I submit the <h:form> the validator is called. It should check the input if it is an integer. The value is not getting updated on the managed bean property. Please explain, below is the code snippet.
<h:inputText id="userNo" label="User Number" value="#{UserNumberBean.userNumber}"
converterMessage="#{ErrMsg.userNoConvert}" validator="#{UserNumberBean.validate}">
<f:valueChangeListener type="#{UserNumberBean.valueChange()}"></f:valueChangeListener>
<f:validateLongRange minimum="#{UserNumberBean.minimum}" maximum="#{UserNumberBean.maximum}" />
</h:inputText>
here the validator method is set in inputText component.
Once I submit the <h:form>, the validate method is called, below is the method
public String validate(javax.faces.context.FacesContext fc, javax.faces.component.UIComponent ui, java.lang.Object o){
System.out.println("in my own validation method");
if(userNumber ==8){
return "validation";
}
return "validation";
}
here userNumber is the backing bean property of the class
public class UserNumberBean {
public Integer userNumber = null;
public void setUserNumber(Integer user_number) {
System.out.println("setting userName" + user_number);
userNumber = user_number;
}
public Integer getUserNumber() {
return userNumber;
}
}
it has getters and setter but still userNumber value is not set. I get NullPointerException in validator method when accessing userNumber. Please let me know what is wrong. Below is the code snippet
<HTML xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<HEAD> <title>Hello</title> </HEAD>
<%# page contentType="application/xhtml+xml" %>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<body bgcolor="white">
<f:view>
<h:form id="helloForm" >
<h2>Hi. My name is Duke. I'm thinking of a number Man from
<h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/> to
<h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess
it?</h2>
<h:graphicImage id="waveImg" url="/wave.med.gif" alt="Duke waving" />
<h:inputText id="userNo" label="User Number" value="#{UserNumberBean.userNumber}"
converterMessage="#{ErrMsg.userNoConvert}" validator="#{UserNumberBean.validate}">
<f:valueChangeListener type="#{UserNumberBean.valueChange()}"></f:valueChangeListener>
<f:validateLongRange minimum="#{UserNumberBean.minimum}" maximum="#{UserNumberBean.maximum}" />
</h:inputText>
<h:commandButton id="submit" action="success" value="Submit" />
<p>
<h:message style="color: red; font-family: 'New Century Schoolbook', serif; font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/>
</p>
</h:form>
</f:view>
</body>
</HTML>
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.LongRangeValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import java.util.Random;
public class UserNumberBean {
Integer randomInt = null;
public Integer userNumber = null;
String response = null;
private boolean maximumSet = false;
private boolean minimumSet = false;
private long maximum = 0;
private long minimum = 0;
public UserNumberBean() {
System.out.println(" in constructor");
Random randomGR = new Random();
randomInt = new Integer(randomGR.nextInt(10));
System.out.println("Duke's number: " + randomInt);
}
public void setUserNumber(Integer user_number) {
System.out.println("setting userName" + user_number);
userNumber = user_number;
}
public Integer getUserNumber() {
return userNumber;
}
public String getResponse() {
System.out.println(" in getResponse");
if ((userNumber != null) && (userNumber.compareTo(randomInt) == 0)) {
return "Yay! You got it!";
} else {
return "Sorry, " + userNumber + " is incorrect.";
}
}
public long getMaximum() {
return (this.maximum);
}
public void setMaximum(long maximum) {
this.maximum = maximum;
this.maximumSet = true;
}
public long getMinimum() {
return (this.minimum);
}
public void setMinimum(long minimum) {
this.minimum = minimum;
this.minimumSet = true;
}
public String validate(javax.faces.context.FacesContext fc, javax.faces.component.UIComponent ui, java.lang.Object o){
System.out.println("in my own validation method");
if(userNumber ==8){
return "validation";
}
return "validation";
}
public void valueChange(){
System.out.println(" in value change");
}
}
What actually is the Apply Request phase? What happens in Apply Request phase? How different is it from Update Model Values phase
Your validator is broken in 2 ways:
Wrong method signature. It should return void. On validation faliures, you should be throwing a ValidatorException. On success you should just be returning and doing nothing additional.
You should be validating the value provided as 3rd argument, not the model value (which isn't been set at that point at all).
So, this should do:
public void validate(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return; // Ignore it. Let required="true" handle.
}
if (value != 8) {
// Assuming that 8 is the guess number?
throw new ValidatorException(new FacesMessage("Wrong guess, try again."));
}
}
Your NullPointerException is caused because you're attempting to compare the model value userNumber to a primitive integer 8. This causes autoboxing to try to unbox userNumber to a primitive, however that fails if the userNumber itself is null which cannot be represented in any primitive form.
As to the phases, the apply request values phase is definitely called, the validations phase is otherwise never called. You seem to expect that the apply request values phase updates the model values. This is not true, it applies the request parameters on JSF input component's submittedValue.
See also:
Difference between Apply Request Values and Update Model Values
Debug JSF lifecycle

Resources