Rectangle 27 3

Don't use f:ajax with PrimeFaces components. Also your method is not defined correclty.

<p:inputText id="Name" value="#{personBean.missingName}"
        label="Name" required="true" size="30"
        validatorMessage="Name is required" >
       <p:ajax event="blur" listener="#{personBean.validateName}"/>
</p:inputText>
public void validateName(AjaxBehaviorEvent event){
    System.err.println("OnBlur Action");
}

Note that you should use

@JavaPlayer I've just tested it and it works, event using f:ajax. You probably have something else that prevent the action fireing. You could try with process="@this".

@Alexandre Lavoie - PrimeFaces doesn't enforce you to have the AjaxBehaviourEvent - primefaces.org/showcase/ui/ajaxifyAction.jsf - process="@this" is implicit and not required as it does that anyway.

@VeenarM, I was talking about f:ajax, also the parameter is not necessary only if declared like listener="#{personBean.validateName()}" ortherwise it is necessary.

@Alexandre Lavoie - Sorry, didn't realise because you jumped from talking about f:ajax to a process= which is related to p:ajax. :) The examples on primefaces don't declare the method with the (), and i've used it with out and it works fine - (the ajax behaviour eventt (I'm talking primefaces not standard jsf) -+1 original though

jsf - primefaces inputText desn't work with ajax event - Stack Overflo...

ajax jsf jsf-2 primefaces
Rectangle 27 26

You can search for "Ajax Behavior Events" in PrimeFaces User's Guide, and you will find plenty of them for all supported components. That's also what PrimeFaces lead Optimus Prime suggest to do in this related question at the PrimeFaces forum <p:ajax> event list?

There is no onblur event, that's the HTML attribute name, but there is a blur event. It's just without the "on" prefix like as the HTML attribute name. You can also look at all "on*" attributes of the tag documentation of the component in question to see which are all available, e.g. <p:inputText>.

The documentation doesn't list the events for the p:ajax tag. I would also expect to have a list of p:ajax events listed on the web somewhere. I wouldn't think i'd have to dig through the source to find such a thing. It'd be nice if someone could just post all of the possibilities here so that when the next guy searches for it he'll find them. The link on the inputText tag is useful, but i'm not sure if that is ALL of the possible events. If it is i'd like to post it here.

Every component has a different set of custom p:ajax event, you need to refer to each section in user's guide and look for ajax behavior events. All there in guide. Non-custom events like, click, keyup are not documented as it is general knowledge of dom events.

Contrary to previous comment, the user's guide I have (3.4) doesn't have a section listing this.

Yes, you will find SOME events, but only special events for some special components like Schedule or SelectCheckBoxMenu. You won't find what is supported for i.e. InputText

jsf - List of events - Stack Overflow

ajax jsf jsf-2 primefaces
Rectangle 27 3

The issue lies in the ajax tag inside the inputText component:

<p:ajax event="keyup" update="example" process="@this" />

This means that you are submitting the component on each keyup event. And the validator will be called each time consequently.

A possible workaround is to move the validator to another component, following the same technique used for validating multiple components:

In the facelets page add an inputHidden that uses uniqueValueValidator:

<h:form id="formId" >
    <p:inputText id="value" value="#{myBean.value}" >
        <p:ajax event="keyup" update="example" process="@this" />
    </p:inputText>
    <h:inputHidden id="hidden">
        <f:validator validatorId="uniqueValueValidator" />
    </h:inputHidden>
    <p:message for="hidden" />
    <p:commandButton value="Save" action="#{myBean.saveValue}" process="@form" update="@form"/>
</h:form>
@Named
@FacesValidator("uniqueValueValidator")
public class UniqueValueValidator implements Validator {

    @Inject
    private DBService service;

