Saturday, June 3, 2006

Communication in JSF and Faces

This article shows how data travels in Jakarta Faces (formerly known as JSF): from the page to the bean and back, from one request to the next, and from one bean to another. It covers bean names and scopes, injection, implicit EL objects, normal and ajax forms, action method arguments, GET request parameters, component attributes, hidden values, the flash scope and servlets. It targets Faces 4.0 and newer. All examples were run on WildFly 39 with Mojarra 4.0. The differences for JSF 2.x, and the way it was done in JSF 1.x, are at the bottom.

Bean names

A backing bean is a CDI bean with @Named. Without a value, its name is the simple class name with the first character lowercased.

@Named
@RequestScoped
public class Bean {
    // ...
}

This bean is available in EL as #{bean}. Only specify a name, as in @Named("foo"), when it must differ from the class name. The @ManagedBean of the old javax.faces.bean package has been removed in Faces 4.0. It does not exist anymore.

As to naming conventions, Faces itself prescribes nothing. The Bean suffix is too vague: a JPA entity, an EJB and a DTO are all Javabeans as well. The ManagedBean suffix is long and technically wrong, as the class is the backing bean and only its instance is managed. Abbreviations such as MB and BB are unclear. What's left are a plain Foo, FooBacking, FooManager and FooController. I tend to use Manager for session and application scoped beans which are not tied to a form, and Backing for request and view scoped beans which are tied to a form, or just leave the suffix out. What matters most is that you are consistent throughout the project.

Need to know the name of the current bean inside the bean? Then the design is wrong. Use a subclass with its own @Named instead.

Bean scopes

The scope decides how long a bean instance lives and who shares it.

  • @RequestScoped of jakarta.enterprise.context: lives as long as one HTTP request, an ajax request included. Use it for plain GET pages, and for simple forms which need no state from the previous request.
  • @ViewScoped of jakarta.faces.view: lives as long as you interact with the same view by postbacks whose action returns null or void. Use it for ajax forms, data tables and anything with rendered or disabled attributes depending on earlier requests. It must be Serializable. Do not confuse it with the removed javax.faces.bean.ViewScoped.
  • @FlowScoped of jakarta.faces.flow: lives as long as a Faces flow, a set of views with a defined entry and exit, such as a wizard.
  • @ConversationScoped of jakarta.enterprise.context: lives until you end the Conversation yourself, or until it times out.
  • @ClientWindowScoped of jakarta.faces.lifecycle: lives as long as the browser tab, across views, for at most 10 tabs per session. It only works with the context parameter jakarta.faces.CLIENT_WINDOW_MODE set to url, uglifying every URL with a random jfwid parameter. A view scoped bean, a flash attribute or a GET parameter almost always does the job better.
  • @SessionScoped of jakarta.enterprise.context: lives as long as the HTTP session. Use it for data which can safely be shared among all browser tabs, such as the logged-in user and the chosen locale. It must be Serializable.
  • @ApplicationScoped of jakarta.enterprise.context: lives as long as the application. Use it for data which can safely be shared among all users, such as dropdown values loaded from the database, and for stateless services.
  • @Dependent: the default of CDI. The instance lives as long as the bean it is injected in. When referenced directly in EL, a new instance is created on every EL evaluation.

Choose the scope which fits the data. An application scoped bean holding user data shows it to all other users. A session scoped bean holding view data mixes up the data when the user works in two tabs. A request scoped bean holding view data loses it on every ajax request, and the form stops working. A view scoped bean holding request data works, but wastes server memory. When a bean holds data of two scopes, split it into two beans and inject the one in the other.

Injecting beans in each other

Use @Inject. Here is a session scoped bean holding the logged-in user.

@Named
@SessionScoped
public class ActiveUser implements Serializable {

    private String name;

    // +getter+setter
}

And here is a view scoped bean which needs it.

@Named
@ViewScoped
public class Products implements Serializable {

    @Inject
    private ActiveUser activeUser;

    @PostConstruct
    public void init() {
        // You can use activeUser here.
    }

    // ...
}

No getter or setter is needed for the injected field. Injected fields are not set yet in the constructor. The earliest point to use them is a @PostConstruct method. Its name is free to choose. The init() is just the canonical name, inherited from HttpServlet#init().

The scopes may be in any direction. You can just as well inject a request scoped bean into a session scoped one. CDI injects a proxy which delegates to the instance of the current request, session or view. This is also why there is no need anymore to obtain another bean via FacesContext, the request map, the session map, the ELResolver or a static getCurrentInstance() method. Just inject it. In the rare case where injection is not possible, such as in a class which is not a CDI bean, use CDI.current().select(ActiveUser.class).get().

Communication between beans

Injection lets one bean call another. When the bean which changes something should not need to know who is interested, fire a CDI event instead.

public record UserSaved(User user) {}
@Named
@RequestScoped
public class Profile {

    @Inject
    private ActiveUser activeUser;

    @Inject
    private Event<UserSaved> userSaved;

    private User user;

    public void save() {
        // ...
        userSaved.fire(new UserSaved(user));
    }

    // ...
}
@ApplicationScoped
public class AuditLog {

    public void onUserSaved(@Observes UserSaved event) {
        // ...
    }
}

The observer method is invoked synchronously, during the fire() call. Any bean can observe the event, in any scope whose context is active at that moment.

Injecting Faces artifacts

Faces artifacts can be injected as well.

@Inject
private FacesContext facesContext;

@Inject
private ExternalContext externalContext;

@Inject @RequestParameterMap
private Map<String, String> requestParameterMap;

@Inject @ManagedProperty("#{param.id}")
private String id;

The FacesContext, ExternalContext and @RequestParameterMap are proxies: in a view scoped bean they still give the ones of the current request. There are more of these, such as @SessionMap, @ViewMap, @HeaderMap and @InitParameterMap, all in the jakarta.faces.annotation package. The @ManagedProperty of jakarta.faces.annotation is different: it evaluates an EL expression once, when the bean is created. In a view scoped bean the field thus keeps the value of the first request, also on postbacks with a different id. For a request parameter in a view scoped bean, rather use <f:viewParam>, as shown in "GET request parameters".

Implicit EL objects

Next to the named beans, EL in Facelets knows these implicit objects.

  • #{component}: the current UIComponent. In plain template text, outside a component attribute, it is the parent component.
  • #{cc}: the current composite component.
  • #{facesContext}: the current FacesContext.
  • #{externalContext}: the current ExternalContext.
  • #{view}: the current UIViewRoot.
  • #{request}, #{session} and #{application}: the HttpServletRequest, HttpSession and ServletContext.
  • #{flash}: the Flash. See "From request to request".
  • #{requestScope}, #{viewScope}, #{sessionScope} and #{applicationScope}: the attribute maps of those scopes.
  • #{param} and #{paramValues}: the request parameters, as a single value and as an array.
  • #{header} and #{headerValues}: the request headers, as a single value and as an array.
  • #{cookie}: the request cookies, as a map of Cookie by name.
  • #{initParam}: the context parameters of web.xml.
  • #{resource}: the URL of a Faces resource.

The #{component} is the this of the view. A good example is styling an invalid input.

<h:inputText id="input1" value="#{bean.input1}" required="true" styleClass="#{component.valid ? '' : 'error'}" />

The #{resource} is mainly useful in a CSS file, to reference an image which is a Faces resource as well. The CSS file must then be included via <h:outputStylesheet>, otherwise its EL is not evaluated.

.logo {
    background-image: url("#{resource['images/logo.png']}");
}

EL can be put directly in template text, without <h:outputText>. Facelets escapes the HTML in it the same way.

<p>Welcome, #{activeUser.name}!</p>

You only need <h:outputText> for escape="false", or when you need a <span> with an id or styleClass. For an <h:outputText> with only a rendered attribute, rather use <ui:fragment rendered> around the template text. It renders nothing of its own and states the intent: show this part conditionally. It can also wrap any mix of template text and components at once.

<ui:fragment rendered="#{not empty activeUser.name}">
    <p>Welcome, #{activeUser.name}!</p>
</ui:fragment>

Implicit navigation

Navigation cases in faces-config.xml are considered legacy since the introduction of implicit navigation in JSF 2.0. An outcome is the view ID, without the extension. The <h:link> and <h:button> turn it into a GET link and a GET button, with the context path and the FacesServlet mapping included.

<h:link value="Home" outcome="home" />
<h:link value="Users" outcome="users" />
<h:button value="Contact" outcome="contact" />

Use GET links for page-to-page navigation, never command links. A POST form should stay on the same view and show its result there. When it must go elsewhere, return the outcome with ?faces-redirect=true, so that the browser address bar shows the new URL and a refresh does not submit the form again.

Normal POST form

This is a normal synchronous POST form. It is the start of the next few sections.

