jsf Button reacts after second click - java

I have a huge problem with my jsf page. I have to pass a Parameter in Post request to a request scoped Bean. All works fine except one little bug. The button to update my information reacts only from second click on.
This Page has to be request scope.
Everytime i push the button it first runs the #PostConstruct and is then ready for a click. I tried to delete the PostConstruct method but my program than stops. I tried nearly everything. Any ideas please?
Here is my Code: I enter this page by calling the Methode "showEditEvent" from another Bean.
package model.backingBean.event;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
//import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import model.backingBean.system.SessionBean;
import model.bean.event.Event;
import model.database.EventManager;
import model.enums.EColorTheme;
import model.exceptions.DatabaseException;
import model.utility.Cryptography;
import model.utility.system.ConfigurationReader;
/**
* Bean for is responsible for the edit actions, which are performed with an
* event. That means you can change eventdetails.
*
* #author 101 Computing
*
*/
#ManagedBean
#RequestScoped
public class EditEventBean implements Serializable {
private static final long serialVersionUID = 1L;
private Event event;
private UIComponent generateVerCode;
private UIComponent updateButton;
private Part uploadedImage;
private static Logger logger = LogManager.getLogger(EditEventBean.class
.getName());
private String color;
private ResourceBundle rb = FacesContext.getCurrentInstance().getApplication().
getResourceBundle(FacesContext.getCurrentInstance(),"msgs");
#ManagedProperty("#{param.eventID}")
private int eventID;
/**
* Injects SessionBean.
*/
#ManagedProperty("#{sessionBean}")
private SessionBean sb;
public String showEditEvent(int eventID) {
FacesContext fcxt = FacesContext.getCurrentInstance();
this.setEventID(eventID);
try {
this.event = EventManager.getEvent(eventID);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(FacesMessage.SEVERITY_ERROR,
rb.getString("exceptions_database"), null);
fcxt.addMessage(null, msgs);
}
return "/facelets/eventAdmin/editEvent.xhtml";
}
public int getEventID() {
return eventID;
}
public void setEventID(int eventID) {
this.eventID = eventID;
}
/**
* Method initializes the event.
*
* #throws IOException
*/
#PostConstruct
public void init() {
FacesContext fcxt = FacesContext.getCurrentInstance();
String id = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("eventID");
if (id != null) {
this.eventID = Integer.parseInt(id);
try {
this.event = EventManager.getEvent(this.eventID);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(
FacesMessage.SEVERITY_ERROR,
rb.getString("exception_database"), null);
fcxt.addMessage(null, msgs);
}
}
}
/**
*
* #param eventID
* #return
*/
public void update(int eventID) {
FacesContext fcxt = FacesContext.getCurrentInstance();
if (this.event.getEndOfEvent().after(this.event.getStartOfEvent())
&& this.event.getEntireTicketamount() > 0) {
if (this.uploadedImage != null) {
upload();
}
if (this.color.equals(EColorTheme.THEME_PINK.toString())) {
this.event.setColorTheme(EColorTheme.THEME_PINK);
} else if (this.color.equals(EColorTheme.THEME_BLUE.toString())) {
this.event.setColorTheme(EColorTheme.THEME_BLUE);
}
EventManager.updateEvent(this.event);
try {
this.event = EventManager.getEvent(this.eventID);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(
FacesMessage.SEVERITY_ERROR,
rb.getString("exception_database"), null);
fcxt.addMessage(null, msgs);
}
// Message for updating
FacesMessage msgs = new FacesMessage(FacesMessage.SEVERITY_INFO,
rb.getString("editEvent_successUpdate"), null);
fcxt.addMessage(null, msgs);
} else {
// Message for updating
FacesMessage message = new FacesMessage("Not updated "
+ "- ends before it starts!");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(updateButton.getClientId(context), message);
}
}
/**
* Method generates a new verification code and saves it in the database.
*/
public void generateNewVerificationCode(int eventID) {
FacesContext fcxt = FacesContext.getCurrentInstance();
String newCode = verificationGenerator();
this.event.setVerificationCode(newCode);
try {
EventManager.setNewVerificationCode(this.event.getEventID(),
newCode);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(FacesMessage.SEVERITY_ERROR,
rb.getString("exception_database"), null);
fcxt.addMessage(null, msgs);
}
FacesMessage message = new FacesMessage("New VC generated.");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(generateVerCode.getClientId(context), message);
logger.info("Generated a new verification code for event with id="
+ this.event.getEventID() + ".");
}
And here is my Facelet
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<ui:composition template="../../templates/basicTemplate.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:viewParam name="eventID" value="#{editEventBean.eventID}" />
<f:viewAction action="#{editEventBean.init}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h1 style="color: #808080; font-size: large">#{msgs.event_editEvent_h1}
</h1>
<br />
<h:form enctype="multipart/form-data">
<f:view>
<input type="hidden" name="eventID"
value="#{editEventBean.eventID}" />
<h:outputText value="#{msgs.editEvent_pictureSize}" /> <br/>
<h:panelGrid columns="3">
<h:outputLabel for="eventPic" value="#{msgs.event_picture}" />
<h:inputFile id="eventPic" value="#{editEventBean.uploadedImage}" sizeLimit="20480"/>
<h:message for="eventPic" errorStyle="color:red" />
<h:outputLabel for="title" value="#{msgs.event_title}" />
<h:inputText id="title" value="#{editEventBean.event.title}"
required="true" requiredMessage="#{msgs.event_reqTitle}"
label="#{msgs.event_title}" size="74">
<f:validateLength minimum="2" maximum="70" />
</h:inputText>
<h:message for="title" errorStyle="color:red" />
<h:outputLabel for="description" value="#{msgs.event_description}" />
<h:inputTextarea id="description"
value="#{editEventBean.event.description}" required="true"
requiredMessage="#{msgs.event_reqDescription}"
label="#{msgs.event_description}" cols="60">
<f:validateLength minimum="2" maximum="500" />
</h:inputTextarea>
<h:message for="description" errorStyle="color:red" />
<h:outputLabel for="location" value="#{msgs.event_location}" />
<h:inputText id="location" value="#{editEventBean.event.location}"
required="true" requiredMessage="#{msgs.event_reqLocation}"
label="#{msgs.event_location}" size="50">
<f:validateLength minimum="2" maximum="50" />
</h:inputText>
<h:message for="location" errorStyle="color:red" />
<h:outputLabel for="startOfEvent"
value="#{msgs.event_editStartDate}" />
<h:inputText id="startOfEvent"
value="#{editEventBean.event.startOfEvent}" required="true"
requiredMessage="#{msgs.event_reqStartDate}"
label="#{msgs.event_startDate}" size="50">
<f:convertDateTime pattern="#{msgs.longDate}" />
</h:inputText>
<h:message for="startOfEvent" errorClass="error" />
<h:outputLabel for="endOfEvent" value="#{msgs.event_editEndDate}" />
<h:inputText id="endOfEvent"
value="#{editEventBean.event.endOfEvent}" required="true"
requiredMessage="#{msgs.event_reqEndDate}"
label="#{msgs.event_endDate}" size="50">
<f:convertDateTime pattern="#{msgs.longDate}" />
</h:inputText>
<h:message for="endOfEvent" errorClass="error" />
<h:outputLabel for="ticketAmount"
value="#{msgs.event_ticketAmount}" />
<h:inputText id="ticketAmount"
value="#{editEventBean.event.entireTicketamount}" required="true"
requiredMessage="#{msgs.event_reqTicketAmount}"
label="#{msgs.event_ticketAmount}" size="50">
<f:convertNumber integerOnly="true" />
</h:inputText>
<h:message for="ticketAmount" errorStyle="color:red" />
<h:outputLabel for="ticketPrice" value="#{msgs.event_ticketPrice}" />
<h:inputText id="ticketPrice"
value="#{editEventBean.event.ticketPrice}" required="true"
requiredMessage="#{msgs.event_reqTicketPrice}"
label="#{msgs.event_ticketPrice}" size="50">
<f:convertNumber type="currency" currencySymbol="€"
maxFractionDigits="2" />
</h:inputText>
<h:message for="ticketPrice" errorStyle="color:red" />
<h:outputLabel for="accountNumber"
value="#{msgs.event_accountNumber}" />
<h:inputText id="accountNumber"
value="#{editEventBean.event.accountNumber}" required="true"
requiredMessage="#{msgs.event_reqAccountNumber}"
label="#{msgs.event_accountNumber}" size="50">
<f:convertNumber integerOnly="true" />
</h:inputText>
<h:message for="accountNumber" errorStyle="color:red" />
<h:outputLabel for="cashPayment" value="#{msgs.event_cashPayment}" />
<h:selectBooleanCheckbox id="cashPayment"
value="#{editEventBean.event.cashPayment}" />
<h:outputLabel></h:outputLabel>
<h:outputLabel for="creditPayment"
value="#{msgs.event_creditPayment}" />
<h:selectBooleanCheckbox id="creditPayment"
value="#{editEventBean.event.creditPayment}" />
<h:outputLabel></h:outputLabel>
<h:outputLabel for="isActive" value="#{msgs.event_isActive}" />
<h:selectBooleanCheckbox id="isActive"
value="#{editEventBean.event.isActive}" />
<h:outputLabel></h:outputLabel>
<h:outputLabel for="isActive"
value="#{msgs.event_chooseTicketColor}" />
<h:selectOneMenu value="#{editEventBean.color}">
<f:selectItem itemValue="PINK" itemLabel="Pink" />
<f:selectItem itemValue="BLUE" itemLabel="Blue" />
</h:selectOneMenu>
<h:outputLabel></h:outputLabel>
<h:commandButton id="updateButton" value="#{msgs.event_update}"
action="#{editEventBean.update(editEventBean.eventID)}"
binding="#{editEventBean.updateButton}" />
<h:message for="updateButton" infoClass="info" />
</h:panelGrid>
<h:panelGrid columns="4">
<h:outputLabel for="verificationCode" value="#{msgs.event_vc}" />
<h:inputText id="verificationCode"
value="#{editEventBean.event.verificationCode}" readonly="true">
</h:inputText>
<h:commandButton id="generateVerCode"
value="#{msgs.event_generateVC}"
action="#{editEventBean.generateNewVerificationCode(editEventBean.eventID)}"
binding="#{editEventBean.generateVerCode}" />
<h:message for="generateVerCode"
infoStyle="color:darkgreen; font-weight: bold;" />
</h:panelGrid>
</f:view>
</h:form>
<br />
</ui:define>
</ui:composition>

Found my error. And it was as easy as frustrating…
the
h:form enctype="multipart/form-data"
needs an id. I need the enctype for uploading files. And then the form has to have an id…
Two pages helped me finding this bug:
"7. If a parent of the with the UICommand button is been rendered/updated by an ajax request beforehand, then the first action will always fail."
(commandButton/commandLink/ajax action/listener method not invoked or input value not updated)
and this example of using file upload:
http://jsflive.wordpress.com/2013/04/23/jsf22-file-upload/
It's difficult find such tiny errors if the code is not your own…

Related

Can't get submit button work

I am new to java and trying to learn how to add data into database.
I cannot make my submit button work. I am getting error of "target unreachable". I am using hibernate and phpMyAdmin.
As I said I new to this. Please let me know if I am missing information that needed.
Instead of calling class in my submit button should I create private String method for the text boxes?
I am confused.
Thanks a lot for your help.
additem.xhtml
<h:body>
<ui:composition template="template.xhtml">
<ui:define name="content">
<h1>Add a New Item</h1>
<br />
<h:form>
<p:panel id="panel" header="Enter an Item" style="margin-bottom:20px;">
<p:growl id="growl" showDetail="true" sticky="false" />
<h:outputLabel value="Item Number" />Item Number:
<p:inputText value="#{LibraryItem.itemNumber}" />
<br />
<h:outputLabel value="Title" />Title:
<p:inputText value="#{LibraryItem.title}" />
<br />
<h:outputLabel for="type" value="Type">Item Type:
<p:selectOneMenu value="#{libraryItem.type}" style="width:228px">
<f:selectItem itemValue="" itemLabel="Select One" />
<f:selectItem itemValue="book" itemLabel="Book" />
<f:selectItem itemValue="magazine" itemLabel="Magazine" />
<f:selectItem itemValue="movie" itemLabel="Movie" />
<f:selectItem itemValue="music" itemLabel="Music" />
</p:selectOneMenu>
</h:outputLabel>
<br />
<h:outputLabel value="Status" />Status:
<p:inputText value="#{LibraryItem.status}" />
<br />
<p:commandButton value="Submit" actionListener="#{AddLibraryItem.addItem}" update="growl" />
<br />
</p:panel>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
AddLibraryItem.java
#Named
#ManagedBean
#Scope("request")
public class AddLibraryItem {
//no arg constructor
public AddLibraryItem(){
}
#Inject private LibraryItem libraryItem;
#Inject private ILibraryService libraryService;
public String addItem(){
//return value
String returnValue = "success";
//assign values
libraryItem.setStatus("CHECKED_IN");
//add to library
try {
libraryService.add(libraryItem);
displayMessage("Success","Item added");
}catch (Exception e){
displayMessage("Error", e.toString());
return "fail";
}
return returnValue;
}
//Getters and Setters
public LibraryItem getLibraryItem() {
return libraryItem;
}
public void setLibraryItem(LibraryItem libraryItem) {
this.libraryItem = libraryItem;
}
public ILibraryService getLibraryService() {
return libraryService;
}
public void setLibraryService(ILibraryService libraryService) {
this.libraryService = libraryService;
}
//method to display messages
private void displayMessage(String title, String message){
//get faces context
FacesContext currentInstance = FacesContext.getCurrentInstance();
//message to show
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, title, message);
//display the message
currentInstance.addMessage(null, fm);
}
}