    @Override
    public void validate(FacesContext context, UIComponent component, Object obj) {

        Object inputValue = ((UIInput) context.getViewRoot().findComponent("formId:value")).getSubmittedValue();

        if(service.isValueNotUnique((String) inputValue) {
            // throw ValidatorException 
        }
    }

}

This approach, like yours, implies a round-trip client-server-client of the inputed content on each keyup event. If this is not necessary, you can avoid it with a javascript approach as explained in the other answer.

java - Skip validation of Primefaces Inputtext on keyup event but vali...

java validation jsf primefaces
Rectangle 27 4

Dialog Framework opens the dialog in an iframe. To update values in the parent view add this ajax event to the commandButton or commonadLink that opens the dialog:

<p:commandButton value="Open Dialog" actionListener"...">
   <p:ajax event="dialogReturn" update="idFormStore"/>
</p:commandButton>

jsf 2 - PrimeFaces RequestContext.getCurrentInstance().update() not wo...

jsf-2 primefaces
Rectangle 27 2

You can find out the index of the selected column with jQuery and send it to server as an ajax event

first add an inputText above the table (make it hidden)

<h:inputText id="mySelectedColumnId" value="#{myBean.mySelectedColumnField}" style="display:none">
    <f:ajax listener="#{myBean.myListener}"></f:ajax>
</h:inputText>

and the following js code to bind clicking on the table and triggering click on the h:inputText which will trigger listened on the server

jQuery(document).delegate("#yourTableID td", "click", function (event) {//bind every click on any td in the table
    var columnNumber = jQuery(this).index();//get index of clicked row
    jQuery("#mySelectedColumnId").val(columnNumber); //set value in the inputtext
    jQuery("#mySelectedColumnId").change(); //this will trigger the ajax listener
});

What I actually meant was the following structure:

<h:outputScript name="js/newjavascriptfile.js" target="head" />

.
.
.
.

<h:form prependId="false">
     <h:inputText id="mySelectedColumnId" value="#{myBean.mySelectedColumnField}" style="display:none">
         <f:ajax listener="#{myBean.myListener}"></f:ajax>
     </h:inputText>
     <p:dataTable id="DataTable"....
.
.
.
.

and inside the js (place it inside js folder inside resources folder in the root of your web app folder Resources (Library) In JSF 2.0) file place

jQuery(window).load(function () {
     jQuery(document).delegate("#yourTableID td", "click", function (event) {//bind every click on any td in the table
        var columnNumber = jQuery(this).index();//get index of clicked row
        jQuery("#mySelectedColumnId").val(columnNumber); //set value in the inputtext
        jQuery("#mySelectedColumnId").change(); //this will trigger the ajax listener
    });
});

Thanks for the reply but in primeface datatable there is no onClick event, in this case how do i get the js code activate (i am in the process of learning js).

Ok, i did it by putting a inputText inside the p:column and using its onClick event, Thanks for the solution.

jsf 2 - Primefaces Datatable column selection - Stack Overflow

jsf-2 primefaces
Rectangle 27 1

When the ajax event is fired, all the input elements in the form are sent. That means that all the selectManyCheckbox (one for each row) are sent. That's why setSelectedTabsNames is called several times.

You have to change how you have designed your implementation. One way woud be to store the selected options in the FopsUser object, so you could do value="#{user.selectedTabsNames}":

<p:selectManyCheckbox id="grid" value="#{user.selectedTabsNames}"
     layout="pageDirection" >
     **<f:selectItems value="#{adminBean.allTabNames}" />**
</p:selectManyCheckbox>

This way the selected tabs for each row are stored separately.

I still have problem after putting selectedTabsNames into each User object. Each selectedTabsNames is called once I submit ajax buttom request.

all selectedTabsNames methods are still got called.

jsf - Primefaces attribute got set several times with ...

jsf primefaces
Rectangle 27 1

Try to remove the immediate attribute of your ajax event and in your commandbutton add the attributes:

process="@this" partialSubmit="true" ajax="true"
<p:ajax event="rowDblselect" listener="#{companyBean.update()}" process="@this" partialSubmit="true" />
<p:commandButton id="button1"  value="Search" actionListener="#{                     
         companyBean.search()}" update="dataTable" process="@this" partialSubmit="true" ajax="true"/>

jsf - Primefaces : jsf primefaces datatable

Rectangle 27 27

As to the cause of your problem, the ajax request will update the HTML DOM tree with new HTML elements from the ajax response. Those new HTML elements do obviously not have the jQuery event handler function attached. However, the $(document).ready() isn't re-executed on ajax requests. You need to manually re-execute it.