<!DOCTYPE html>
<html lang="en"
    xmlns:f="jakarta.faces.core"
    xmlns:h="jakarta.faces.html">
    <h:head>
        <title>Form</title>
    </h:head>
    <h:body>
        <h:form id="form">
            <h:panelGrid columns="3">
                <h:outputLabel for="input1" value="Input 1" />
                <h:inputText id="input1" value="#{bean.input1}" required="true" />
                <h:message id="input1Message" for="input1" />

                <h:outputLabel for="input2" value="Input 2" />
                <h:inputText id="input2" value="#{bean.input2}" required="true" />
                <h:message id="input2Message" for="input2" />

                <h:panelGroup />
                <h:commandButton id="submit" value="Submit" action="#{bean.submit}" />
                <h:messages id="messages" globalOnly="true" />
            </h:panelGrid>
        </h:form>
    </h:body>
</html>

And here is the bean.

@Named
@RequestScoped
public class Bean {

    @Inject
    private FacesContext context;

    private String input1;
    private String input2;

    public void submit() {
        context.addMessage(null, new FacesMessage("Submitted: input1=" + input1 + ", input2=" + input2));
    }

    // +getters+setters
}

An empty input field is submitted as an empty string. To get null in a String property instead, add this context parameter to web.xml. Other types, such as Long, are converted to null already. See also The empty String madness for the details.

<context-param>
    <param-name>jakarta.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
    <param-value>true</param-value>
</context-param>

Ajax POST form

To turn the form into an ajax form, add <f:ajax> to the command button.

<h:commandButton id="submit" value="Submit" action="#{bean.submit}">
    <f:ajax execute="@form" render="@form" />
</h:commandButton>

The execute attribute defaults to @this, the button itself. The inputs are then not processed at all. Hence the execute="@form". To process only some inputs, list them, separated by spaces, e.g. execute="@this input1". Keep the @this in there, otherwise the action of the button does not run.

The render attribute defaults to @none. The render="@form" renders the whole form again, so that the messages show up. You can also list just the message components: render="input1Message input2Message messages".

The event attribute defaults to action for a command component, which is a click on a button or link.

The page must use <h:head> instead of <head>. Otherwise the faces.js script, which does the ajax work, is not included.

Ajax validation

To validate an input as soon as the user leaves it, add <f:ajax> to the input and render its message.

<h:inputText id="input1" value="#{bean.input1}" required="true">
    <f:ajax event="blur" render="input1Message" />
</h:inputText>
<h:message id="input1Message" for="input1" />

The event attribute defaults to valueChange for an input component. That is the change event of a text input or dropdown, and the click event of a checkbox or radio button. However, the change event does not fire when you tab through an empty field without typing, so a required field is not validated. Hence the event="blur".

Put the bean of such a form in the view scope. A request scoped bean is created again on every ajax request, and loses everything set by the previous one.

@Named
@ViewScoped
public class Bean implements Serializable {
    // ...
}

Rendering outside the form

A render ID is resolved relative to the closest parent NamingContainer, such as <h:form>, <h:dataTable> and <ui:repeat>. Prefix the ID with : to resolve it from the view root.

<h:form id="form">
    <h:commandButton value="Submit" action="#{bean.submit}">
        <f:ajax render=":result" />
    </h:commandButton>
</h:form>
<h:outputText id="result" value="#{bean.result}" />

Mojarra 4 resolves a plain render="result" here as well. JSF 2.x however failed on it with "contains an unknown id". Always write the absolute ID. When the target sits in another naming container, the absolute ID includes the ID of that one too.

<h:form id="form">
    <h:commandButton value="Submit" action="#{bean.submit}">
        <f:ajax render=":otherForm:result" />
    </h:commandButton>
</h:form>
<h:form id="otherForm">
    <h:outputText id="result" value="#{bean.result}" />
</h:form>

When unsure, open the page in the browser and look at the generated HTML. The id of the element is the client ID, here otherForm:result. Prefix it with : and you have the absolute render ID.

Rendering another form

Rendering a part of the page which contains another form just works.

<h:panelGroup id="firstPanel">
    <h:form id="firstForm">
        <h:inputText id="input" value="#{bean1.input}" required="true" />
        <h:commandButton value="Submit" action="#{bean1.submit}">
            <f:ajax execute="@form" render="@form :secondPanel :messages" />
        </h:commandButton>
        <h:message for="input" />
    </h:form>
</h:panelGroup>
<h:panelGroup id="secondPanel">
    <h:form id="secondForm">
        <h:inputText id="input" value="#{bean2.input}" required="true" />
        <h:commandButton value="Submit" action="#{bean2.submit}">
            <f:ajax execute="@form" render="@form :firstPanel :messages" />
        </h:commandButton>
        <h:message for="input" />
    </h:form>
</h:panelGroup>
<h:messages id="messages" globalOnly="true" />

Up to JSF 2.2, the rendered form lost its hidden javax.faces.ViewState field, and its first submit did nothing. The workaround was to add the client ID of the other form itself to the render attribute, e.g. render="@form :secondPanel :secondForm". Since JSF 2.3, the ajax script adds the view state to every form in the view which needs it. The workaround is not needed anymore.

Rendering conditionally rendered content

The ajax script updates the HTML element with the ID which the server gives back. When that element was not in the HTML to begin with, there is nothing to update. This fails when #{bean.showResult} is false at first.

<h:form id="form">
    <h:commandButton value="Show" action="#{bean.toggle}">
        <f:ajax render=":result" />
    </h:commandButton>
</h:form>
<h:outputText id="result" value="#{bean.result}" rendered="#{bean.showResult}" />

Wrap it in a component which is always rendered, and render that one.

<h:form id="form">
    <h:commandButton value="Show" action="#{bean.toggle}">
        <f:ajax render=":result" />
    </h:commandButton>
</h:form>
<h:panelGroup id="result">
    <h:outputText value="#{bean.result}" rendered="#{bean.showResult}" />
</h:panelGroup>

Action method arguments

An action method can take arguments, and they can be any object.

<h:form>
    <h:dataTable value="#{users.list}" var="user">
        <h:column>#{user.name}</h:column>
        <h:column>
            <h:commandButton value="Edit" action="#{users.edit(user)}" />
        </h:column>
    </h:dataTable>
</h:form>
public void edit(User user) {
    // ...
}

The argument is evaluated when the action is invoked, not when the button is rendered. For the user of a table row this works because the table makes that row current again. The list must then still be the same as when the page was rendered. That is why Users is view scoped. See also Using datatables in JSF and Faces.

This replaces all the older ways. Each of them still works, and still has its niche.

The <f:param> adds a request parameter, as a string. It works in <h:commandLink> and <h:commandButton> alike.

<h:commandButton value="Edit" action="#{users.edit}">
    <f:param name="id" value="#{user.id}" />
</h:commandButton>
@Inject
private ExternalContext externalContext;

public void edit() {
    Long id = Long.valueOf(externalContext.getRequestParameterMap().get("id"));
    // ...
}

The <f:setPropertyActionListener> sets a bean property right before the action is invoked.

<h:commandButton value="Edit" action="#{users.edit}">
    <f:setPropertyActionListener target="#{users.selected}" value="#{user}" />
</h:commandButton>

The <f:attribute> sets an attribute on the component, which an action listener can read.

<h:commandButton value="Edit" actionListener="#{users.edit}">
    <f:attribute name="user" value="#{user}" />
</h:commandButton>
public void edit(ActionEvent event) {
    User user = (User) event.getComponent().getAttributes().get("user");
    // ...
}

GET request parameters

Here is a list of GET links, each with a request parameter.

<ul>
    <ui:repeat value="#{users.list}" var="user">
        <li>
            <h:link value="View #{user.name}" outcome="user">
                <f:param name="id" value="#{user.id}" />
            </h:link>
        </li>
    </ui:repeat>
</ul>

They end up as <a href="/contextname/user.xhtml?id=2">. In user.xhtml, the <f:viewParam> sets the parameter as a bean property, and the <f:viewAction> invokes a bean method once all view parameters are set.

<f:metadata>
    <f:viewParam name="id" value="#{userDetails.id}" />
    <f:viewAction action="#{userDetails.load}" />
</f:metadata>
<h:head>
    <title>User</title>
</h:head>
<h:body>
    <h:messages />
    <h:panelGrid columns="2" rendered="#{not empty userDetails.user}">
        Name <h:outputText value="#{userDetails.user.name}" />
        Email <h:outputText value="#{userDetails.user.email}" />
    </h:panelGrid>
</h:body>
@Named
@ViewScoped
public class UserDetails implements Serializable {

    @Inject
    private UserService userService;

    @Inject
    private FacesContext context;

    private Long id;
    private User user;

    public void load() {
        if (id == null) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Bad request. Please use a link from within the system.", null));
            return;
        }

        user = userService.find(id);