JSP <f:validator> didn't see my validation class

........ ............ ........... ............ ................
My application doesn't display the validated data and I didn't know why.
In other cases it works but not this time, and I really didn't know what's the matter.
JSP:
(...)
<div id="contentarea">
<c:if test="${userBean.isOnline}">
<h2>
<h:outputLabel value="#{msg.vehicleRegistration}" />
</h2>
<fieldset>
<h:form>
<h:outputLabel value="#{msg.brandLabel}" />
<h:inputText id="brand" value="#{carBean.brand}">
<f:validator validatorId="TextValidator" />
</h:inputText>
<h:message for="brand" style="color:red" />
<br />
<h:outputLabel value="#{msg.surnameLabel}" />
<h:inputText id="surname" value="#{carBean.surname}">
<f:validator validatorId="TextValidator" />
</h:inputText>
<h:message for="surname" style="color:red" />
<br />
<h:outputLabel value="#{msg.addresLabel}" />
<h:inputText id="address" value="#{carBean.adress}">
<f:validator validatorId="TextValidator" />
</h:inputText>
<br />
<h:message for="address" style="color:red" />
<br />
<h:outputLabel value="#{msg.yearLabel}" />
<h:inputText id="year" value="#{carBean.year}">
<f:validator validatorId="NumberValidator" />
</h:inputText>
<h:message for="year" style="color:red" />
<br />
<br />
<h:commandButton value="#{msg.addButtonLabel}" onclick="alert('#{msg.vehicleAdded}')"
action="#{carList.addToList(carBean)}" styleClass="myButton" />
</h:form>
</fieldset>
</c:if>
<c:if test="${!userBean.isOnline}">
<h2>
<h:outputLabel value="#{msg.accessDenied}" />
</h2>
<b><a href="/Project"> <h:outputText
value="#{msg.accessDeniedLabel}" />
</a> </b>
</c:if>
</div>
(...)
</html>
TextValidator.java
package my.jsf.code;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
public class TextValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
FacesContext facesContext = FacesContext.getCurrentInstance();
String localePL = facesContext.getViewRoot().getLocale()
.toLanguageTag();
String text = localePL.equals("pl") ? "Pole nie może być puste!"
: "Field cannot be empty!";
String val = (String) value;
if (val == null) {
FacesMessage msg = new FacesMessage(text);
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}