This can be achieved in various ways. The simplest way is to use $(document).on(event, selector, function) instead of $(selector).on(event, function). This is tied to the document and the given functionRef is always invoked when the given eventName is triggered on an element matching the given selector. So you never need to explicitly re-execute the function by JSF means.

$(document).on("change", ":input", function() {
    console.log("From change event on any input: " + this.id);
});

The alternative way is to explicitly re-execute the function yourself on complete of ajax request. This would be the only way when you're actually interested in immediately execute the function during the ready/load event (e.g. to directly apply some plugin specific behavior/look'n'feel, such as date pickers). First, you need to refactor the $(document).ready() job into a reusable function as follows:

$(document).ready(function(){
    applyChangeHandler();
});

function applyChangeHandler() {
    $(":input").on("change", function() {
        console.log("From applyChangeHandler: " + this.id);
    });
}
$.each()

Then, choose one of the following ways to re-execute it on complete of ajax request:

Use the oncomplete attribute of the PrimeFaces command button:

oncomplete="applyChangeHandler()"
<h:outputScript target="body">
<h:outputScript id="applyChangeHandler" target="body">
    applyChangeHandler();
</h:outputScript>

and reference it in update attribute:

update=":applyChangeHandler"
  • Use <p:outputPanel autoUpdate="true"> to auto update it on every ajax request: <p:outputPanel autoUpdate="true"> <h:outputScript id="applyChangeHandler"> applyChangeHandler(); </h:outputScript> </p:outputPanel>
<o:onloadScript>
$(document).ready()
<h:outputScript>
<o:onloadScript>applyChangeHandler();</o:onloadScript>

Or you could use event delegation, which is the technique designed specifically to solve this kind of problem.

@Anthony: That works only on ajax requests which are executed via "plain jQuery" and on HTML DOM elements which are attached via "plain jQuery" because it has its own internal event listeners therefor.

All of my experience tells me neither of those statements is correct.

@BalusC. Thanks for posting. It seems the 3rd choice is suitable for my use case. I am planning to put that code block in the facelet template. And for this 3rd way, I removed $(document).ready(function(){} otherwise the handler is registered twice on initial page load, then put the autoUpdatable p:outputPanel to the end of the body manually. If I eventually find myself implementing the functionalities that Omnifaces already offers, definitely will give it a try. :)

javascript - JSF/PrimeFaces ajax updates breaks jQuery event listener ...

javascript jquery ajax jsf-2 primefaces
Rectangle 27 27

As to the cause of your problem, the ajax request will update the HTML DOM tree with new HTML elements from the ajax response. Those new HTML elements do obviously not have the jQuery event handler function attached. However, the $(document).ready() isn't re-executed on ajax requests. You need to manually re-execute it.

This can be achieved in various ways. The simplest way is to use $(document).on(event, selector, function) instead of $(selector).on(event, function). This is tied to the document and the given functionRef is always invoked when the given eventName is triggered on an element matching the given selector. So you never need to explicitly re-execute the function by JSF means.

$(document).on("change", ":input", function() {
    console.log("From change event on any input: " + this.id);
});

The alternative way is to explicitly re-execute the function yourself on complete of ajax request. This would be the only way when you're actually interested in immediately execute the function during the ready/load event (e.g. to directly apply some plugin specific behavior/look'n'feel, such as date pickers). First, you need to refactor the $(document).ready() job into a reusable function as follows:

$(document).ready(function(){
    applyChangeHandler();
});

function applyChangeHandler() {
    $(":input").on("change", function() {
        console.log("From applyChangeHandler: " + this.id);
    });
}
$.each()

Then, choose one of the following ways to re-execute it on complete of ajax request:

Use the oncomplete attribute of the PrimeFaces command button:

oncomplete="applyChangeHandler()"
<h:outputScript target="body">
<h:outputScript id="applyChangeHandler" target="body">
    applyChangeHandler();
</h:outputScript>

and reference it in update attribute:

