I'm using boolean switchers to resolve a choosed behaviour of application, for example SAVEACCEPTED enables SAVE button of form.
<h:commandButton action="#{bean.save}" disabled="#{!bean.saveaccepted}"开发者_开发知识库>
JSF need private boolean and its getters and setters, but if I want to resolve some internal logic in application server, it must be defined static. For example
IF (USERFOUND) SAVEACCEPTED = true;
So, I'm using settings class and there are public static booleans defined. And in the beans there are getters and setters pointing to the Settings.VARIABLE
Settings.java
public static boolean SAVEACCEPTED = false;
Bean.java
public static boolean isSaveAccepted() {
return Settings.SAVEACCEPTED;
}
Problem is, that the public boolean is only one and if more then one users using an application, when the first switch the variable, it affects second user form.
How can I solve this issue, is there some standard solution?
Don't use a static
variable. Use a @SessionScoped
or @ViewScoped
bean to store the settings separately for each user.
@Named
@SessionScoped
public class Settings
{
private boolean saveAccepted = false;
public boolean isSaveAccepted()
{
return saveAccepted;
}
public void setSaveAccepted(boolean saveAccepted)
{
this.saveAccepted = saveAccepted;
}
}
and
<h:commandButton action="#{bean.save}" disabled="#{!settings.saveaccepted}">
What if i'd need to set the saveAccepted = true in another bean (not in JSF)? It doesn't work, because in that case, saveAccepted have to be static.
Do not use a static variable.
If you need to set the value in another bean, you can @Inject
an instance:
@Named
@RequestScoped
public class SomeOtherBean
{
@Inject
private Settings settings;
public boolean getSaveAccepted()
{
return settings.getSaveAccepted();
}
public void setSaveAccepted(boolean saveAccepted)
{
settings.setSaveAccepted(saveAccepted);
}
}
and CDI will give you the right instance of Settings
.
BalusC comments:
Based on the question history, OP is using Tomcat which is just a simple servletcontainer.
Since it looks like you're not using a full Java EE 6 container, you can use @ManagedBean
instead of @Named
and @ManagedProperty
instead of @Inject
.
@ManagedBean
@RequestScoped
public class SomeOtherBean
{
@ManagedProperty
private Settings settings;
public boolean getSaveAccepted()
{
return settings.getSaveAccepted();
}
public void setSaveAccepted(boolean saveAccepted)
{
settings.setSaveAccepted(saveAccepted);
}
}
My apologies for sending you down a more complicated path!
Using static variable in this scenario is not ideal. Static fields by definition are shared across all instances of the class. So what is happening is the value you are storing are getting shared for all instances of your managed bean.
I recommend you save it at the request scope with @ViewScoped
or define it in the faces-config.xml with <managed-bean-scope>
.
精彩评论