        if (user == null) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Bad request. Unknown user.", null));
        }
    }

    // +getters+setters
}

The <f:viewParam> converts the parameter to the type of the property, here Long. A value such as abc ends up as a conversion error in <h:messages>, and the property stays null. The <f:viewAction> runs on GET requests only. Add onPostback="true" to run it on postbacks as well.

The <f:viewParam> also works in a view scoped bean, unlike @ManagedProperty("#{param.id}"), which is evaluated only once. OmniFaces offers yet another way: the CDI annotation @Param injects a converted and validated request parameter straight into the bean, without anything in the view.

@Inject @Param(name = "id")
private User user;

Converting GET request parameters

The load() method above converts an ID to a User. That belongs in a converter.

@ApplicationScoped
@FacesConverter(forClass = User.class, managed = true)
public class UserConverter implements Converter<User> {

    @Inject
    private UserService userService;

    @Override
    public String getAsString(FacesContext context, UIComponent component, User user) {
        return user == null ? "" : String.valueOf(user.getId());
    }

    @Override
    public User getAsObject(FacesContext context, UIComponent component, String id) {
        if (id == null || id.isEmpty()) {
            return null;
        }

        try {
            User user = userService.find(Long.valueOf(id));

            if (user == null) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unknown user ID " + id, null));
            }

            return user;
        }
        catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid user ID " + id, null), e);
        }
    }
}

The managed = true lets CDI create the converter, so that @Inject and @EJB work in it. The same attribute exists on @FacesValidator. The converter must also be a CDI bean. With the default bean discovery mode annotated, the @FacesConverter alone is not enough for that, and the injected service stays null. Hence the @ApplicationScoped; the converter is stateless anyway.

The forClass makes Faces use the converter for every property of type User. The view gets much shorter.

<f:metadata>
    <f:viewParam name="id" value="#{userDetails.user}"
        required="true" requiredMessage="Bad request. Please use a link from within the system." />
</f:metadata>

And the bean only needs a user property. The id property and the load() method can go.

Component attributes

The <f:attribute> puts a custom attribute on any component. Everything which gets the component, such as a validator, a converter and a listener, can read it via getAttributes(). A classic use is a validator which compares two fields.

<h:inputSecret id="password" binding="#{password}" value="#{register.password}" required="true" />
<h:inputSecret id="confirm" required="true">
    <f:validator validatorId="confirmPasswordValidator" />
    <f:attribute name="password" value="#{password}" />
</h:inputSecret>
<h:message for="confirm" />
@FacesValidator("confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator<String> {

    @Override
    public void validate(FacesContext context, UIComponent component, String confirm) {
        UIInput password = (UIInput) component.getAttributes().get("password");

        if (confirm != null && !confirm.equals(password.getValue())) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Passwords do not match", null));
        }
    }
}

The binding="#{password}" puts the first component in the view under that name. Do not bind it to a bean property. Inputs are validated in the order of the view, so the first input has its converted value already. Pick an attribute name which is not already a property of the component, such as id, value or rendered. In the view itself the attributes are available as #{component.attributes.password}.

OmniFaces has ready-made multi-field validators, such as <o:validateEqual>.

Hidden values

A value which JavaScript sets in the page goes in a <h:inputHidden>.

<h:form id="form">
    <h:inputHidden id="hidden" value="#{bean.hidden}" />
    <h:commandButton value="Submit" action="#{bean.submit}"
        onclick="document.getElementById('form:hidden').value = 'bar';" />
</h:form>

JavaScript needs the client ID, which includes the ID of the form. A plain HTML hidden input works too. Its value is a request parameter, which you can read via the @RequestParameterMap or #{param}.

<input type="hidden" name="foo" value="bar" />

Do not use hidden inputs to carry bean state to the next request. A hidden value comes from the client and can be changed by the client. Put the state in a view scoped bean instead.

From request to request

Data needed by the next postback to the same view belongs in a view scoped bean. That covers most cases where JSF 1.x used <h:inputHidden> or Tomahawk's <t:saveState>.

Data needed by the next view after a redirect belongs in the flash scope. It survives exactly one redirect.

@Inject
private FacesContext context;

@Inject
private Flash flash;

public String save() {
    // ...
    flash.put("savedName", name);
    flash.setKeepMessages(true);
    context.addMessage(null, new FacesMessage("Saved " + name));
    return "result?faces-redirect=true";
}
<h:messages />
<p>Saved name: #{flash.savedName}</p>

The setKeepMessages(true) keeps the faces messages through the redirect as well. A refresh of the result page shows neither the name nor the message. Use #{flash.keep.savedName} to keep the value for the next request as well. Every request which reads it that way keeps it one request longer.

The bean of the result page can get the value from the injected Flash.

@Named
@RequestScoped
public class Result {

    @Inject
    private Flash flash;

    private String savedName;

    @PostConstruct
    public void init() {
        savedName = (String) flash.get("savedName");
    }

    // +getter
}

Call flash.keep("savedName") to keep the value for the next request as well. An @Inject @ManagedProperty("#{flash.savedName}") field does the same as the flash.get().

Data needed by all views of the user belongs in a session scoped bean. Data needed by all users belongs in an application scoped bean. Putting it in the session map or application map yourself is not needed anymore.

View scope and tag handlers

Tag handlers such as <c:if>, <c:forEach> and <ui:include src> run while the view is being built, not while it is being rendered. In JSF 2.0 and 2.1, a tag handler attribute referencing a view scoped bean created a new instance of that bean on every postback. This has been fixed since JSF 2.2, and in Mojarra 2.1.18. Choosing between a tag handler and the rendered attribute is still a matter of when the decision must be made: once when the view is built, or on every render. See also What exactly does the Jakarta Faces View State contain? for the details.

Servlets and filters

The FacesContext exists only in requests which go through the FacesServlet. In any other servlet and in a filter, FacesContext.getCurrentInstance() returns null. Do not try to create one yourself. To share data with a servlet or filter, inject the CDI bean instead.

@WebServlet("/report")
public class ReportServlet extends HttpServlet {

    @Inject
    private ActiveUser activeUser;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // You can use activeUser here.
    }
}

This works for request, session and application scoped beans. A view scoped bean does not work there: there is no view, and calling it throws a ContextNotActiveException.

JSF 2.x

Everything above works on JSF 2.3 as well, with these differences.

  • The packages are javax.* instead of jakarta.*, and the namespaces are http://xmlns.jcp.org/jsf/html and http://xmlns.jcp.org/jsf/core. The context parameter is javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL.
  • Injecting FacesContext and friends, @ManagedProperty of javax.faces.annotation and managed = true need a class annotated with @FacesConfig in the application.

On JSF 2.2 there is no injection of Faces artifacts and no managed = true. Get the FacesContext via FacesContext.getCurrentInstance(). For injection in a converter or validator, use OmniFaces, whose @FacesConverter and @FacesValidator classes support @Inject and @EJB. The CDI @ViewScoped of javax.faces.view exists since JSF 2.2.

On JSF 2.0 and 2.1 there is no CDI view scope. There you use the @ManagedBean and its scopes of the javax.faces.bean package, and @ManagedProperty("#{activeUser}") with a setter instead of @Inject. A managed property can only reference a bean of the same or a broader scope, so #{param.id} cannot be injected in a view scoped bean. The <f:viewAction> does not exist yet; use <f:event type="preRenderView">. Action method arguments need EL 2.2, which comes with Servlet 3.0, e.g. Tomcat 7. On Tomcat, also add the VM argument -Dorg.apache.el.parser.COERCE_TO_ZERO=false, otherwise empty inputs bound to a Long or Integer end up as 0.

JSF 1.x

JSF 1.x has no annotations, no view scope, no ajax and no EL method arguments. Managed beans were declared via <managed-bean> in faces-config.xml, and one bean was injected in another via <managed-property>. A GET parameter was set as a managed property with the value #{param.id}, which works on request scoped beans only. Action parameters were passed via <f:setPropertyActionListener>, <f:attribute> or <f:param>, as shown in "Action method arguments". Another bean was obtained via Application#evaluateExpressionGet(), or createValueBinding() on JSF 1.1. Data was kept for the next request in an <h:inputHidden>, a Tomahawk <t:saveState> or the session map.

146 comments:

Unknown said...

Thanks, fine article about parameters in JSF action calls. But you should add a note that commas in ths "attrvalue1" string causes lot of trouble.

Unknown said...

This section is one of the most referred section, during our development, which is in JSF. Thanks a lot for all your tips, and also to your posts in related topics in Sun's forum.

Cheers !!

Feba Mary

Gunjan Bohra said...

Thanks for this fine artical .
And thank for you effort on Sun forum ...

Successful said...

Thanks for the tips. One additional comment about "Accessing the FacesContext inside HttpServlet or Filter". This approach works great, but we found that if we were calling different servlets that used this approach, we need to call "context.release()" at the end of each servlet call. If you look at the source code in the FacesServlet, you can see the same approach is used.