update=":applyChangeHandler"
  • Use <p:outputPanel autoUpdate="true"> to auto update it on every ajax request: <p:outputPanel autoUpdate="true"> <h:outputScript id="applyChangeHandler"> applyChangeHandler(); </h:outputScript> </p:outputPanel>
<o:onloadScript>
$(document).ready()
<h:outputScript>
<o:onloadScript>applyChangeHandler();</o:onloadScript>

Or you could use event delegation, which is the technique designed specifically to solve this kind of problem.

@Anthony: That works only on ajax requests which are executed via "plain jQuery" and on HTML DOM elements which are attached via "plain jQuery" because it has its own internal event listeners therefor.

All of my experience tells me neither of those statements is correct.

@BalusC. Thanks for posting. It seems the 3rd choice is suitable for my use case. I am planning to put that code block in the facelet template. And for this 3rd way, I removed $(document).ready(function(){} otherwise the handler is registered twice on initial page load, then put the autoUpdatable p:outputPanel to the end of the body manually. If I eventually find myself implementing the functionalities that Omnifaces already offers, definitely will give it a try. :)

javascript - JSF/PrimeFaces ajax updates breaks jQuery event listener ...

javascript jquery ajax jsf-2 primefaces
Rectangle 27 27

As to the cause of your problem, the ajax request will update the HTML DOM tree with new HTML elements from the ajax response. Those new HTML elements do obviously not have the jQuery event handler function attached. However, the $(document).ready() isn't re-executed on ajax requests. You need to manually re-execute it.

This can be achieved in various ways. The simplest way is to use $(document).on(event, selector, function) instead of $(selector).on(event, function). This is tied to the document and the given functionRef is always invoked when the given eventName is triggered on an element matching the given selector. So you never need to explicitly re-execute the function by JSF means.

$(document).on("change", ":input", function() {
    console.log("From change event on any input: " + this.id);
});

The alternative way is to explicitly re-execute the function yourself on complete of ajax request. This would be the only way when you're actually interested in immediately execute the function during the ready/load event (e.g. to directly apply some plugin specific behavior/look'n'feel, such as date pickers). First, you need to refactor the $(document).ready() job into a reusable function as follows:

$(document).ready(function(){
    applyChangeHandler();
});

function applyChangeHandler() {
    $(":input").on("change", function() {
        console.log("From applyChangeHandler: " + this.id);
    });
}
$.each()

Then, choose one of the following ways to re-execute it on complete of ajax request:

Use the oncomplete attribute of the PrimeFaces command button:

oncomplete="applyChangeHandler()"
<h:outputScript target="body">
<h:outputScript id="applyChangeHandler" target="body">
    applyChangeHandler();
</h:outputScript>

and reference it in update attribute:

update=":applyChangeHandler"
  • Use <p:outputPanel autoUpdate="true"> to auto update it on every ajax request: <p:outputPanel autoUpdate="true"> <h:outputScript id="applyChangeHandler"> applyChangeHandler(); </h:outputScript> </p:outputPanel>
<o:onloadScript>
$(document).ready()
<h:outputScript>
<o:onloadScript>applyChangeHandler();</o:onloadScript>

Or you could use event delegation, which is the technique designed specifically to solve this kind of problem.

@Anthony: That works only on ajax requests which are executed via "plain jQuery" and on HTML DOM elements which are attached via "plain jQuery" because it has its own internal event listeners therefor.

All of my experience tells me neither of those statements is correct.

@BalusC. Thanks for posting. It seems the 3rd choice is suitable for my use case. I am planning to put that code block in the facelet template. And for this 3rd way, I removed $(document).ready(function(){} otherwise the handler is registered twice on initial page load, then put the autoUpdatable p:outputPanel to the end of the body manually. If I eventually find myself implementing the functionalities that Omnifaces already offers, definitely will give it a try. :)

javascript - JSF/PrimeFaces ajax updates breaks jQuery event listener ...

javascript jquery ajax jsf-2 primefaces
Rectangle 27 27

As to the cause of your problem, the ajax request will update the HTML DOM tree with new HTML elements from the ajax response. Those new HTML elements do obviously not have the jQuery event handler function attached. However, the $(document).ready() isn't re-executed on ajax requests. You need to manually re-execute it.