Session management with parameter tagging / p:button /p:commandButton

I have a web application which have to implement login. user provide username and pwd after authenticating user should redirect to page which they have privilages pages are differant from user to user. Sometimes 2 or more users can get same page but available data should differant for do this I have pass users privilage ID(divisionId) to other beans
for now i have tried URL tagging parameter tagged to URL and dirrect to page successfully but I can't take it to bean variable.
Itried this with p:Button then textbox inputs won't get to bean class to execute the method when button click.
xhtml code -
<h:body>
<p:growl id="growl" showDetail="true" life="3000" />
<p:dialog id="dialog" header="Login" widgetVar="dlg" visible="true" closable="false" >
<h:form id="form">
<h:panelGrid columns="2">
<h:outputLabel for="username" value="Username: " />
<p:inputText id="username" value="#{loginBean.username}"
required="true" requiredMessage="Enter Username"/>
<h:outputLabel for="password" value="Password: " />
<p:password id="password" value="#{loginBean.password}"
required="true" requiredMessage="Enter Password"/>
</h:panelGrid>
<p:commandButton id="LoggingButton" value="Login" action="#{loginBean.doLogin()}"
update=":growl" oncomplete="handleLoginRequest(xhr, status, args),">
</p:commandButton>
</h:form>
</p:dialog>
</h:body>
loginbean-
public class LoginBean{
private String username;
private String password;
private int divisionId;
/**
* Creates a new instance of loginBean
*/
public LoginBean() {
}
public String doLogin() {
DbUser du = new DbUser();
divisionId = du.ValidateUser(username, password);
if(divisionId==0)
addMessage("Invalied username or password", false);
else{
if(divisionId==1){
// return "superuser.xhtml?faces-redirect=true";
return "superuser.xhtml?test="+divisionId+"faces-redirect=true";
//superAdmin
}
else if(divisionId==2||divisionId==3){
// return "engadmin_create_div.xhtml?faces-redirect=true";
return "engadmin_create_div.xhtml?test="+divisionId+"faces-redirect=true";
//ENG/IT ADMIN
}
else{
// return "viewonly_user.xhtml?faces-redirect=true";
return "viewonly_user.xhtml?test="+divisionId+"faces-redirect=true";
//View only users
}
}
return null;
}
I think that work :)
<p:growl id="growl" showDetail="true" life="3000" />
<p:dialog id="dialog" header="Login" widgetVar="dlg" visible="true" closable="false" >
<h:form id="form">
<h:panelGrid columns="2">
<h:outputLabel for="username" value="Username: " />
<p:inputText id="username" value="#{loginBean.username}"
required="true" requiredMessage="Enter Username"/>
<h:outputLabel for="password" value="Password: " />
<p:password id="password" value="#{loginBean.password}"
required="true" requiredMessage="Enter Password"/>
</h:panelGrid>
<p:commandButton id="LoggingButton" value="Login" actionListener="#{loginBean.doLogin()}">
</p:commandButton>
</h:form>
</p:dialog>
</h:body>
Bean
public class LoginBean{
private String username;
private String password;
private int divisionId;
/**
* Creates a new instance of loginBean
*/
public LoginBean() {
}
public static void redirect(String strDes) throws IOException {
ExternalContext ext = FacesContext.getCurrentInstance().getExternalContext();
ext.redirect(ext.getRequestContextPath() + strDes);
}
public void doLogin() {
DbUser du = new DbUser();
divisionId = du.ValidateUser(username, password);
if(divisionId==0)
addMessage("Invalied username or password", false);
else{
if(divisionId==1){
LoginBean.redirect("superuser.xhtml?test="+divisionId+"faces-redirect=true");
//superAdmin
}
else if(divisionId==2||divisionId==3){
LoginBean.redirect("engadmin_create_div.xhtml?test="+divisionId+"faces-redirect=true");
//ENG/IT ADMIN
}
else{
LoginBean.redirect("viewonly_user.xhtml?test="+divisionId+"faces-redirect=true");
//View only users
}
}
}
you get parameter from bean:
Map<String,String> params =
FacesContext.getExternalContext().getRequestParameterMap();
String action = params.get("test");

How do I get "p:focus" to work properly in this simple app (its currently not "focusing" at all)

PROBLEM:
The PrimeFaces "p:focus" tag is not focusing.
-I.e., when the xhtml page is presented to the user, no input fields are in focus.
QUESTION:
Why not? How can I get "p:focus" to work properly in this simple app?
(NOTE: using Java 6, Mojarra v2.1.11, PrimeFaces v3.4.2)
index.jsp
<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
<title>testcal2 - index.xhtml</title>
<meta charset="utf-8" />
</h:head>
<h:body>
<h:form id="queryForm">
<f:event type="postValidate" listener="#{testBean.validate}" />
<h:panelGroup id="msgsx">
<p:messages showSummary="true"/>
</h:panelGroup>
<p:panel id="queryPanel" header="Test p:focus..." style="width:100%;">
<p:focus context="queryPanel"/>
<h:panelGroup id="msgs" style="height:1.5em; text-align: center;display:block">
<p:message id="lastName_msg" for="lastName" style="display:none;" showSummary="false"/>
<p:message id="birthDate_msg" for="birthDate" style="display:none;" showSummary="false"/>
<p:message id="startDate_msg" for="startDate" style="display:none;" showSummary="false"/>
</h:panelGroup>
<h:panelGroup id="querypanelgroup" style="display:inline-block;">
<h:panelGroup>
<h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
<p:outputLabel style="margin-right: 5px;" value="Last Name:" for="lastName"/>
</h:panelGroup>
<h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
<p:inputText
id="lastName"
value="#{testBean.parmMap['lastName']}"
requiredMessage="last name required"
size="95"
maxlength="95"
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();return false;" >
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<br/>
<br/>
<h:panelGroup>
<h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
<p:outputLabel style="margin-right: 5px;" value="Birth Date:" for="birthDate"/>
</h:panelGroup>
<h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
<p:inputText
id="birthDate"
value="#{testBean.parmMap['birthDate']}"
requiredMessage="birth date required"
converter="dpConverter"
styleClass="datePicker"
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(1).show();$(this).mask('99/99/9999');return false;">
<p:ajax event="change" process="#this" update="#this"/>
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<br/>
<br/>
<h:panelGroup>
<h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
<p:outputLabel style="margin-right: 5px;" value="Start Date:" for="startDate"/>
</h:panelGroup>
<h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
<p:inputText
id="startDate"
value="#{testBean.parmMap['startDate']}"
requiredMessage="start date required"
converter="dpConverter"
styleClass="datePicker"
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(2).show();$(this).mask('99/99/9999');return false;">
<!-- optional to populate another field with same value...
onchange="$('...hashSymbolHere...queryForm\\:endDate').val($(this).val());">
-->
<p:ajax event="change" process="#this" update="#this"/>
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<br/>
<br/>
<p:commandButton
id="submit"
value="Submit"
oncomplete="applyDatePicker();"
type="submit"
update="#form"
process="#form"
action="#{testBean.submitQuery}"
style="width:150px;"
styleClass="button"/>
<p:commandButton
value="Reset"
update="#form"
onclick="location.reload();return true;"
process="#this"
actionListener="#{testBean.reset}"
immediate="true"
ajax="false"/>
</h:panelGroup>
</p:panel>
</h:form>
<h:outputStylesheet library="styles" name="query.css" />
<h:outputScript library="primefaces" name="/jquery/jquery.js" />
<h:outputScript library="primefaces" name="/jquery/plugins/ui/jquery-ui.custom.js" />
<h:outputScript library="primefaces" name="/jquery/plugins/inputmask/maskedinput.js" />
<h:outputScript library="js" name="index.js" target="head" />
</h:body>
</f:view>
</html>
index.js
$(document).ready(function()
{
applyDatePicker();
});
function applyDatePicker(){
$('.datePicker').datepicker(
{
showOn: 'button',
buttonText: "Choose",
showButtonPanel: true,
showOptions: {direction: 'up'},
changeYear: true,
changeMonth: true,
yearRange: "c-120:c+0"
});
}
TestBean.java
package aaa.bbb.ccc.war;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIForm;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ComponentSystemEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component("testBean")
#Scope("request")
public class TestBean implements Serializable
{
public TestBean()
{
parmMap = this.getParmMap();
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parmMap", parmMap);
}
public void reset(ActionEvent event)
{
LinkedHashMap<String, Object> m = new LinkedHashMap<String, Object>();
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("parmMap");
setParmMap(m);
}
public String submitQuery()
{
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("hitlistData");
if (this.getParmMap().isEmpty())
{
return "";
}
return "/page2.xhtml?faces-redirect=true";
}
private static LinkedHashMap<String, Object> parmMap;
public LinkedHashMap<String, Object> getParmMap()
{
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("parmMap");
if (null == map)
{
map = new LinkedHashMap<String, Object>();
}
return map;
}
public void setParmMap(LinkedHashMap<String, Object> map)
{
parmMap = map;
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parmMap", parmMap);
}
private static SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
public void validate(ComponentSystemEvent e) throws ParseException
{
LinkedHashMap parmMap = this.getParmMap();
UIForm queryForm = (UIForm) e.getComponent();
FacesContext fc = FacesContext.getCurrentInstance();
UIInput lastName_c = (UIInput) queryForm.findComponent("lastName");
String lastName = (String) (lastName_c.getValue());
UIInput birthDate_c = (UIInput) queryForm.findComponent("birthDate");
String birthDate = (String) birthDate_c.getValue();
UIInput startDate_c = (UIInput) queryForm.findComponent("startDate");
String startDate = (String) startDate_c.getValue();
try
{
if (null != lastName && lastName.trim().length() > 0)
{
if (null == birthDate || birthDate.length() < 1)
{
birthDate_c.setValid(false);
fc.addMessage(birthDate_c.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, birthDate_c.getRequiredMessage(), birthDate_c.getRequiredMessage()));
}
else
{
birthDate_c.setValid(true);
}
}
else
{
birthDate_c.setValid(true);
}
if (null == startDate || startDate.trim().length() < 1)
{
startDate_c.setValid(false);
fc.addMessage(startDate_c.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, startDate_c.getRequiredMessage(), startDate_c.getRequiredMessage()));
}
else
{
startDate_c.setValid(true);
}
if (fc.getMessageList().size() > 0)
{
fc.renderResponse();
}
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
}
It's because you're returning false on focus here:
<p:inputText
...
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();return false;" >
</p:inputText>
Returning false causes the event's default behaviour to be blocked.
To fix your problem, simply remove return false; from onfocus attribute of the input component.
<p:inputText
...
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();" >
</p:inputText>

ViewScoped works like RequestScoped - why?

I wrote a ViewScoped Managed-Bean and every time I refresh the page in my webbrowser, the Managed-Bean seems to be recreated, article is null, it loads a new article-object and so on. For me it looks like the same behaviour as RequestScoped.
I use Eclipse IDE for Java EE Developers, the newest JDK, Apache Tomcat 7.0.8 and Mojarra 2.0.3.
What is wrong?
Managed-Bean:
...
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
...
#ManagedBean
#ViewScoped
public class CreateArticle {
#ManagedProperty(value = "#{index.facade}")
private PersistenceFacade facade;
private Article article;
private Vector<ArtCategory> artcat;
public CreateArticle() {
artcat = ArtCategory.listArtCat();
}
#PostConstruct
public void postCreateArticle() {
if (article == null) {
try {
article = facade.createArticle();
} catch (DAOException e) {
e.printStackTrace();
}
}
}
public void setFacade(PersistenceFacade facade) {
this.facade = facade;
}
public Vector<ArtCategory> getArtcat() {
return artcat;
}
public Article getArticle() {
return article;
}
public String save() {
try {
facade.save(article);
facade.commit();
} catch (DAOException e) {
e.printStackTrace();
}
FacesMessage message = new FacesMessage(
"Successful!");
FacesContext.getCurrentInstance().addMessage(null, message);
return "/testpage.xhtml";
}
}
createArticle.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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Create article</title>
</h:head>
<h:body>
<h1>
<h:outputText value="System" />
</h1>
<h2>
<h:outputText value="Test1" />
</h2>
<h3>
<h:outputText value="Test2" />
</h3>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel for="artname">Articlename</h:outputLabel>
<h:inputText id="artname" value="#{createArticle.article.artname}"
required="true">
<f:ajax event="blur" render="artnameMessage" />
</h:inputText>
<h:message id="artnameMessage" for="artname" />
<h:outputLabel for="briefdesc">Brief description</h:outputLabel>
<h:inputTextarea id="briefdesc"
value="#{createArticle.article.briefdesc}" required="false">
<f:ajax event="blur" render="briefdescMessage" />
</h:inputTextarea>
<h:message id="briefdescMessage" for="briefdesc" />
<h:outputLabel for="price">Price</h:outputLabel>
<h:inputText id="price" value="#{createArticle.article.price}"
required="true">
<f:ajax event="blur" render="priceMessage" />
</h:inputText>
<h:message id="priceMessage" for="price" />
<h:outputLabel for="selectartcat">Article Category</h:outputLabel>
<h:selectOneMenu id="selectartcat"
value="#{createArticle.article.artcatnr}" required="true">
<f:selectItems value="#{createArticle.artcat}" var="artcat"
itemLabel="#{artcat.name}" itemValue="#{artcat.artcatnr}" />
<f:ajax event="blur" render="selectartcatMessage" />
</h:selectOneMenu>
<h:message id="selectartcatMessage" for="selectartcat" />
<h:panelGroup />
<h:commandButton value="Save"
action="#{createArticle.save}">
<f:ajax execute="#form" render="#form" />
</h:commandButton>
<h:messages globalOnly="true" layout="table" />
</h:panelGrid>
</h:form>
</h:body>
</html>
That's expected behaviour. Surely it will be recreated when you fire brand new HTTP GET requests by refreshing the page in the browser. Otherwise it would act like a session scoped bean and it would make the view scope useless (think about new GET requests in different browser tabs!). It will however not be recreated when you invoke any ajax requests or submit the form in the same view. A request scoped one would be recreated everytime. That's the core point/advantage of a view scoped bean.
Also make sure your implementing Serializable on your ViewScoped beans, just as you would with a SessionScoped bean.

Categories

Resources