Thanks,
Noah

Sandro Mancuso said...

Thank you very much for your article. It is very well written and helpful.
The best that I read so far about the topic.

Cheers.

Sandro

Unknown said...

Great article! Do you know of a way to pass parameters to the rendered attribute of an inputText or any other such field?

Cheers!

Bauke Scholtz said...

Use f:attribute. See the section "Passing component attributes from JSF to backing beans".

Unknown said...

Thanks for the VERY quick response. I think the problem is that rendered expects to see a property of a backing bean rather than a method call, thus there is no UIComponent being passed to the method, if I am correct. I believe "action" and "actionListener" behave differently, and execute a set method signature, whereas rendered only looks for a "getProperty" method with no args. I could be wrong, though...it's happened before...a few hundred times :)

Bauke Scholtz said...

That section actually demonstrates exactly what you need. In your specific case just replace the h:outputText by h:inputText, the HtmlOutputText by HtmlInputText, the value="" by rendered="" and public String getTextValue() by public boolean isRendered() -or so. Inside the isRendered() method, the attribute value is available to you the same way.

Unknown said...

Yes, you are correct. Thank you so much again! One more quick question, is there any way in said method (isRendered(), for example) to get a reference to the current element on which the rendered attribute method is being executed. I am trying to set up a generic enough security-related method that will not have to be written for each component. A daunting task, for sure. Again, thanks for all the help so far :)

demonm said...

Hello! I tried to adopt example with attributes to use it with dataTable, but had problems with null here. Maybe problem in using non-standard components, because I use ICEfaces (AJAX on background). I posted my problem on it support forum here
http://www.icefaces.org/JForum/posts/list/0/6520.page

Maybe somebody can help me with solution. Thanks in advance!

Bauke Scholtz said...

During the first time that the component binding getter is invoked, the attribute will indeed return null, simply because it is not set yet. Obtain the attribute in the action method or in the getter of the datalist.

Unknown said...

To begin with, thanks for the article and all your help at the Java Forums. I'm left with a doubt, though. Have you found any "tidy" ways to pass a collection from two beans in request scope?
As in <h:inputHidden id="items" value="#{myBean.myCollection}">

Thanks again and happy new year.

Bauke Scholtz said...

Nicolas: for non-String and non-Number typed objects you'll have to write a Converter or, in this case better, to use the RequestMap.

Unknown said...

Hi Balus. I've been trying your suggestion and focused on using the RequestMap. My problem is that the collection items are being passed from/to the same backing bean. In other words, I've got the same page in faces-context from-view-id and to-view-id. When filling values with requestMap.put(..) in that situation, I find that they're not loaded afterwards.
If this is the wrong place to be asking you questions, and you still want to help, you can reach me at gmail with username s.nico.zeitlin
Thanks again!

Anonymous said...

If I have session scoped beans what's the benefits using ELResolver to access another managed bean instead of using SessionMap?

Bauke Scholtz said...

The only benefit is that you don't need to specify the scope. If you ever change the scope in the faces-config.xml, you'll also have to change the codings.

Dimitri said...

Great article, i am looking to create a login based application therefore I have a request scope bean loginBean and within the login action create UserBean(usernane,pwd)which is session scoped. here begins my problem.. i am looking to use ajax push (icefaces)
http://www.icefaces.org/JForum/posts/list/4351.page
In this post they instruct to create a request scoped bean to update the PersistentFacesState of the session bean were do I inject this ...

NetFixUp said...

Great stuff...Thanks for all the work !!

I have a question.

When I use this:

((h:form))
((h:commandLink value="Click here" actionListener="#{myBean.action}"))
((f:attribute name="attributeName1" value="attributeValue1" /))
((f:attribute name="attributeName2" value="attributeValue2" /))
((/h:commandLink))

((h:commandButton value="Press here" actionListener="#{myBean.action}"))
((f:attribute name="attributeName1" value="attributeValue1" /))
((f:attribute name="attributeName2" value="attributeValue2" /))
((/h:commandButton))
((/h:form))



package mypackage;

import javax.faces.event.ActionEvent;

import net.balusc.util.FacesUtil;

public class MyBean {

// Actions -----------------------------------------------------------------------------------

public void action(ActionEvent event) {
String attributeName1 = FacesUtil.getActionAttribute(event, "attributeName1");
String attributeName2 = FacesUtil.getActionAttribute(event, "attributeName2");

System.out.println("attributeName1: " + attributeName1);
System.out.println("attributeName1: " + attributeName1);
}

}

-----------------------------

I am calling MyBean.Action.

Works great for passing value to bean from JSP. How do I use that bean Action to move to the next JSP page? Since it is a void and does not return anything for faces-config.xml to navigate??

Thanks
Phil

NetFixUp said...

Hey,

I fixed my issue..

thanks for your time.

Nohacks

Phil

harpreet said...

Thanks Baluc

It helped me great.
Awsome blog.


Harry

henry said...

Hi,

Just wanted to thank you for your blog.

While much of what is out there focuses on solutions to highly specialized esoteric problems which I probably won't ever encounter, your blog contains examples of how to solve and implement very simple and usable solutions.

This is extremely important. Keep the examples rolling. Nothing is ever too simple.

teste said...

Great!!! It saved my life!

Anonymous said...

I'm learning JSF from your blog and I noticed an interesting behavior when using f:setPropertyActionListner. It works great when passing in strings but if fails when I pass it a value expression (value expression does evaluate correctly). ex:

h:commandButton value="Press here" action="#{myBean.action}"
f:setPropertyActionListener target="#{myBean.propertyName1}" value="#{bean2.propertyValue1}"
...

have you noticed this from your experience?

Bauke Scholtz said...

Apparently bean2 is request scoped and the getter of its propertyValue1 returns null in the next request. Either put it in the session scope or use h:inputHidden to retain this value for the next request.

Anonymous said...

now i see the light!:) how did you become so good at jsf? what do you recommend I do to come up to speed? i'm currently reading your blog and writing a sample app so I can learn the framework.
Thanks.

牛仔 said...

Great article.
I've a question for pass parameter to backing bean.

<sql:query sql = "SELECT PLI_ITEM_NO,PLI_TRNH_LEN,PLI_TRNH_WID,PLI_TRNH_DEP FROM PLI_PLAN_ITEM WHERE PLI_PLAN_ID = ${pid} AND PLI_ITEM_NO = ${iid}" var = "itemresult" dataSource="${db}">
</sql:query>
<table id="ro-item" cellspacing="0" cellpadding="3" border="0">
<c:forEach var="itemrow" items="${itemresult.rows}">
<c:set var="irl" value="${itemrow.PLI_TRNH_LEN}"/>
<c:set var="irw" value="${itemrow.PLI_TRNH_WID}"/>
<c:set var="ird" value="${itemrow.PLI_TRNH_DEP}"/>
<tr><td>Length:</td*lt;
<td><h:inputText id="itemlength" value="#{irl}" size="6"></h:inputText>m</td></tr>
<tr><td>Width:</td>
<td><h:inputText id="itemwidth" value="#{irw}" size="6"></h:inputText>m
</td></tr>
<tr><td>Depth:</td>
<td><h:inputText id="itemdepth" value="#{ird}" size="6"></h:inputText>m</td></tr>
</c:forEach>
</table>
<h:commandButton id="submit" value="Submit" actionListener="#{planBean.action}">
<f:attribute name="attributeName1" value="attributeValue1" />
<f:attribute name="attributeName2" value="attributeValue2" />
</h:commandButton>

When user clicks the commandbutton, it will throw a NullPointException. I wonder why I can't pass the variable to the backing bean. Thank you in advance.

Anonymous said...

This is a fantastic article especially for JSF beginners like me. I have tried the samples and everything works great.
However I could not understand how I can specify what action should be executed if I provide the user with a url such as:

http://mycompany.com/product.jsp?product_id=123

How can I specify that the above link should execute MyBean.abcAction and if the result is “success” then user gets redirected to the product’s page otherwise to an error page?

I have the task of sending emails to users and in these emails I have to provide users with links to the latest products added to the database. In a pure JSP the link would look like the one above.

I am not sure if this can be done with commandButton or commandLink as they seem to use the session id which will be invalid in an email.

I would very much appreciate if somebody could help me with this.

Regards,
Byurhan

牛仔 said...

Sorry I made a mistake. Instead of <f:attribute name="attributeName1" value="attributeValue1" />
It should be <f:attribute name="attributeName1" value="#{irl}" />
Thank you.

dmanohar said...

Excellent article
so handy to refer

chandra shekar yeruva said...

hi Baluc can you please let me know how to pass value in input hidden.
My scenario as folllows..
I am getting some additional inforamtion from request and i need to get that info from request and need to pass to a bean to refer somewhere.how can i do that one.