This can be achieved in various ways. The simplest way is to use $(document).on(event, selector, function) instead of $(selector).on(event, function). This is tied to the document and the given functionRef is always invoked when the given eventName is triggered on an element matching the given selector. So you never need to explicitly re-execute the function by JSF means.

$(document).on("change", ":input", function() {
    console.log("From change event on any input: " + this.id);
});

The alternative way is to explicitly re-execute the function yourself on complete of ajax request. This would be the only way when you're actually interested in immediately execute the function during the ready/load event (e.g. to directly apply some plugin specific behavior/look'n'feel, such as date pickers). First, you need to refactor the $(document).ready() job into a reusable function as follows:

$(document).ready(function(){
    applyChangeHandler();
});

function applyChangeHandler() {
    $(":input").on("change", function() {
        console.log("From applyChangeHandler: " + this.id);
    });
}
$.each()

Then, choose one of the following ways to re-execute it on complete of ajax request:

Use the oncomplete attribute of the PrimeFaces command button:

oncomplete="applyChangeHandler()"
<h:outputScript target="body">
<h:outputScript id="applyChangeHandler" target="body">
    applyChangeHandler();
</h:outputScript>

and reference it in update attribute:

update=":applyChangeHandler"
  • Use <p:outputPanel autoUpdate="true"> to auto update it on every ajax request: <p:outputPanel autoUpdate="true"> <h:outputScript id="applyChangeHandler"> applyChangeHandler(); </h:outputScript> </p:outputPanel>
<o:onloadScript>
$(document).ready()
<h:outputScript>
<o:onloadScript>applyChangeHandler();</o:onloadScript>

Or you could use event delegation, which is the technique designed specifically to solve this kind of problem.

@Anthony: That works only on ajax requests which are executed via "plain jQuery" and on HTML DOM elements which are attached via "plain jQuery" because it has its own internal event listeners therefor.

All of my experience tells me neither of those statements is correct.

@BalusC. Thanks for posting. It seems the 3rd choice is suitable for my use case. I am planning to put that code block in the facelet template. And for this 3rd way, I removed $(document).ready(function(){} otherwise the handler is registered twice on initial page load, then put the autoUpdatable p:outputPanel to the end of the body manually. If I eventually find myself implementing the functionalities that Omnifaces already offers, definitely will give it a try. :)

javascript - JSF/PrimeFaces ajax updates breaks jQuery event listener ...

javascript jquery ajax jsf-2 primefaces
Rectangle 27 2

Chart should be visible when page loads...after that all ajax request properly renders your chart. To do that just provide a dummy series data like (0,0) for series 1 and (0,0) for series 2 when page loads, after that everything works fine

jsf - primefaces charts not updating when submit a new request - Stack...

jsf jsf-2 primefaces
Rectangle 27 2

As per the comments, you're using a @RequestScoped bean. The ajax events cause a new request, so it's being rebuilt and consequently loosing its current state. The solution is to use the view scope and take advantage of the JSF' stateful nature.

jsf - Double p:selectOneMenu to feed one last p:selectOneMenu with p:a...

ajax jsf primefaces
Rectangle 27 1

I am not sure what you're doing with 'rendererType and rendered' on your ajax events - they make no sense and ikely just breaking.

I've got it working fine in the below example (note my bean is different name) - i made the grid only 1 in colum size just for testing purposes and you're best off wrapping those full data objects you want re-rendered after ajax request. see the below code p:ajax uses 'update' to render content, where f:ajax uses render="id" etc..

<h:form>
    <h:panelGrid columns="1">
        <h:panelGroup layout="block" id="nameSection" >
            <p:outputLabel for="uname"  value="Name"/> 

            <p:inputText id="uname"  value="#{onBlur.name}" required="true" requiredMessage="Enter your name">
                <p:ajax event="blur" update="nameSection"/>
            </p:inputText>


            <h:outputText value=""/>
            <p:message id="name" for="uname" />
        </h:panelGroup> 

        <h:panelGroup layout="block" id="addressSection" >
            <p:outputLabel for="add"  value="Address"/>
            <p:inputText id="add" value="#{onBlur.address}"   required="true" requiredMessage="Enter your address">
                <p:ajax event="blur" update="addressSection"/>
            </p:inputText>

            <h:outputText value=""/>
            <p:message id="address" for="add" />
         </h:panelGroup>
    </h:panelGrid>

    <h:commandButton value="Submit"/>
