What is the correct way to bind input value to JSF managed bean property? - jsf

I am new to JSF and managed beans. I have a managed bean with some private property with public setter and Getter methods. Now when I add the managed bean's properties to JSF forms, should I add the private methods directly or should I use call the property by Getter methods?
For example:
<h:inputText value="#{BeanName.userName}"/>
<h:inputText value="#{BeanName.getUserName()}"/>
Which one is correct in above?

Assuming that you're using JBoss EL or EL 2.2+, both ways would work fine in the initial display. But the first one is actually more correct because the second one would only get the value, but never set the value. If you want to collect input values, you should always go for the first way. The EL (Expression Language) will then automatically locate the getUserName() and setUserName() methods whenever needed.
The second way will never work when you're using standard JSF EL implementation since it doesn't support direct method calls.
To learn more about JSF, start at our JSF wiki page.

If in your java class you have something like
....
private String coolStuff;
public String getCoolStuff() {
return coolStuff;
}
....
Then in your jsf page you access it like so:
#{myBackingBean.coolStuff}
The framework automatically looks for a method called getCoolStuff()
Hope that helps

number 1 is correct from above it is the private field that you connect if you are using EL with JSF in your form.
You still need the getter and the setter which the managed bean calls to get the values so you can save them in a database ....etc

Related

Can JSF be configured to not invoke Entity setter unless the field actually changed?

When a JSF form field is wired into an entity bean field (which is mapped to a DB field), each setter in the entity bean is called regardless of whether the user changed the form field value in the front end, i.e. the setters on unchanged fields are invoked the same as those that have changed but their new value is the same as the old value.
My question is simple: Is there a way to configure JSF to only call the setters mapped to the fields that have changed in the front end? The reason for this is that I have a requirement by which I have to detect deltas on every persist and log them, more about which can be read in this question.
Maybe I didn't understand you clearly, but why are you mapping directly your entity beans to a JSF view ?! IMHO it would be better if you add managed beans between your JSF pages and the entities in order to better separate your business logic from data access.
Any way, I think the easiest solution to impelement for that case is by making use of Value Change Events which are invoked "normally" after the Process Validations phase (unless you make use of the immediate attribute).
The good news about Value Change Events (regarding your example) is they are invoked ONLY after you force form submit using JavaScript or Command components AND the new value is different from the old value.
So, as an example on how to use value change listeners, you can add valueChangeListner attribute to each of your JSF tags like following:
<h:inputText id="input" value="#{someBean.someValue}"
valueChangeListener="#{someBean.valueChanged} />
Then, implement your valueChanged() method to look something like:
public void valueChanged(ValueChangeEvent event) {
// You can use event.getOldValue() and event.getNewValue() to get the old or the new value
}
Using the above implementation, may help you to separate your logging code (it will be included in the listeners) from your managed properties setters.
NB: Value Change Listeners may also be implemetend otherwise using the f:valueChangeListener Tag, but this is not the best choice for your example (you can find some examples in the section below, just in case)
See also:
Valuechangelistener Doubt in JSF
JSF 2 valueChangeListener example
When to use valueChangeListener or f:ajax listener?

adf managed bean retrieving a value from input text