h:inputHidden id="hidden value 1" value = "value got from servlet request."

how can i set the value "value got from servlet request" to a bean property.?

Can anyone help me on this I am a new guy to JSF.

Anonymous said...

Hi,

Great site. I've been able to use the posts on storing/accessing user objects in the various Faces contexts.

I have a JSF prototype application that is deployed in Tomcat 5.5. When using a browser that supports tabs connects to this application on more than one tab, I'm finding that the tabs seem to share a common JSF Session.

Is there a way to force different tabs to use different sessions?

If not, is there a technique for tracking when the user switches between browser tabs?

Thanks,
Charlie

Bauke Scholtz said...

There is not.

To solve your problem, keep the data in question request scoped instead of session scoped. You can use h:inputHidden or requestMap to transfer data from request to request.

Anonymous said...

Thanks. I was afraid that was going the be answer :-)

Irina said...

I have application that displays customer data in the table form. I don’t know the data structure in advance, so I came up with the following architecture:

I have report.jsp page that include reporttable.jsp or custom reportable.jsp

report.jsp
...
<f:subview id="invTable">
<jsp:include page="#{reportBean.tableJsp}"/>
</f:subview>
...


tableJsp string is pointed to /reporttable.jsp or /customer1/reporttable.jsp depending on the customer needs.

reporttable.jsp
...
<h:dataTable id="tableData" value="#{reportBean.reportData}" var="rpt" >
<c:forEach items="#{reportBean.columnNames}" var="name">
<h:column>
<f:facet name="header">
<h:outputText value="#{name}" />
</f:facet>
<h:outputText value="#{rpt[name]}"/>
</h:column>
</c:forEach>
</h:dataTable>
...


For the customer that need something different I create customer1Bean that will return customized reportDate

/customer1/reportable.jsp
It maybe different from the generic jsp, but also can be almost the same except the bean it calls
...
<h:dataTable id="tableData" value="#{customer1Bean.reportData}" var="rpt" >
...

I am wondering, if there is a way to call correct bean dynamically, so I don’t have to duplicate pages if they are the same.

I would appreciate any suggestions.
Irina.

Anonymous said...

Hi Irina,

Is it possible to have your list beans implement a common Java interface? Especially one that can support generic methods like:

Object getValue(String name) and
void setValue(String name, Object value)?

If so, it might be possible to stash the field (column) names in hidden inputs, and pass the values in as the 'name' argument.

I haven't actually tried this, but it seems like it has the potential to work.

Charlie

Raja Nagendra Kumar said...

This is Awsome knowlege on JSF.. Your insites into jsf programing is great..

Regards,
Raja Nagendra Kumar,
C.T.O
www.tejasoft.com

f0rsa said...

Hi first thanks for article..

Do you have any idea how to pass an h:inputText value as an attributes.I have try lots of thing but I couldn't manage .

Unknown said...

Thanks Balu,

I am facing one problem i am using ui:param tag when i included same jspx page in two diffrent jspx i am passing two diffrent parameters using ui:param , but problem is its always taking the first page parameters. its not taking the new parameters.

Unknown said...

This is the best article out of all articles i have seen.The information you provided is just like a guide for me in my JSF project.Thank u it's simply superb Balu.

Tom Dong said...

This is a very useful article. Thank you!

Anonymous said...

Passing new hidden values to backing beans: you have passed hardcoded value i want to pass the value which is set from javascript into a hidden field and also i dont want to use command button

Bauke Scholtz said...

@All: also not a commandLink? Then look for an Ajaxical solution. The value must be sent to the server side anyhow.

Anonymous said...

what I am doin is when a row is clicked. I call javascript function and set index of the row in hidden field h:inputHidden (I refered your code for UsingDataTables : HighlightRowsOnClick for this )
I have a commandlink on my page when a commandLink is clicked I call action in the action I want this index value which is now in Hidden Field on my JSF . Please can you tell me how to do that?

Anonymous said...

I have a Datatable. what I am doin is when a row is clicked. I call javascript function and set index of the clcicked row in hidden field h:inputHidden (I refered your code for UsingDataTables : HighlightRowsOnClick for this )
I have a commandlink on my page when a commandLink is clicked I call action.In the action I want this index value which is now in Hidden Field on my JSF . Please can you tell me how to retrieve the hidden field value to my backing bean?

ravi said...

Hi Balu,
Thank you very much for the JSF information that you have given us. It is very helpful.
I have small problem here, when I used the sessionmap to store my data in the session, for every request the size of the session variable is increasing tough I am using .remove method to remove vales from map. Can you suggest me the best way to store the objects in a session variable and which do not increase for every request.

Once again thanks for the article.

chamika deshan said...

Your articles are very helpful. Thank you very much!

munawar said...

Its informative article about JSF.
Thanks
Roshu

Unknown said...

thanks it is very practical.I had a question on "Passing GET Parameters From JSF To Backing Beans":
I had tried your method.there still is a limitation:
the backing bean being injected must be in a request scope
now the problem is: the backing bean's scope is "none",which is managed by another bean;and the backing bean is developeed by the third party,so I can give it a value using
"FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap() "( I can't change the backing bean's source code)
is there another way?

Bauke Scholtz said...

Create your own request scoped bean and make the bean with the 'none' scope a managed property of the request scoped bean. See 'Injecting beans in each other' section. Inside your own request scoped bean decorate (wrap) the setters of the bean with the 'none' scope.

Unknown said...

it is an good idea,and I wrap the none bean inside request bean and set setter to evaluate it.and make a configration in faces-config.xml.BUT the ONLY PROBLEM is:the request bean never got chance been invoked.so never send the value to the none bean before it is used!so the only way is still changed the code in none bean!but it is not editable if developed by third party.if you had email,i will send you and example by eclipse.thanks anyway.

Goethe-Ist-Taoist said...

Thanks for u great job. i have tried out: Passing GET parameters from JSF to backing beans

And this may have side effects, if
have more similar Backing-Beans for one page.
i.e: MyBean1 and MyBean2 may have the same structure.
GET-Parameters will be assigned to both beans, one of which may not wanted.

Unknown said...

hi ,
It is very great article to read. got my all answers from it. thanks fro it.

Varsha said...

I am running into a strange kind of problem with jsf. I have a web application has a main page, other jsf pages say page 1, page 2 and so on. Now from main page I go to Page 1, on page 1 there are some dynamically generated records and I can select any of those to go to Page 2.Page 2 has input text boxes showing the details of the selected record which can be changed. From Page 2 I can click a link to return to the main page. Now when I go to page 1 and then select any other record it shows me the value of the previously selected record in the text box of Page 2. On page 2 I have if I capture this using the outputText I get the values of the currently selected record from the bean. Looks like get method is not being called for the input text box. Any help on this would be greatly appreciated.

Pranayaa said...

A good article.
I have one superclass and multiple subclasses. Superclass and subclasses are managed beans.
Super class has few variables.
In my JSF I called superclass bean to get the values for the components. Based on user action I will call any one of the subclass bean. I got a NULL POINTER EXCEPTION while accessing a variable which is declared in super class because both managed bean altogether is different.
But how can I access the value which is assigend to a super class bean variable from sub class bean?

Code:
Super class:
public class GrantingBaseAction{
protected SLEGeographyValue grantingGeographyValue = new SLEGeographyValue();
protected GrantingGeographyCriteriaValue geographyCriteriaValue = new GrantingGeographyCriteriaValue();

public SLEGeographyValue getGrantingGeographyValue() {
return grantingGeographyValue;
}

public void setGrantingGeographyValue(SLEGeographyValue grantingGeographyValue) {
this.grantingGeographyValue = grantingGeographyValue;
}
public GrantingGeographyCriteriaValue getGeographyCriteriaValue() {
return geographyCriteriaValue;
}

public void setGeographyCriteriaValue(
GrantingGeographyCriteriaValue geographyCriteriaValue) {
this.geographyCriteriaValue = geographyCriteriaValue;
}
}