</h:form>

Any reason why this was downvoted? comment would be nice... If you wanted further info on the renderType/rendered on ajax - refer to document guide : primefaces.org/docs/vdl/3.5/primefaces-p/ajax.html

Not sure why; it's a valid answer. If the downvoter feels strongly enough about it, OD will come back to explain.

My fault: it was an unwanted downvote. And I could not untoggle it because the answer hasn't been edited anymore.

jsf - Unable to validate for primefaces event blur? - Stack Overflow

jsf primefaces
Rectangle 27 1

OMG it took me a long time to figure this one out. BalusC is as always dead on the money but the thing that escaped me was that updating a Datatable does not update all its children as I expected. Updating the table does in fact update the rows (deleted rows in the underlying model disappear) and reorder rows if the underlying model has been reordered, but values in outputText widgets inside CellEditor containers are not updated, except for the one edited, unless you supply a <p:ajax /> tag to those you want to update, which in my case was all of them. I am guessing there was a design assumption that when a CellEditor initiated an Ajax call, the Datatable parent would only update the child cell edited. I've never understood why a CellEditor needs both an InputText and an OutputText contained in order to work.

This led to horrendous problems for me when multiple users concurrently edited the same Datatable in different sessions. UserA would make an edit and get a correctly updated table, potentially with the rows in a different order. Then UserB, whose Datatable was now out of date, would make an edit, and the edit would get persisted to the database correctly (because the row had a unique, hidden ID) but the edit would go to the wrong row in the Datatable (but the correct column), and UserB, even after update, would not see UserA's change in a different cell. Once I put the <p:ajax update="datatableID" /> tag in the inputText body it worked properly. I still had concurrency issues which I had to solve separately, but at least the Datatable was correct after edits.

BalusC, if you are out there, please correct my bad assumptions here.

jsf - primefaces datatable rowedit not updating cell element - Stack O...

jsf primefaces datatable listbox
Rectangle 27 1

link your ThemeSwitcher component to a managedBean and add a listener linked to a ajax event:

<h:form id="form-theme">
<p:themeSwitcher id="defaultSwitcher" value="#{themeSwitcherBean.theme}">
<f:selectItems value="#{themeSwitcherBean.themes}" />
<p:ajax listener="#{themeSwitcherBean.saveTheme}" />
</p:themeSwitcher>
</h:form>

in your managedbean create the method who call saveTheme, that going to call a class to persist in database, and call the the class for the database when start to get the theme who had saved into the database:

@SessionScoped
@ManagedBean(name="themeSwitcherBean")
public class ThemeSwitcherBean implements Serializable{ 
private Map<String, String> themes;
    private String theme;
    private GuestPreferences gp;

    private void setGp(GuestPreferences gp) {
        this.gp = gp;
    }

    public Map<String, String> getThemes() {
        return themes;
    }

    public String getTheme() {
        return theme;
    }

    public void setTheme(String theme) {
        this.theme = theme;
    }