I'm trying to retrieve a value from an input text in my jsf page, but when I change its value it doesn't change in the managed bean.
here's the input text:
<af:inputText label="Código:" id="codigo" value="#{tipoBaixaBean.codigo}"/>
and my managed bean is annotated like this:
#ManagedBean
#RequestScoped
public class TipoBaixaBean {
private long codigo;
I have the getters and setters, but the value of the property "codigo" never changes,
What would be the problem??
Thank you
Change your Bean scope to 'pageFlowScope' or 'viewScope' in adfc-config.xml . That should do.
You don't say when you are trying to get the value...on page submit or when you tab out of the field. If you want the value when you tab out (lose focus) then set the autoSubmit property on the input text field to true.
I would also suggest using a print statement in set method to make sure it's being called. The scope issue only arises if you are trying to retain the value between page requests.
Not sure how can you bind an inputText to a long object in backing bean.
Ideally it should be something like
private RichInputText codigo;
you can get the value of codigo using the getter.
getCodigo.inputValue();
I don't think scope will cause any problem. It works for the least life scope i.e. backing bean scope.
It really depends on the exact moment in which you are getting/setting the value, but if you need to do it automatically every time a change occurs, then you'll need to implement the Value Change Listener. Check this out: Value Change Listener example

JSF, EL, Managed Beans - How to tell what the getter & setter signatures are?

With JSF, Managed Beans, & EL 2.2 I know generally that an expression of the form:
#{bean.value}
Will map to a corresponding set of functions in a managed bean class like so:
#ManagedBean
class Bean {
private String value;
public String getValue() { return value; }
public void setValue( String s ) { value = s; }
}
It is also possible to get and set properties of a map:
#{bean.value['key']}
Backed by something like:
#ManagedBean
class Bean {
private Map<String, Boolean> kvMap;
public boolean getValue( String key ) { return kvMap.get( key ); }
public void setValue( String key, boolean value ) { kvMap.put( key, value ); }
}
So far so good.
I'm finding as I spend more time with JSF however that I'm trying to write reusable chunks of code. Specifically, small blocks of xhtml in <ui:composition> blocks that I can include via <ui:include>. What's more, many of the more useful things for me are things like nested sets of checkboxes (our UI designer is just gaga over them ;-), and there <ui:repeat> becomes very handy.
Invariably, in order to use <ui:repeat> and <ui:include> without an ungodly amount of typing, I've been using aliases, either created via <ui:param> or inline with something like the var attribute of <ui:repeat>.
As I've been writing more and more nested UIComponents, particularly things that get their values from maps within maps, I'm finding it harder and harder to deduce the correct setter method signature that JSF will look for when submitting a form (for some reason writing getters seems to be more natural).
My question for you gurus then is:
Is there some way to get JSF to tell me what it expects a setter signature to look like? Since JSF generally doesn't complain about an expression that resolves to a getter-only (thinking it is a read-only property), I find the lack of feedback frustrating and it seems to require a lot of fiddling with different method signatures before I finally hit that magic right one.
I'm hoping there's some technique, say a FacesContext... query at runtime or looking in some compiled intermediate like a class file that would point me to the correct setter signature for a deeply nested property. If there is such a thing I think it would save me a lot of time trying to figure out how to get a setter constructed by trial and error.
Hopefully I've articulated clearly enough what I'm after, thanks in advance for your replies.
I understand that your question basically boils down to "How should a setter for a Map look like?".
The answer is simple: you don't need any one. EL uses the put() method on the Map itself. You only need to provide a getter for the whole Map. On getting map values, EL will use the get() method of the Map itself. This is all behind the scenes done by the builtin MapELResolver.
So this should do:
#ManagedBean
class Bean {
private Map<String, Boolean> kvMap;
public Map<String, Boolean> getValue() { return kvMap; }
}
which is to be used as #{bean.value['key']} or #{bean.value.key} if the key doesn't contain periods. You can just use it in input components as well.
<h:selectBooleanCheckbox value="#{bean.value.key}" />
As to the tooling, well, the JBoss Tools plugin for Eclipse has good EL autocomplete support for normal javabeans, but it can't autocomplete map keys. Further Eclipse has its own facilities to autogenerate bean properties along with getters and setters based on a list or existing properties.

Basic question about backing beans for Composite Components

I can't find any guidance on this question. I am writing a composite component that needs its own backing bean because it interacts with a data base.
The new component also needs to be able to set a value in some other backing bean as the result of some user action.
To do this, the question is do I have to write a #FacesComponent java class or a regular #Model/#Named (I use CDI annotations) type of bean? If you can use either, what is the advantage of one or the other?
Secondary question: will I be able to use CDI #Inject into a #FacesComponent to get my DAOs and such?
Update: I discovered that I can access cc.attr objects with the following code in a regular backing bean:
FacesContext fc = FacesContext.getCurrentInstance();
Object obj = fc.getApplication().evaluateExpressionGet(fc,
"#{cc.attrs.model.location}", Location.class);
So this allows me to obtain attributes. I haven't found out how I can write them yet.
So it seems that the only real reason to do a #FacesComponent is if you want to write rendering code that will output something the normal Facelets tags won't render. Is this correct?
I think BalusC responded to this basic question in this thread.
The main advantage is the ability of a #FacesComponent to access attributes that a UIComponent normally has access to, rather than trying to tie in with EL expressions executed in the bean.

How to pass information between beans in JSF 2?

I have a scenario and dont have a clear idea for this to work yet.
Here's the example scenario :
I have a myView.xhtml file that can be displayed as a window popup or a primefaces dialog popup from 2 other container xhtml, let's say container1.xhtml and container2.xhtml (the myView.xhtml is included with something like this ? <ui:include src="myView.xhtml" />)
And, we also have the view-scoped beans, let's call them myViewBean, container1Bean and container2Bean
container1Bean has the property of transactionDate, and container2Bean has a property of transDate
myViewBean's #PostConstruct method will query the database based on a parameter of type date.
On container1.xhtml, if a user clicks on a button that will popup the myView.xhtml, container1Bean should be able to provide it's transactionDate to the myViewBean, and myViewBean will be able to query based on it in the #PostConstruct method.
On container2.xhtml, if a user clicks on a button that will popup the myView.xhtml, container2Bean should be able to provide it's transDate to the myViewBean, and myViewBean will be able to query based on it in the #PostConstruct method.
I was thinking about using #Inject Container1Bean and #Inject Container2Bean in the MyViewBean, so that inside MyViewBean, i can get the transactionDate of container1Bean or transDate of container2Bean. To decide which container bean is active is to check which one is not null.
But what if the container beans grows, there could be other container beans that make use of the MyViewBean, and the #Inject ContainerXXBean will grow in numbers inside the MyViewBean. There must be other solutions for this.
Please share ideas on how to accomplish this .. Thank you ! :-)
Thank you !
If you want to access only the contents of the other beans you can do that programmatic.
Get the current instance of the FacesContext inside from one bean. And using that context you can grab the instance of other beans.
See this illustration. As per the title of your question, you want to some information between beans. You can accomplish this by calling the other bean's public methods, which may be specifically created for this purpose. (setters-getters).
If container1Bean, myViewBean and container2Bean share some properties, why not putting them in a new bean ? (let's call it sharedBean, but I'm sure you'll find a better name adapted to your case). You could then inject sharedBean using #ManagedProperty in every dependent bean. Let's just try not to have circular references.
I'll also suggest to review your architecture. Are you sure you need all thoses beans, partitionned exactly like this? This sounds like something which will be difficult to maintain.

Resources