Subclass
--------
public class GrantingMNCAction extends GrantingBaseAction {
public String globalExpand() throws Exception {
for (SLEMarketValue marketValue : grantingGeographyValue.getMarketList()) {
//Somoe action

}

return null;
}

In this class while accessing grantingGeographyValue, i received Nullpointer Exception.

How to resolve this?

Bauke Scholtz said...

You declared them as two separate beans, did you? That's not the way how super/subclassing works.

Just inject the one bean in the other as managed property.

Pranayaa said...

I declared them as two separate beans. But how can I use the property of first bean from second bean? (Since the property is also accessed from sub class bean.

Bauke Scholtz said...

Read the "Injecting managed beans in each other", "Accessing another managed bean" and/or "Returning current managed bean instance of self" parts of this article.

It's a huge misunderstanding that an instance of a certain subclass would "automagically" be merged with a random instance of its superclass. That's not how Java works.

Atul Singhal said...

Thanks Baluc for this article. It really helped in our development.

I am facing one problem while developing the web application in JSF and not getting the solution how to handle it.

Problem Description:

1. Each web page is divided in two parts left navigation and content.
2. In the left navigation we have links which are linked to the content pages.
3. Those content pages containing some sort of form having some input text fields
4. Now, user clicked on, say Link1 in the left navigation linked "xhtml page" is openend in the content area and now user input some values in the text field and clicked on other link "say Link2" then how to populate popup having choice either move or cancel. if move then the Link2 page should get displayed else will remain on the same page.

can you please provide some workaround of this?

Thanks in advance.

Bauke Scholtz said...

This goes beyond the scope of JSF. You need to control it at the client side. Javascript is suitable for this. Best what you can do is to make use of the onbeforeunload event. Most recent webbrowsers expect of Opera supports it.

Are You Special Out Here said...

hi BalusC , really a nice job , thaks for nice and informative articles

I am very new to JSF working in JDevloper IDE.

I want to access some value passed to JSF page as query string in its back bean class

my URL is like this for calling JSF page form some html pg is somewhat like this "http://127.0.0.1:7101/m-CA-ViewController-context-root/faces/BMsg.jspx?recID=12"

I want to access it my back bean mthd I am doing it as ..
but it always return a null value

public class BMsg {

// ....

public String retRecID()
throws IOException {
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest req=(HttpServletRequest)ectx.getRequest();
String s=req.getParameter("recID");

return s;

}

}

can u please make me correct or suggest me anything , thanks in advance..

Bauke Scholtz said...

This bit is already explained here: Passing GET parameters from JSF to backing beans. Good luck.

Mr President said...

This is really great stuff. Extremely thorough. Thanks for sharing!

Milos said...

This is so classy!
thank you

Mirco Attocchi said...

Thanks!!

andy said...

I was struggling to find how to do all this !!! thnx !

Srinivas Chunduru said...

Hi, thanks for giving this information about JSF , and i want some code to transfor data or attributes between one JSF page to another JSF page that means if i entered any value(in inputText) in one JSF page,that value should display in the second JSF page, can u please help me

Bauke Scholtz said...

Use a managed bean.

Srinivas Chunduru said...

hi, thanks for giving this information, and i want some code, if i enter any value in one JSF page that must be displayed in second JSF page with out using the bean, can any one please help me

Bauke Scholtz said...

If you don't want to use a managed bean, then why JSF? Go for plain vanilla JSP/Servlet if you don't want to use beans.

Jaimico said...

Hello BalusC:

Excelent article, thanks!!

In a response to another comment you wrote: Apparently bean2 is request scoped and the getter of its propertyValue1 returns null in the next request. Either put it in the session scope or use h:inputHidden to retain this value for the next request

I tried that and it works when going from page1 to page2 (which also have the hidden inputs), but while going to page2 to page3 I get the following error:

javax.el.PropertyNotFoundException: Target Unreachable, 'concesion' returned null

(concesion is an atribute of the request managed bean, it is an object -kind of big- and I have the converter for it)

Is it recommended to pass the object in hidden fields?, if so, can you point me to a good tutorial or best practices lectures for passing entire objects from request to request?

In another response you recommended to use RequestMap, is in my case also recommended? Because I feel that using it can cause me problems of loading incorrect objects if the user clicks de back browser button.

Thanks in advance!!!! :)

Bauke Scholtz said...

Instead of h:inputHidden you can also use Tomahawk's t:saveState. This component doesn't require a converter for non-standard types. You can even cache complete beans for the next request.

Jaimico said...

Thanks for your help BalausC, it worked perfectly...

I had some problems because objects needed to be serialized... and some objects contain ImpuStream's, but following instructions on this page (http://oreilly.com/catalog/javarmi/chapter/ch10.html) helped me to solve it.

But I ended up with havy posts and Glassfish complaining of "Post too large", I found that adding %<property name="maxPostSize" value="...."/> to the domain.xml (inside http-service) could solve the problem... but I dont know if it's recommended to send too large post (some of my objects have pdf files).

Perhaps I should use the RequestMap, does it last only for one request or do I have to use something else?

Thanks!!!

Bauke Scholtz said...

Ouch, InputStreams .. I'd rather to keep them where they belong (filesystem or database) and use some ID to associate with them so that it can be re-retrieved again.

Jaimico said...

You're right BalusC, I'll keep them on Data Base and retrieve them only when needed =P.

Thank you very much for your help!!!! I'll be keeping an eye on your blogs.

TC Flyers said...

coooooooooooooool, wonderful article, I really appreciate this work.
Bravo

Thomas said...

Thanks for great article!

Unknown said...

Hi BalusC,

Is there a way to call Bean method through outputlink in JSF

Cheers,
manas

Bauke Scholtz said...

The constructor and -if any- the managed property setter will be invoked. Just make use of it.

Unknown said...

Passing objects from request to request

If you have a request scoped managed bean and you want to reuse a property, parameter and/or object for the next request, without reinitializing it again and again, then just use the h:inputhidden tag to save the object in it. Here is a basic JSF example:


Great Page BalusC..

I have a question. I want to put the whole request bean back into the request. I see that I can use a hidden field on the JSP page for one field but what about the whole bean?

I am using a request bean to hold the search parms that loads the bean. This works great.

The problem is when I use the rich:datascroller for the next page.
It goes back to the bean and the request scope bean is empty. This holds the search values.

How do I put this back into the request after each process??

Thanks
Phil

Bauke Scholtz said...

Use a4j:keepAlive.

Unknown said...

Works Great !!!!

a4j:keepAlive beanName = "SearchFormBean"/


Thanks again this will help keep memory requirements down with less session beans. Also it works correctly..!!


Thanks
Phil

oneironaut-art said...

Thanks, this was so helpful!

Marcel said...

Great article and blog.
I'm just starting to learn JSF and I was wondering if you can provide a little advice.

I want to create a component that will present a bunch of different images that would need to be provided to the component as inputs along with some presentation configuration attributes (what transitions to apply, transition durations, etc).

Would the standard approach to do this be:

i:imageComponent imageUrls="http://imageUrl1,http://imageUrl2" etc

or

i: imageComponent
i: image url="http://imageUrl1" width="480" height="320"
i: image url="http://imageUrl2"
i: imageComponent

The second approach seems more flexible but in my case it's the imageComponent that would do all the rendering work so I'm just looking for the standard way to pass in a list of inputs to a component. I hope you can understand this without the tags - they don't seem to be allowed in comments

Bauke Scholtz said...

Create a bean representing the image details. Have a List of beans, use t:dataList to iterate over it and apply the bean properties on the h:graphicImage.

Firat said...

excellent solution. thanks a lot.

பாà®°்த்தசாரதி செல்லதுà®°ை said...

very useful information relate to JSF r there. This is very useful for me.

Jalead said...

Thanks for sharing such great information about JSF.

I found it very useful. It really helped to get the most out of the topic.

Cheers!

Waheed said...

Its very good article

my question is that i not found this class,
import net.balusc.util.FacesUtil;

it syor ownclass or its a jsf class?

Trevor said...

I'm working on master-detail pages in a JSF 1.1 portal environment and just figured out a variation of "Passing GET parameters from JSF to backing beans" that I thought I'd share.

The code under "Passing GET parameters from JSF to backing beans" didn't work for me. I think the reason is because the JSF navigation handler is always doing a redirect. Replacing or reconfiguring the navigation handler was not an option, nor was upgrading to JSF 1.2 or 2.0.

The solution I came up with was to create a class called ParameterHelper with an action handler called 'forward'. When this executes it grabs all the parameters from the request and sets them on the next request, effectively getting around the problem of parameters existing when the form submit is processed, but disappearing by the time the next page loads.

The code for this is:

import java.util.Iterator;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.portlet.ActionResponse;

public class ParameterHelper
{
public void forward(ActionEvent event)
{
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
Map parameters = context.getRequestParameterMap();
ActionResponse response = (ActionResponse) context.getResponse();

for (Iterator iter = parameters.keySet().iterator(); iter.hasNext(); )
{
String name = (String) iter.next();
Object value = parameters.get(name);

if (value != null)
{
response.setRenderParameter(name, value.toString());
}
}
}
}

The backing bean has its properties set in the same way as described in "Passing GET parameters from JSF to backing beans" by using the #{param.parameterName1} syntax.

The only addition is that the h:commandLink must have an 'actionListener' attribute which points to the 'forward' method of the ParameterHelper class.

<h:commandLink action="edit" value="Edit" actionListener="#{parameters.forward}">
<f:param name="id" value="#{row['id']}" />
</h:commandLink>

With this solution, master-detail pages can be created under JSF 1.1 without putting backing beans in session scope. Hope this helps someone.

Unknown said...

Thanks for the great article. this was the most referred article by me for JSF.

Currently im having trouble passing the EL as value in "f:attribute "

e.g: f:attribute name="testName" value="#{bean.attr}"

im getting null from event.getComponent().getAttributes().get("testName");

If facelets tag is compile time is there any other way of acheiving this. Any Ideas?

Bauke Scholtz said...

Then its getter didn't return the desired value at the desired moment.

Philip said...

Hi BalusC,

Would you know if is possible to retrieve the current id of a component from a deferred el expression.

[a4j:commandButton]

[h:inputHidden value="#{testAction.saveId( somehowgetIDOfParentComponent )}" /]

[/a4j:commandButton]

in the above example I am looking for the id of the a4j:commandButton.

Anonymous said...

in jsf 1.1, I'm handling the required and conversion errors automatically and overriding the messages for required and conversion errors in a .properties file, however, I want to display the name of the field that generated the error in the error message, I tried using the {0} but searching the internet I found it's not possible with jsf 1.1 , any advice on how to accomplish this when forced to use jsf 1.1 ?

Anonymous said...

thank you in advance and sorry it's a little off-topic

Unknown said...

Hi BalusC,

Thanks very much for this wonderful article
I have a question regarding managed property. I have a managed property called accountID(int) which i set in my faces-config.xml . but when i access it in my backing bean it gives me zero. Not sure where i have gone wrong. My URL : http://localhost:8080/for/adminbean.jsp?accountID=123

Here is my code:

In my backing Bean i want to load adminbean object and display its details on screen. Since the loading can happen only after the bean construction i have a lazy loading in the bean getter method
public class AdminController {


private Integer accountID;
private AdminBean adminbean;
public AdminController (){


}

public Integer getAccountID(){
return accountID;
}

public void setAccountID(Integer accountID) {
this.accountID = accountID;
}

//Load the admin bean
public AdminBean getAdminbean(){
if(adminbean==null){
try {
loadAdminBeanInfo();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return this.adminbean;
return accountID;
}

public void setAdminbean(AdminBean adminbean) {
this.adminbean = adminbean;
}


public void loadAdminBeanInfo(){

System.out.println("Account data"+this.getAccountID());

}




}


So in the load if i print accountID it gives me zero instead of 123. Please advise.

Thank you

Bauke Scholtz said...

You already have posted the question at the sun forum before.

Tamás said...

Hi BalusC,

This page is an excellent guide, thanks for that.

I'd like to ask you a question:
I'm developing an application using Icefaces on Liferay. I have one controller bean in request scope, and a few managedbeans registered in session scope. I have two pages. One creates a list, following a link from that list another page opens containing detailed data. My problem happens when the second page opens: sometimes (it's non-deterministic for me now) the values get re-set after the page opens correctly. Sometimes they don't get re-set, and then it's fine. This holds true only for the selectOneMenu or selectOneRadio elements. The selected values of these are set correctly at first, but then they are re-set to default. This re-setting can even be seen on the page in case of the radio list. Input boxes work just fine.

Do you have any idea what could be causing this? I already tried different icefaces versions (1.7.0, 1.8.2), tried to replace the value="#.." with binding="#.." - no luck so far. Also, I couldn't really find relevant threads in other forums.

Thanks in advance.

Unknown said...

@BalusC: I used your context.getApplication().evaluateExpressionGet but I got this error: class file for javax.el.ELException not found. I have Tomcat 6.0.20 and Mojarra JSF 1.2_13-b01-FCS. What class am I missing?

MRUTTUNJAYA said...

Thanks a lot for ur article ,, thank you very much

Jose said...

Hi,

I am going to introduce my code,














































and it does not work. On Luke said (April 1, 2008 7:14 AM) I know I have to pass the value of the inputText tag instead of its id, but anyway it does not work.

What is going on?

Thanks for your greatfull blog.

Jose said...

Here is my code. I do not know what was wrong.

This is my idea: for the inputtext tags I pass the values of a Customer that is a property of the backing bean
The method details lists the properties of Customer. And what I need is to get in the commandButton tag update
those values even if some of them are new values.

((h:form))
((h:panelGrid columns="2" bgcolor="#eff5fa"))

((h:outputLabel value="Customer ID:"/))
((h:inputText id="customerId" value="#{customer.details.customerId}" disabled="true"/))
((h:outputLabel value="Customer Name:"/))
((h:inputText id="customerName" value="#{customer.details.name}"/))
((h:outputLabel value="Credit Limit:"/))
((h:inputText id="creditLimit" value="#{customer.details.creditLimit}"/))
((h:outputLabel value="Discount Code"/))
((h:selectOneMenu id="discountCode" value="#{customer.details.discount}"))
((f:selectItems value="#{customer.discountCodes}"/))
((/h:selectOneMenu))((h:outputLabel value="Email:"/))((h:inputText id="email" value="#{customer.details.email}"/))((h:outputLabel value="Phone:"/))((h:inputText id="phone" value="#{customer.details.phone}"/))((h:outputLabel value="Fax:"/))((h:inputText id="fax" value="#{customer.details.fax}"/))
((h:outputLabel value="Address (Line 1):"/))
((h:inputText id="address1" value="#{customer.details.addressline1}"/))((h:outputLabel value="Address (Line 2):"/))
((h:inputText id="address2" value="#{customer.details.addressline2}"/))((h:outputLabel value="State:"/))((h:inputText id="state" value="#{customer.details.state}"/))((h:outputLabel value="City:"/))((h:inputText id="city" value="#{customer.details.city}"/))((h:outputLabel value="Zip:"/>
((h:inputText id="zip" value="#{customer.details.zip.zipCode}"/))((/h:panelGrid))
((h:commandButton id="back" value="Back" action="#{customer.list}"/))
((h:commandButton id="update" value="Update" actionListener="#{customer.update}"))
((f:attribute name="attName" value="#{customer.details.name}" /))
((f:attribute name="attCreditLimit" value="#{customer.details.creditLimit}" /))
((f:attribute name="attDiscountCode" value="#{customer.details.discountCode.discountCode}" /))
((f:attribute name="attEmail" value="#{customer.details.email}" /))
((f:attribute name="attPhone" value="#{customer.details.phone}" /))
((f:attribute name="attFax" value="#{customer.details.fax}" /))
((f:attribute name="attAddressline1" value="#{customer.details.addressline1}" /))
((f:attribute name="attAddressline2" value="#{customer.details.addressline2}" /))
((f:attribute name="attState" value="#{customer.details.state}" /))
((f:attribute name="attCity" value="#{customer.details.city}" /))
((f:attribute name="attZip" value="#{customer.details.zip.zipCode}" /))
((/h:commandButton))
((/h:form))


Thanks in advance

Unknown said...

Hi,

How to know javascript enabled or not on server side on pagerefresh in JSF?

Cheers,
Manas

Phoenic said...

Thank u very much BalusC C:

sandip said...

When onbeforeunload fires I am opening confirmation popup to ask user if he want to navigate to other page.
If user click 'ok', hidden field hdnUserSelection assigned a value 'yes'.
If user click 'cancel', hidden field hdnUserSelection assigned a value 'no'.


In filter I am doing
String userselection = request.getParameter('hdnUserSelection');

Here for userselection, I am always getting null.

Can you please help ?

Abhishek Dhote said...

Hi BalusC, Thanks for the useful tutorial on JSF, it helps me a lot!

Abhishek Dhote said...

Hi Balusc, I wanna use f:param with h:commandButton. I read your atricle about f:param with h:commandButton but I cannot use the same, so can you help?
Regards,
Abhi

Bauke Scholtz said...

As stated in the article, use f:attribute.

Abhishek Dhote said...

Thanks for the prompt response!
Actully my problem is on the button click on want the url like shown below:

http://localhost/MyPage.jsf?paramName=paramValue

is there any way we can achieve this!

Bauke Scholtz said...

Use CSS to make link look like a button.

Jigar said...

Hey,
i want to handle an event when context gets initilized,

so i have


import javax.faces.context.FacesContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyApplicationContextListener implements ServletContextListener {


DataBean var;

public MyApplicationContextListener() {
}

public DataBean getVar() {
return var;
}

public void setVar(DataBean var) {
this.var = var;
}

public void contextInitialized(ServletContextEvent event) {
System.out.println("contextInitialized >>>>>>>>>>>>>>>>>>>"+ var);
System.out.println("" + findBean("bookBean", DataBean.class));
}

public void contextDestroyed(ServletContextEvent event) {
System.out.println("contextDestroyed >>>>>>>>>>>>>>>>>>>>>>>");
}

public static T findBean(String managedBeanName, Class beanClass) {
FacesContext context = FacesContext.getCurrentInstance();
return beanClass.cast(context.getApplication().evaluateExpressionGet(context, "#{" + managedBeanName + "}", beanClass));
}
}











PhaseTracker




bookBean
DataBean
session


myApplicationContextListener
MyApplicationContextListener
application

var
#{bookBean}






but @ initilization of context in
context initilied method i am getting 'var' as null

Bauke Scholtz said...

Create bean yourself and put it in application scope.

Anonymous said...

Thanks BalusC!!!
For all the efforts!

Unknown said...

Hi BalusC

You should write and publish a book about all these JSF knowledge. Is really the most comprehensive and accurate Java/JSF information source.

Thanks.

Martin

Picanha said...

Thanks. Well written, organized, and very very useful.

Cheers!

BiBoN said...

Great article! Thanks!!

taysay said...

BalusC you are simply a blessing. Tanx for your invaluable gift . May God crown your every effort with absolute success.

Anonymous said...

hi,
i need to communicate managed beans but i must do it in JSF 2.0.

I like your way to injecting managed beans in each other using faces-config.xml

but

is it appropriate to use a faces-config.xml?

can you advise an other smart way without using facesContext, i hate it.

thanks for any respond

Bauke Scholtz said...

@mervet, use @ManagedProperty annotation.

See also bottom of this stackoverflow answer for an overview how to convert faces-config to the new JSF 2.0 annotations.

Unknown said...

Wonderful article and it has come in very handy, in fact all of your writings are bookmarked on most of our developers browsers. I am using sessionMap to keep variables that are needed from request to request and then clearing when done. We were using processScope when we used ADF which was simple because in your pages you could reference #{ProcessScope.variable} for both input and output but we are trying to move away from ADF. Is there a simple way to display the value of a specific entity in the session map on a JSF page without having to create a method in the managedBean to drill down into FacesContext?

Bauke Scholtz said...

Just referencing the session map key in EL like #{key} ought to be sufficient. If you however want to explicitly reference in the session scope because you've another object on the same key in the request scope (the search order for EL is request-session-application), then use`#{sessionScope.key}.

Unknown said...

Thanks and keep up the good work!

llazzeri said...

Hi BalusC, I need a suggestion.
I made a page reachable via a url having in the query string the ID of the product to show. The backing bean has properties whose getter method uses the product ID to read the db. In the page there is a form to place an order and when I submit it, the view is restored but the product ID is null and the getter methods fail. This happen even if I save the bean in view scope. Why? Isn't the same view? It works fine only if I save the bean in session scope. But here I need a suggestion on how to clear the session of unused beans...

Bauke Scholtz said...

@Livio: use <f:viewParam>. Assuming that you have an URL like product.jsf?id=123 and a managed bean "Products" with a property "id" (with setter), then add the following to the view to set it from the param:

<f:metadata>
    <f:viewParam name="id" value="#{products.id}" />
</f:metadata>

You can then do the database action in a @PostConstruct method.

@PostConstruct
public void init() {
product = productDAO.find(id);
}

Anonymous said...

Excellent information, it just saved me a whole bunch of time and frustration!

Unknown said...

Hey BalusC, small world this one :) This morning on stackOverflow, now here :D

Nice article, quite complete and helpful!

Thanks again!

Almir Campos (Zona8) said...

Very nice article! It helped me so much!

Anonymous said...

Regards,

"Passing action parameters from JSF to backing beans

f:setPropertyActionListener: with the h:commandLink and h:commandButton tags you can trigger a method of the backing bean using the action or the actionListener attribute."

An empirical test (under JSF 1.2) shows the order of events on postback is:

1. Call h:commandButton's actionListener
2. Call the f:setPropertyActionListener bean set methods
3. Call the h:commandButton's action

This means that f:setPropertyActionListener is really only useful with action.

Regards!

valsaraj said...

Simply great!

Anonymous said...

That's Awesome try
nice to see so helpful data from there...
May Allah bless u

Marcoaam said...

Great article! Helped me a great deal in the question of passing parameters to "Rendered" attribute, in JSF 1.2. Thanks to frosted, for having asked it in the first place, and to BalusC for the response and the great article.

Anonymous said...

It seems that instead of using an f:attribute tag you can just add the attribute to the action. For example:

<h:commandLink attributeName1="attributeValue1"<

Is this a new feature, or are there drawbacks to using this?

Bauke Scholtz said...

@Bryan: this construct didn't work in JSF 1.x on JSP, where this article is based on. By the way, if you're using JSF 2.x, I recommend reading Communication in JSF 2.0 instead.

Unknown said...

Hi balusc,

I am using jsf 1.2. I want to map the get request params passed through the url directly to my managed bean properties. In the get params section of this blog you have mentioned about passing get params through URL. But i would like to know how it will get mapped to the corresponding managed bean.

Thanks,
Venu

Unknown said...

One more thing my url will be in the following format:

https://example.com/mypage.xhtml?parameterName1=parameterValue1&parameterName2=parameterValue2

Unknown said...

Hi BalusC,

Could you give me an example for getting the url parameters using phase listener and passing the parameters to the managed bean. Please guide me in this regard.

Sebastián Marichal said...

Hi BalusC, i-m trying to make a SecurityFilter to perform ACL checks.

My first attempt was to use a
PhaseListener in RENDER_RESPONSE Phase and an FunctionalityID in each .xhtml like this:



In my PhaseListener i get this value from the viewRoot:

String idFunctionality = facesContext.getViewRoot().getAttributes().get("idFunct");

if(!doACL(idFunctionality)){
//Redirect
try {
response.sendRedirect("/paginas/ErrorSecurity.faces");
} catch (IOException e) {
e.printStackTrace();
}
}


That worked fine but in some point it started to giving to me problems when performing redirection and always throwing this exception:

Exception when handling error trying to reset the response.: java.lang.IllegalStateException
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:436) [jbossweb-7.0.13.Final.jar:]
at javax.servlet.http.HttpServletResponseWrapper.sendRedirect(HttpServletResponseWrapper.java:170) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at org.jboss.weld.servlet.ConversationPropagationFilter$1.sendRedirect(ConversationPropagationFilter.java:83) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
....
...


So i decided to implement a filter instead of a PhaseListener, but my main problem is that i cannot access to FacesContext to get my idFunct from the view root. I saw your warning about the abuse of the method described to access FacesContext, so i'm not sure if it is a good idea to put that code in my ACL Filter.

Do you know what is going on wrong in my PhaseListener when i try to redirect?

Do you have any idea to implement ACL in this context? I think that another approach can be use a filter and just get the url from the request and map the path string to a idfunct, but i need to include an extra table in my BD... what do you think?

Thanks you!!!

Sebastián Marichal said...

Well i managed to resolve one of the issues, the exception when redirecting :


That worked fine but in some point it started to giving to me problems when performing redirection and always throwing this exception:

Exception when handling error trying to reset the response.: java.lang.IllegalStateException
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:436) [jbossweb-7.0.13.Final.jar:]
at javax.servlet.http.HttpServletResponseWrapper.sendRedirect(HttpServletResponseWrapper.java:170) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at org.jboss.weld.servlet.ConversationPropagationFilter$1.sendRedirect(ConversationPropagationFilter.java:83) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
....

i put a return; immediately of the redirect and that fixed the problem in both cases (PhaseListener and Filter).

So my question now goes in a theoretical way, which is the best approach for the ACL check? PhaseListener or ServletFilter? If i choose ServletFilter i can't access to the idFunct attribute in the view root, but i read somewhere that the most appropriate way is to use a filter to to ACL checks instead of a PhaseListener.

Regards!

Sebastián Marichal said...

Hi guys, do you have some advise about my question?

Thanks!

csmatyi said...

Sometimes you have this in your code:

import net.balusc.util.FacesUtil;

Could you make this available for us?

Thanks, Matthew

Unknown said...

Thanks for this fine artical ; but i would be see how do i for passing the paramater the page to another page

Unknown said...

i am trying to make search engine in jsf which can find the data from database, any reference please


thank you.

Unknown said...

Thank you... @BalusC

Unknown said...

Hi BalusC

I have two xhtml pages viz main.xthml and address.xhtml with corresponding backing bean viz mainBean.java and addressBean.java. I have included address.xhtml in my main.xhtml in a p:wizard tab called address. now i my problem is am not able to get address object/bean in my mainBean.java to save the main object. Can you please guide me on this?

Thanks

Unknown said...

Hi BalusC

How can I send javascript global variable value to the backbean. I am using jsf 2.0 with Ice faces.

I want to implement a dirty check and current I am not able apply javascript call in ace:tabset (ace component). So I want to pass javascript variable to the backbean and from their I will do the validation.

Thanks.

Juliana Jolie said...

Balus C, your contribution for the Java community is invaluable. It's 2021 and I'm still using this article in the system I'm working.
Thanks a lot! Kisses from Brazil!