    @PostConstruct
    public void init() {
        setGp(new GuestPreferences()); // persistent class
        setTheme(gp.getTheme()); // theme from the database;

        themes = new TreeMap<String, String>();
        themes.put("Aristo", "aristo");
        themes.put("Black-Tie", "black-tie");
        themes.put("Blitzer", "blitzer");
        themes.put("Bluesky", "bluesky");
        themes.put("Bootstrap", "bootstrap");
        themes.put("Casablanca", "casablanca");
        themes.put("Cupertino", "cupertino");
        themes.put("Dark-Hive", "dark-hive");
        themes.put("Dot-Luv", "dot-luv");
        themes.put("Eggplant", "eggplant");
        themes.put("Excite-Bike", "excite-bike");
        themes.put("Flick", "flick");
        themes.put("Glass-X", "glass-x");
        themes.put("Hot-Sneaks", "hot-sneaks");
        themes.put("Humanity", "humanity");
        themes.put("Le-Frog", "le-frog");
        themes.put("Midnight", "midnight");
        themes.put("Mint-Choc", "mint-choc");
        themes.put("Overcast", "overcast");
        themes.put("Pepper-Grinder", "pepper-grinder");
        themes.put("Redmond", "redmond");
        themes.put("Rocket", "rocket");
        themes.put("Sam", "sam");
        themes.put("Smoothness", "smoothness");
        themes.put("South-Street", "south-street");
        themes.put("Start", "start");
        themes.put("Sunny", "sunny");
        themes.put("Swanky-Purse", "swanky-purse");
        themes.put("Trontastic", "trontastic");
        themes.put("UI-Darkness", "ui-darkness");
        themes.put("UI-Lightness", "ui-lightness");
        themes.put("Vader", "vader");
    }

    public void saveTheme() {           
        gp.setTheme(theme); // theme to database
    }

}

method theme from class GuestPreferences is going to persist to the database

@SessionScoped
public class GuestPreferences {

    public String getTheme(){        
        //return the theme from the database
    }

    public void setTheme(String theme){
        //send the theme to the database
    }

}

the form to send and receive data from the database depends of you prefer: * jdbc * jta * jpa

for example, jta, make a persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="NAME-WHAT-YOU-WANT" transaction-type="JTA">
    <provider>CLASS-OF-YOUR-PROVIDER</provider>
    <jta-data-source>YOUR-DATASOURCE</jta-data-source>
    <class>PATH-OF.GuestPreferences</class>
    <properties>
      <property name="NAME-OF-PROPERTY-TO-FORM-A-JDBC-URL" value="VALUE-OF-PROPERTY"/>
      <property name="NAME-OF-PROPERTY-TO-FORM-A-JDBC-URL" value="VALUE-OF-PROPERTY"/>
      <property name="NAME-OF-PROPERTY-TO-FORM-A-JDBC-URL" value="VALUE-OF-PROPERTY"/>
    </properties>
  </persistence-unit>
</persistence>

in a resources class you can declare:

@SuppressWarnings("unused")
   @Produces
   @PersistenceContext
   private EntityManager em;

then, you can use it in your GuestPreferences class:

@Inject
private EntityManager em;

em.getTransaction().begin();
Query query = em.createQuery("SELECT u FROM user_table u where u.iduser=:iduser");
query.setParameter("iduser", "THEME-USER-ID");
User resultUser = (User) query.getResultList();
em.getTransaction().commit();
if(User!=null){ 
   return resultUser.getTheme();
 }

code above assumes you have a table called user_table where a user has a iduser, name ..., and a theme column, and it assumes you have an object called User to manage users

jsf - How to save theme in Primefaces - Stack Overflow

jsf jsf-2 primefaces
Rectangle 27 1

