PrimeFaces Wizard is not reset - jsf

We are using the PrimeFaces 4.0 + spring 4 on Tomcat 7.
I go to PrimeFaces show case, open the wizard, type first name and last name hit the next button. Then I select other menus from left panel ( like AutoComplete ) I go back to wizard the first name and last name fields are clear. That is what I expected.
I developed a wizard same as above but every time I come back to wizard page the wizard still holds the previously entered value and is not reset.
My managed bean is as below ( I have used ViewScoped no SessionScope which mentioned in documents):
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#Named
#ViewScoped
public class AccountController {
#Valid
private Account account = new Account()
//Setters and getters
}
Edited:
I found that the problem is for integration of JSF and Spring. When I remove the #Named and use #ManagedBean it works fine. Any comments?!

Spring does not have a built in support for JSF ViewScope, but you can add this scope to JSF as:
public class ViewScope implements Scope {
public Object get(String name, ObjectFactory<?> objectFactory) {
Map<String, Object> viewMap = FacesContext.getCurrentInstance()
.getViewRoot().getViewMap();
if (viewMap.containsKey(name)) {
return viewMap.get(name);
} else {
Object object = objectFactory.getObject();
viewMap.put(name, object);
return object;
}
}
public Object remove(String name) {
return FacesContext.getCurrentInstance().getViewRoot().getViewMap()
.remove(name);
}
public String getConversationId() {
return null;
}
public void registerDestructionCallback(String name, Runnable callback) {
// Not supported
}
public Object resolveContextualObject(String key) {
return null;
}
}
Please refer to http://blog.primefaces.org/?p=702
And in your applicationConetext.xml
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="utils.ViewScope" />
</entry>
</map>
</property>
</bean>
And finally:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#Named
#ViewScoped
#Scope("view")
public class AccountController {
#Valid
private Account account = new Account()
//Setters and getters
}

Related

p:inputSwitch doesn't work

