Can't upload file with primefaces uploadedFile - jsf

I'm trying to upload the file(image) to my registration form without success. I followed BalusC recommendations (How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable) for upload with Primefaces 8.0 and JSF 2.2. No configurations in web.xml.
My upload method is not invoking. I've tried with the listener, but...nothing happened.
I cut some of Bean's code just to not bother you with code that has nothing to do with my issue.
Here is my html:
<h:form id="register">
<h:message for="RegisterGroupPanel" style="color:red;" />
<h:panelGrid columns="3" id="RegisterGroupPanel">
<!-- register a PostValidateEvent -->
<f:event listener="#{userRegisterBean.validatePassword}"
type="postValidate" />
<h:outputLabel for="username" value="Username : " />
<h:inputText id="username" value="#{userRegisterBean.username}"
required="true" requiredMessage="Please enter username" />
<h:message for="username" style="color: red;" />
<h:outputLabel for="password" value="Password : " />
<h:inputSecret id="password" value="#{userRegisterBean.password}"
required="true" requiredMessage="Please enter password" />
<h:message for="password" style="color: red;" />
<h:outputLabel for="confirmPassword" value="Confirm password : " />
<h:inputSecret id="confirmPassword" required="true"
requiredMessage="Please enter confirm password" />
<h:message for="confirmPassword" style="color: red;" />
</h:panelGrid>
</h:form>
<h:form enctype="multipart/form-data">
<p:fileUpload mode="simple" value="#{userRegisterBean.uploadedFile}" skinSimple="true" />
<p:commandButton value="Submit" ajax="false" action="#{userRegisterBean.upload}"/>
</h:form>
<br/>
<p:commandButton value="register" action="#{userRegisterBean.register}" />
and Bean:
#Component
#Scope("view")
public class UserRegisterBean implements Serializable {
private static final long serialVersionUID = -6740935236874916229L;
#Autowired
private UserApplicationService userApplicationService;
#Autowired
private PasswordEncoder passwordEncoder;
private String username;
private String password;
private transient UploadedFile uploadedFile;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UploadedFile getUploadedFile() {
return uploadedFile;
}
public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}
public void upload() {
if (uploadedFile.getSize() > 0) {
FacesMessage message = new FacesMessage("Succesful", uploadedFile.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
} else {
FacesMessage message = new FacesMessage("Not Succesful", "file is not uploaded");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
}

Related

Updating a field after a failed Validation

I am building a web application using the technologies mentioned in the post header. I have searched similar threads, but none of them provided an answer to my problem. I have configured my Maven project, the pom file is correct, JSF and PrimeFaces are working, but I encounter a problem when I do the following:
I copied the Client Side Validation example from the Prime Faces Showcase website, and on my end, it isn't working as expected.
When validation fails for a field, an error appears to the right of the field, and as long as it's there, I cannot update the field. When I try to type something, nothing happens on the screen, but if I highlight the text in the field, I can see it there.
Here's my registration.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Hello from Facelets
<h2>Registration Form</h2>
<h:form id="form">
<p:panel id="panel" header="Form" style="margin-bottom:10px;">
<p:fieldset legend="Registration Form" widgetVar="regWidget" style="width: 600px;">
<h:panelGrid columns="3" width="550" border="0">
<h:outputLabel value="UserName" />
<p:inputText value="#{regCont.prospect.userName}"
id="userName"
required="true"
requiredMessage="UserName is required"
validatorMessage="UserName should be of length from 5 to 15 chars"
>
<f:validateLength minimum="5" maximum="15" for="userName"></f:validateLength>
</p:inputText>
<p:message for="userName"/>
<h:outputLabel value="Password" />
<p:password value="#{regCont.password}"
id="password"
required="true"
requiredMessage="Password is required"
validatorMessage="Password should be of length from 5 to 15 chars"
>
<f:validateRegex pattern="^(?=^.{8,12}$)(?!.*(.)\1{3,})(?=.*[A-Z])(?=.*[a-z]{3,})(?=.*[^a-zA-Z0-9]{2,})(?=.*[0-9]{2,})[a-zA-Z]"/>
</p:password>
<p:message for="password" />
<h:outputLabel value="FirstName" />
<p:inputText value="#{regCont.prospect.firstName}"
id="firstName"
required="true"
requiredMessage="FirstName is required"
validatorMessage="FirstName should be of length from 5 to 15 chars"
>
<f:validateLength minimum="1" maximum="45" for="firstName"></f:validateLength>
</p:inputText>
<p:message for="firstName" display="tooltip" />
<h:outputLabel value="LastName" />
<p:inputText value="#{regCont.prospect.lastName}"
id="lastName"></p:inputText>
<p:message for="lastName" display="tooltip"/>
<h:outputLabel value="Email" />
<p:inputText value="#{regCont.prospect.email}"
id="email"
validatorMessage="Invalid Email">
<f:validateRegex pattern="[a-zA-Z0-9]+#[a-zA-Z]+.[a-zA-Z]{2,3}"></f:validateRegex>
</p:inputText>
<p:message for="email" />
<h:outputLabel value="Nation" />
<p:inputText value="#{regCont.prospect.nation}"
id="nation">
</p:inputText>
<p:message for="nation" />
<h3 style="margin-top:0">User type</h3>
<h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
<p:outputLabel for="type" value="User type:" />
<p:selectOneRadio id="type" value="#{regCont.prospect.userType}">
<f:selectItem itemLabel="Delegate" itemValue="Delegate" />
<f:selectItem itemLabel="Leader" itemValue="Leader" />
</p:selectOneRadio>
</h:panelGrid>
<p:commandButton value="Register" update="panel" icon="ui-icon-check" validateClient="true" style="margin-right:10px"/>
<h:commandButton value="Reset p:ajax" style="margin-right:20px;" >
<p:ajax update="panel" resetValues="true" />
</h:commandButton>
</h:panelGrid>
</p:fieldset>
</p:panel>
</h:form>
</h:body>
</html>
And here's my RegistrationController class:
#ManagedBean(name = "regCont")
#RequestScoped
public class RegistrationController implements Controller {
#ManagedProperty(value = "#{prospect}")
private Prospect prospect;
#ManagedProperty(value = "#{user}")
private User user;
private String msg;
private String password;
public void hashPassword() throws NoSuchAlgorithmException {
byte[] salt = Passwords.getNextSalt();
prospect.setSalt(salt);
prospect.setPasswordHash(Passwords.getHashWithSalt(password, salt));
password = "";
}
public Prospect getProspect() {
return prospect;
}
public void setProspect(Prospect prospect) {
this.prospect = prospect;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
private void clearAll() {
user.setFirstName("");
user.setLastName("");
user.setNation("");
user.setEmail("");
user.setUserName("");
user.setPasswordHash(null);
prospect.setFirstName("");
prospect.setLastName("");
prospect.setNation("");
prospect.setEmail("");
prospect.setUserType("");
prospect.setUserName("");
prospect.setPasswordHash(null);
}
public void saveUser() {
UserDAO dao = new UserDAO();
dao.createEntity(user);
this.msg = "Member Info Saved Successfull!";
clearAll();
}
public void saveProspect() {
ProspectDAO dao = new ProspectDAO();
try {
hashPassword();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
dao.createEntity(prospect);
this.msg = "Member Info Saved Successfull!";
}
public void reset() {
RequestContext.getCurrentInstance().reset("form");
}
public void updateUser(int id) {
UserDAO dao = new UserDAO();
try {
hashPassword();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
dao.updateEntity(id);
this.msg = "Member Info Update Successfull!";
clearAll();
}
public void deleteUser(int id) {
UserDAO dao = new UserDAO();
dao.deleteEntity(id);
this.msg = "Member Info Delete Successfull!";
clearAll();
}
}
Only case this works is, when I implemented the Reset button, and on a failed validation, I click reset, then I can input values into fields.
Also, when I hover above a field (p:inputText), the cursor doesn't change to the text cursor like on other fields (eg. h:inputText). Really don't have an idea how does the same piece of code work on the PrimeFaces ShowCase web site, and not on my end?
Does anybody have an idea how can I fix this?
I'm using JSF 2.2 + PrimeFaces 5.3

Show faces message below input fields

I am working with JSF (PrimeFaces)/EJB/JPA and a MySQL database. What I want to do is to show AT THE TOP OF THE XHTML BODY "User was successfully added to database" info message when an user is introduced successfully in the DB. I know I can use h:messages but then, also the validation error messages `are shown at the top of the body, and I want the error messages to be shown below the input fields. How could I do this?
Facelet code
<h:body>
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>`<!--WRONG-->
<p:inputText id="name" required="true" value="#{usersManagedBean.username}" requiredMessage="requiered field">
<f:validator validatorId="validators.NameValidator"/>
</p:inputText>
<p:watermark for="name" value="User" />
<p:message for="name" />
<p:inputText id="age" required="true" value="#{usersManagedBean.username}" requiredMessage="requiered field">
<f:validator validatorId="validators.AgeValidator"/>
</p:inputText>
<p:watermark for="age" value="Age" />
<p:message for="age" />
<p:commandButton value="Save user" action="#{usersManagedBean.saveUser}" ajax="false" />
</h:body>
Managed Bean code
//imports
#Named(value = "usersManagedBean")
#SessionScoped
public class UsersManagedBean implements Serializable
{
String username;
int userage;
#PostConstruct
public void init()
{
username="";
userage=0;
}
//Getters and Setters
public void saveUser()
{
User eUser = new Users();
eUser.setName(username);
eUser.setAge(userage);
ejbUsersDAO.create(eUser); //DAO
addSuccessMessage("User was successfully added to database");
}
public static void addSuccessMessage(String msg)
{
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage("successInfo", facesMsg);
}
}
Try setting globalOnly="true" attribute in your <h:messages> and change your addSuccessMessage to
fc.addMessage(null, facesMsg);

How to call the managebean method from panel form button in primefaces

Command Button is not working in my xhtml page when i am clicking on button its not calling Save method of CalendarController but handleSelectData method working fine. so please tell me where i am wrong.
xhtml file
<ui:composition 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:pe="http://primefaces.org/ui/extensions">
<p:dialog id="eventdailog" width="425px" height="320px"
header=" Create Event" widgetVar="dlg" focus="event"
showEffect="explode" hideEffect="explode" modal="true">
<h:form id="createevent">
<p>
<p:commandLink
value="Important:Learn about Event Management features"
style="text-decoration:none" />
</p>
</h:form>
<h:form id="event">
<p:tabView>
<p:tab id="Event1" title="Event">
<h:form id="eventtab">
<h:outputLabel for="event" />
<p:inputText id="event" label="Description" rendered="true" />
<p:watermark for="event" value="Please add description" />
<h:outputLabel for="date" />
<p:calendar value="#{calendar.date}" pattern="MM/dd/yyyy hh:mm a"
id="date" showOn="button" />
<h:outputText value="#{calendar.date}">
<f:convertDateTime pattern="MM/dd/yyyy hh:mm a" />
</h:outputText>
<p:autoComplete id="autoComp"
value="#{autocompleteBeanController.selectedUserProfiles}"
completeMethod="#{autocompleteBeanController.completeUserProfile}"
var="auto" itemLabel="#{auto.displayName}" itemValue="#{auto}"
converter="#{userAutocompleteConverter}" forceSelection="true"
required="true" rerequiredMessage="Send to is required"
label="Send to" minQueryLength="1" maxResults="5" multiple="true">
<p:ajax event="itemUnselect"
listener="#{autocompleteBeanController.handleUnselect}" />
<p:column>
<p:graphicImage value="#{auto.imagePath}" width="30" height="20" />
#{auto.displayName}
</p:column>
</p:autoComplete>
<p:watermark for="autoComp" value="Send to.."
onclick="PrimeFaces.cleanWatermarks();"
oncomplete="PrimeFaces.showWatermarks();" />
<br />
<p:commandButton id="save" value="Create"
actionListner="#{calendarController.save}"
onclick="dlg.hide();return false" />
</h:form>
</p:tab>
CalendarController.java
#Named
#Scope("session")
public class CalendarController implements Serializable {
private static final long serialVersionUID = -6221780314938096482L;
private Date date;
#Inject
private AutocompleteBeanController autocompletebean;
#Inject
private EventService eventService;
#Inject
private ManagedLoginBean login;
public ManagedLoginBean getLogin() {
return login;
}
public void setLogin(ManagedLoginBean login) {
this.login = login;
}
public EventService getEventService() {
return eventService;
}
public void setEventService(EventService eventService) {
this.eventService = eventService;
}
public AutocompleteBeanController getAutocompletebean() {
return autocompletebean;
}
public void setAutocompletebean(AutocompleteBeanController autocompletebean) {
this.autocompletebean = autocompletebean;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void handleDateSelect(SelectEvent event) {
FacesContext facesContext = FacesContext.getCurrentInstance();
SimpleDateFormat format = new SimpleDateFormat("d/M/yyyy");
RequestContext.getCurrentInstance().execute("dlg.show();");
}
public void save(ActionEvent event) {
EventDTO eventDto = new EventDTO();
eventDto.setEventUserDto(PaatashaalaUtil.getUserProfileDTO(login));
int status = eventService.createEvent(eventDto);
FacesMessage msg = null;
if (status == 1) {
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event Update",
null);
FacesContext.getCurrentInstance().addMessage("event", msg);
}
}
}
The correct attribute for p:commandButton is actionListener and not actionlistener

Primefaces wizard drops info from previous tabs

I am new to JSF. I am trying to use the Wizard component from the Primefaces official site and I am facing an issue: when moving to next tab, the info from the previous gets dropped.
I used the code from the site except the User bean. When I did a debug I saw that every time the Next button is pushed, the setter for each field is called, but the fields that were set in the previous steps are null.
I am using primefaces 3.5 version and jsf-api and jsf-impl 2.1.18.
Here is the code:
UserWizard:
#ManagedBean(name="userWizardBean")
#SessionScoped
public class UserWizard {
private User user = new User();
private boolean skip;
private static Logger logger = Logger.getLogger(UserWizard.class.getName());
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void save(ActionEvent actionEvent) {
//Persist user
FacesMessage msg = new FacesMessage("Successful", "Welcome :" + user.getFirstname());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public boolean isSkip() {
return skip;
}
public void setSkip(boolean skip) {
this.skip = skip;
}
public String onFlowProcess(FlowEvent event) {
logger.info("Current wizard step:" + event.getOldStep());
logger.info("Next step:" + event.getNewStep());
if(skip) {
skip = false; //reset in case user goes back
return "confirm";
}
else {
return event.getNewStep();
}
}
}
User:
public class User {
private String firstname;
private String lastname;
private Integer age;
private String street;
private String city;
private String postalCode;
private String info;
private String email;
private String phone;
public User(String firstname, String lastname, Integer age, String street, String city, String postalCode, String info, String email, String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.street = street;
this.city = city;
this.postalCode = postalCode;
this.info = info;
this.email = email;
this.phone = phone;
}
public User() {
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
And the xhtml file:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
<h:form>
<p:growl id="growl" sticky="true" showDetail="true"/>
<p:wizard widgetVar="wiz"
flowListener="#{userWizard.onFlowProcess}">
<p:tab id="personal" title="Personal">
<p:panel header="Personal Details">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value" styleClass="grid">
<h:outputText value="Firstname: *" />
<p:inputText required="true" label="Firstname"
value="#{userWizard.user.firstname}" />
<h:outputText value="Lastname: *" />
<p:inputText required="true" label="Lastname"
value="#{userWizard.user.lastname}" />
<h:outputText value="Age: " />
<p:inputText value="#{userWizard.user.age}" />
<h:outputText value="Skip to last: " />
<h:selectBooleanCheckbox value="#{userWizard.skip}" />
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="address" title="Address">
<p:panel header="Adress Details">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value">
<h:outputText value="Street: " />
<p:inputText value="#{userWizard.user.street}" />
<h:outputText value="Postal Code: " />
<p:inputText value="#{userWizard.user.postalCode}" />
<h:outputText value="City: " />
<p:inputText value="#{userWizard.user.city}" />
<h:outputText value="Skip to last: " />
<h:selectBooleanCheckbox value="#{userWizard.skip}" />
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="contact" title="Contact">
<p:panel header="Contact Information">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value">
<h:outputText value="Email: *" />
<p:inputText required="true" label="Email"
value="#{userWizard.user.email}" />
<h:outputText value="Phone: " />
<p:inputText value="#{userWizard.user.phone}"/>
<h:outputText value="Additional Info: " />
<p:inputText value="#{userWizard.user.info}"/>
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="confirm" title="Confirmation">
<p:panel header="Confirmation">
<h:panelGrid id="confirmation" columns="6">
<h:outputText value="Firstname: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.firstname}" />
<h:outputText value="Lastname: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.lastname}"/>
<h:outputText value="Age: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.age}" />>
<h:outputText value="Street: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.street}" />
<h:outputText value="Postal Code: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.postalCode}" />
<h:outputText value="City: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.city}" />
<h:outputText value="Email: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.email}" />
<h:outputText value="Phone " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.phone}"/>
<h:outputText value="Info: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.info}" />
<h:outputText />
<h:outputText />
</h:panelGrid>
<p:commandButton value="Submit" update="growl"
actionListener="#{userWizard.save}"/>
</p:panel>
</p:tab>
</p:wizard>
</h:form>
</h:body>
</html>
Any help or tip would be appreciated.
Thanks
I've managed to make it work: just added:
#ManagedBean(name = "userWizard")
and
#ViewScoped
to the UserWizard class and it worked .
Actually the problem is with the scope because you have mentioned as session scope so data is stored only for single session, it should be View scope as in view scope data remains stored unless you are redirected to another page.
I hope it helps you.

Primefaces actionbutton called several times

I've been strugling with an issue I can't find the way to solve it and I can't find anything related on the web.
I'm using Netbeans with Primefaces to develop a JSF web app.
Everything works fine except that sometimes the call to the actionlisteners is being done several times.
For example this is my JSF page with primefaces:
<h:body>
<ui:composition template="home.xhtml">
<ui:define name="content">
<h2>Administración de alertas SMS</h2>
<p:panel id="display">
<p:selectBooleanCheckbox itemLabel="Enviar alertas SMS" value="#{smsConfigBean.alertsEnabled}"/>
<p>
<h:outputText value="Mensaje de Texto: " /><br /><br />
<p:inputTextarea rows="5" cols="50" counterTemplate="{0} caracteres restantes." counter="counter" maxlength="160" value="#{smsConfigBean.smsMessage}" id="smsMessage"/>
<br />
<h:outputText id="counter" />
</p>
<p>
<h:outputText value="Dispositivo de envio SMS: " />
<p:selectOneRadio id="options" value="#{smsConfigBean.usePhone}">
<f:selectItem itemLabel="Modem USB" itemValue="false" />
<f:selectItem itemLabel="Telefono Android" itemValue="true" />
</p:selectOneRadio>
</p>
<br />
<p:tabView id="tabView">
<p:tab id="tab1" title="Modem USB">
<h:panelGrid id="modemGrid" columns="2" cellpadding="4">
<h:outputText value="Puerto: " />
<p:inputText id="port" value="#{smsConfigBean.port}"/>
<h:outputText value="Bit Rate (Opcional): " />
<p:inputText id="bitRate" value="#{smsConfigBean.bitRate}"/>
<h:outputText value="Nombre de modem (Opcional): " />
<p:inputText id="modemName" value="#{smsConfigBean.modemName}"/>
<h:outputText value="PIN: " />
<p:inputText id="pin" value="#{smsConfigBean.modemPin}"/>
<h:outputText value="Centro de Mensajes: " />
<p:inputText id="smsc" value="#{smsConfigBean.SMSC}"/>
</h:panelGrid>
</p:tab>
<p:tab id="tab2" title="Telefono Android">
<h:panelGrid id="phoneGrid" columns="2" cellpadding="4">
<h:outputText value="Path ADB:" />
<p:inputText id="adbPath" value="#{smsConfigBean.adbPath}"/>
<h:outputText value="Directorio de Configuracion:" />
<p:inputText id="configPath" value="#{smsConfigBean.configPath}"/>
<h:outputText value="Modo de conexion " />
<p:selectOneRadio id="connectOptions" value="#{smsConfigBean.useWifi}">
<f:selectItem itemLabel="USB" itemValue="false"/>
<f:selectItem itemLabel="WiFi" itemValue="true" />
</p:selectOneRadio>
<h:outputText value="Direccion IP (Solo para WiFi): " />
<p:inputText id="ipDir" value="#{smsConfigBean.ipDir}"/>
</h:panelGrid>
</p:tab>
</p:tabView>
</p:panel>
<br />
<p:commandButton id="saveSmsAlerts" value="Guardar" update="messages" action="#{smsConfigBean.saveChanges}" actionListener="#{smsConfigBean.saveChanges}"/>
</ui:define>
</ui:composition>
</h:body>
And this is my backend bean:
package Beans;
import helpers.Global; import javax.faces.bean.ManagedBean; import
javax.faces.bean.SessionScoped;
#ManagedBean #SessionScoped public class SmsConfigBean {
private Boolean alertsEnabled;
private Boolean usePhone;
private Boolean useWifi;
private String port;
private int bitRate;
private String modemName;
private String modemPin;
private String SMSC;
private String adbPath;
private String configPath;
private String ipDir;
private String smsMessage;
public SmsConfigBean() {
alertsEnabled = Global.getAlertsEnabled();
port = Global.getPort();
bitRate = Global.getBitRate();
modemName = Global.getModemName();
modemPin = Global.getModemPin();
SMSC = Global.getSMSC();
usePhone = Global.getUsePhone();
adbPath = Global.getAdbPath();
configPath = Global.getConfigPath();
useWifi = Global.getUseWifi();
ipDir = Global.getIpDir();
smsMessage = Global.getSmsMessage();
}
public Boolean getAlertsEnabled() {
return alertsEnabled;
}
public void setAlertsEnabled(Boolean alertsEnabled) {
this.alertsEnabled = alertsEnabled;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getBitRate() {
return bitRate;
}
public void setBitRate(int bitRate) {
this.bitRate = bitRate;
}
public String getModemName() {
return modemName;
}
public void setModemName(String modemName) {
this.modemName = modemName;
}
public String getModemPin() {
return modemPin;
}
public void setModemPin(String modemPin) {
this.modemPin = modemPin;
}
public String getSMSC() {
return SMSC;
}
public void setSMSC(String SMSC) {
this.SMSC = SMSC;
}
public Boolean getUsePhone() {
return usePhone;
}
public void setUsePhone(Boolean usePhone) {
this.usePhone = usePhone;
}
public String getAdbPath() {
return adbPath;
}
public void setAdbPath(String adbPath) {
this.adbPath = adbPath;
}
public String getConfigPath() {
return configPath;
}
public void setConfigPath(String configPath) {
this.configPath = configPath;
}
public Boolean getUseWifi() {
return useWifi;
}
public void setUseWifi(Boolean useWifi) {
this.useWifi = useWifi;
}
public String getIpDir() {
return ipDir;
}
public void setIpDir(String ipDir) {
this.ipDir = ipDir;
}
public String getSmsMessage() {
return smsMessage;
}
public void setSmsMessage(String smsMessage) {
this.smsMessage = smsMessage;
}
public void saveChanges(){
Global.setSmsMessage(smsMessage);
Global.setIpDir(ipDir);
Global.setUseWifi(useWifi);
Global.setConfigPath(configPath);
Global.setAdbPath(adbPath);
Global.setUsePhone(usePhone);
Global.setSMSC(SMSC);
Global.setModemPin(modemPin);
Global.setModemName(modemName);
Global.setBitRate(bitRate);
Global.setPort(port);
Global.setAlertsEnabled(alertsEnabled);
Global.sendInfoResponseMessage("Cambios guardados con exito");
}
}
The problem is that when saving the changes of this form by hitting the commandButton 'saveSmsAlerts' the call is being made twice. Resulting in the growl message to be shown twice too.
(You won't see the growl component because it was defined in the template)
This happens also in another page that I did for the same app that uploads a file using fileuploader. The file is uploaded 4 times!!
I'm using chrome to test the application and netbeans to develop it.
You should remove one of action or actionListener attribute.
<p:commandButton id="saveSmsAlerts" value="Guardar" update="messages" action="#{smsConfigBean.saveChanges}"/>
if you remove action attribute you should change the action method signature
<p:commandButton id="saveSmsAlerts" value="Guardar" update="messages" actionListener="#{smsConfigBean.saveChanges}"/>
Like this
public void saveChanges(ActionEvent e){
...
}
here is the difference between action and actionListener
Differences between action and actionListener

Resources