On Primefaces 5.x (I'm using 5.1, but should work also on newer versions), you should be able to solve your issue by adding an ajax event related to contextMenu in the JSF page, as follows:

<p:ajax event="contextMenu" listener="#{profileSetEventController.onNodeSelectListener}" update="@([id$=btnPanel]) @([id$=dlgProfileSetEvent])" />

I tend to prefer this solution to the one already posted (the one that "overrides" the Primefaces onRightClick function) for three reasons.

First, there is no need to modify the Primefaces javascript (what if a newer version changes something about it? It's likely that, in this case, you have to modify your custom script!)

Second, you may want to separate the behavior of the listener onNodeSelectListener depending on which click (left or right) is fired by using e.isContextMenu() in the backing bean, so the controller may become something like:

public void onNodeSelectListener(NodeSelectEvent e) {
    if (e.isContextMenu()) {
      // right click has been fired
    } else {
      // left click has been fired
    }
}

The second parameter true in this.selectNode(d, true) of the Primefaces script nodeRightClick serves exactly this purpose. In other words, by using this.selectNode(d) (as the overriding script does), it will be not possible to decide whether the listener has been invoked by a left or a right click.

Last, you may want to use a different listener (onRightClickSelectListener) for the two events (select and contextMenu) in the JSF page, as follows:

<p:ajax event="select" listener="#{profileSetEventController.onNodeSelectListener}" update="@([id$=btnPanel]) @([id$=dlgProfileSetEvent])" />
<p:ajax event="contextMenu" listener="#{profileSetEventController.onRightClickSelectListener}" update="@([id$=btnPanel]) @([id$=dlgProfileSetEvent])" />

and consequentely in the backing bean, as:

public void onNodeSelectListener(NodeSelectEvent e) {
   // called when a select event occurs
}

public void onRightClickSelectListener(NodeSelectEvent e) {
  // called when a contextMenu event occurs
}

Therefore using a contextMenu event only for the right click, instead of using select event for both clicks, may be a cleaner approach anyway.

jsf - select event doesn't fire when right click on primefaces treenod...

jsf select primefaces tree contextmenu
Rectangle 27 20

The <h:head> is a JSF component which provides a hook to programmatically include JavaScript and CSS resources in the generated HTML <head>. PrimeFaces uses it to include the necessary JS/CSS code for the Ajax works and fancy look'n'feel.

As a test, create a page with a <h:head> and a PrimeFaces component, open the page in the webbrowser and check the generated HTML source by rightclick - View Source. You'll see that several JSF and PrimeFaces specific JS/CSS files are been added. Now replace <h:head> by <head> and check the generated HTML source once again, you'll see nothing this time.

jsf - What's the difference between and in Java Facele...

jsf facelets variant
Rectangle 27 20

The <h:head> is a JSF component which provides a hook to programmatically include JavaScript and CSS resources in the generated HTML <head>. PrimeFaces uses it to include the necessary JS/CSS code for the Ajax works and fancy look'n'feel.

As a test, create a page with a <h:head> and a PrimeFaces component, open the page in the webbrowser and check the generated HTML source by rightclick - View Source. You'll see that several JSF and PrimeFaces specific JS/CSS files are been added. Now replace <h:head> by <head> and check the generated HTML source once again, you'll see nothing this time.

jsf - What's the difference between and in Java Facele...

jsf facelets variant
Rectangle 27 12

This is a problem with the default way that Spring Security sends redirects back to the client. The default method of sending a redirect to the client is the HTML approach of sending a 302 Temporarily Moved response, however this does not work for AJAX clients. The AJAX client will interpret this as a redirect to a new location to post/get its data and not as a page redirect. The correct way to get the AJAX client to redirect the browser to a new page in the same way as a normal HTML request is:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<partial-response>
  <redirect url="http://your.url.here/"></redirect>
</partial-response>

To override the default invalid session strategy used by Spring Security, you need to create a SessionManagementFilter bean in your Spring config, and pass it a class that implements InvalidSessionStrategy and sends the correct redirect response when a request is received either via HTML or AJAX:

<bean id="sessionManagementFilter" class="org.springframework.security.web.session.SessionManagementFilter">
  <constructor-arg name="securityContextRepository" ref="httpSessionSecurityContextRepository" />
  <property name="invalidSessionStrategy">
    <bean class="yourpackage.JsfRedirectStrategy">
       <constructor-arg name="invalidSessionUrl" value="/your_session_expired_page.xhtml" />
    </bean>
  </property>
</bean>
<bean id="httpSessionSecurityContextRepository" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/>
<security:http use-expressions="true">
    <security:custom-filter ref="sessionManagementFilter" before="SESSION_MANAGEMENT_FILTER" />
    ...
</security:http>

The custom session management filter will now be created when your application starts, and the invalid session strategy class provided will execute whenever an expired session is found.

A good example of how to implement the invalid session strategy can be found here: https://gist.github.com/banterCZ/5160269

One note from my (successful) implementation of your answer here: Don't clear your cookies then trigger the ajax request as a way of testing this method! The new, session-less request isn't considered "invalid" the same way an expired session is!

jsf 2 - Redirect handling PrimeFaces Ajax requests on session timeout ...

ajax jsf-2 primefaces spring-security session-timeout