I added an <p:inputSwitch> in my JSF page, but this is not working.
Get and set method is not called when I change the stat
The JSF page :
<p:inputSwitch value="#{SystemController.statSystem}" />
The managed bean
#ManagedBean
#ViewScoped
public class SystemController extends AbstractController implements Serializable {
private Boolean statSystem;
public Boolean getStatSystem() {
return statSystem;
}
public void setStatSystem(Boolean statSystem) {
this.statSystem=statSystem;
}
I added an ajax tag and it works ! Get and Set methods are working now.
<p:inputSwitch value="#{SystemController.statSystem}" >
<p:ajax />
</p:inputSwitch>
Your statSystem variable is not initialized.
Init like:
private Boolean statSystem = false;
or instead change data type to primitive:
private boolean statSystem;

ApplicationScoped Bean eager=true destroys when switching to different view

JSF2, Primefaces 3.3.FINAL, Spring
I have ApplicationScoped Bean for loading all dropdown data during start up of server. I referenced the same bean via ManagedProperty annotation. But when switching views the bean gets destroyed and i need to recreate the bean and data again.
Sample Code:
#ManagedBean(name = "refDataBean", eager = true)
#ApplicationScoped
public class RefDataBean extends AbsBackingBean implements Serializable{
....
#PostConstruct
public void init(){
//load multiple drop down data - populateData-db call
}
}
#ManagedBean(name = "searchViewBean")
#ViewScoped
public class SearchViewBean{
#ManagedProperty(value = "#{refDataBean}")
private RefDataBean refDataBean;
#PostConstruct
public void init() { //getUser object }
public User retrieveUser(User user) {
List<User> userList = refDataBean.getUserList();
}
public PICTSRefDataBean getPictsRefDataBean() {
return pictsRefDataBean;
}
public void setPictsRefDataBean(final PICTSRefDataBean pictsRefDataBean)
{ this.pictsRefDataBean = pictsRefDataBean; }
}
In one page/view, user.xhtml
<h:selectOneMenu value="#{searchViewBean.selectedUser}" >
<f:selectItems value="#{refDataBean.userList}" var="taskUser"
itemLabel="#{taskUser.fullNameAndId}"
itemValue="#{taskUser.networkLogin}"></f:selectItems>
</h:selectOneMenu>
When switching to another page, team.xhtml, the refDataBean is null and it goes to PostConstruct method of RefDataBean constructing the whole drop down list again. Since its a static data, i expect load it once and should be able to access in any page. I know that Objects in View scope are destroyed when you switch to a different view. How to restrict that? Or what am i missing? Please help

Pass a param from ManagedBean to jsf page

I am working with JSF 2.2 and Tomcat 8 and I am just starting to play with them.
I have a command button in a jsf page.
<h:commandButton id="newObject" value="New Object" action="#{someObject.someAction}">
<f:param name="object_id" value="#{someObject.object_id}" />
</h:commandButton>
The ManagedBean is similar to this:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
#ManagedBean
public class SomeObject implements Serializable{
private static final long serialVersionUID = 1L;
private int object_id;
public int getObject_id() {
return object_id;
}
public void setObject_id(int object_id) {
this.object_id = object_id;
}
public String someAction() {
setObject_id(sqlInsert());
if(getObject_id() != 0) {
System.out.println(getObject_id());
return "new_page";
}
}
}
The sqlInsert method is working fine. I use it to insert a new row in some sql table and get the auto generated key, which is an int. If the insert did not happen it would return 0.
I can navigate to the new_page, but the param object_id is 0. I added println to show the object_id and it is the actual key.
What am I doing wrong?
Since you are using the only #ManagedBean annotation on your Managed Bean and not specifying any Scope of you bean explicitly, your Bean will act as if its a #RequestScoped bean.[See link]
So every time you click your New Object button, the Bean is re initialized and you will loose the state(variable values).
Think and decide which scope you want to use [See link]. For your requirements #ViewScoped might do the job for you.

How to override CustomerStateRequestProcessor in broadleaf

How can I ovveride CustomerStateRequestProcessor#resolveAuthenticatedCustomer function in broadleaf?
I tried this:-
#Component("blCustomerStateRequestProcessor")
public class MyCustomerStateRequestProcessor extends
CustomerStateRequestProcessor {
#Resource(name = "blCustomerService")
protected CustomerService customerService;
#Override
public Customer resolveAuthenticatedCustomer(Authentication authentication) {
if (authentication instanceof OpenIDAuthenticationToken) {
OpenIDAuthenticationToken openIDAuthenticationToken = (OpenIDAuthenticationToken) authentication;
if (openIDAuthenticationToken.isAuthenticated()) {
return (Customer) openIDAuthenticationToken.getPrincipal();
} else {
return null;
}
} else {
return super.resolveAuthenticatedCustomer(authentication);
}
}
}
Added context component scan :-
<context:component-scan base-package="org.broadleafcommerce.common.web.security,com.mycompany.web.request.processor" />
This resulted in :-
org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'blCustomerStateRequestProcessor' for bean class [org.broadleafcommerce.profile.web.core.security.CustomerStateRequestProcessor] conflicts with existing, non-compatible bean definition of same name and class [com.mycompany.web.request.processor.MyCustomerStateRequestProcessor]
I am trying to overrid resolveAuthenticatedCustomer method for OpenIdAuthenticationToken.
Thanks
Rather than use component-scanning to redefine the bean, remove that annotation and do it via XML instead.
So your class definition would change to:
public class MyCustomerStateRequestProcessor extends
CustomerStateRequestProcessor {
...
}
And then in any of your applicationContext.xml files (except for the servlet one) add this:
<bean id="blCustomerStateRequestProcessor" class="com.yourcompany.site.web.MyCustomerStateRequestProcessor" />
Note that this pattern is the same for overriding any Broadleaf-defined beans.

How to save theme in Primefaces

I want to use Primefaces ThemeSwitcher. I'm interested how I can save the selected theme when I reload the web application. For example how I can set the theme name as variable from database?
You won't be needing the ThemeSwitcher to effect the kind of persistence you're looking for.
Simply perform the database lookup for the theme in a ServletContextListener and then store the value in the servlet context, possibly overriding whatever you've set in the web.xml
public Class MyContextListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent sce){
String selectedTheme = myThemeDAO.getConfiguredTheme();
sce.getServletContext().setInitParameter("primefaces.THEME",selectedTheme);
}
}
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
One more way to do this: include stylesheet to your pages template:
<h:body>
<h:outputStylesheet library="primefaces-#{themesBean.theme}" name="theme.css" /> </h:body>
Where #{themesBean.theme} variable reffers to name of your theme.
P.S. tested in PF5
I think setting selected theme in session would help:
session.setAttribute
Edit web.xml through code:
http://illegalargumentexception.blogspot.co.at/2008/08/java-using-xmlbeans-to-edit-webxml.html
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>EDITME</param-value>
</context-param>
Or create method before loading your page to choose the theme from db. (cleaner solution)

Resources