java - How can I get hidden value from facelet?

I have a few hiden fields in my .xhtml page.

<h:inputHidden value="1" id="hidePrev"/>
.....
<h:inputHidden value="1" id="hideNext"/>

And I can't catch their values from my JSF bean.

public class FacesUtil {
public static Object getMapValue(String key) {
    return FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get(key);
}

public static void setMapValue(String key, Object value) {
    FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().put(key, value);
}

}

My bean code:

    nextFlag = (String)FacesUtil.getMapValue("hideNext");
    prevFlag = (String)FacesUtil.getMapValue("hidePrev");

Fields nextFlag and prevFlag are still empty. They have getter and setter methods. I'm using JSF 2.2 ver. Please, help me to resolve this problem.

3 Answers

  1. Daniel- Reply

    2019-11-15

    The <h:inputHidden> isn't intented to add custom request parameters to the form submit. It's intented to remember already-definied bean properties across postbacks. For adding custom request parameters, you should be using <f:param> in command components or "plain vanilla" <input type="hidden"> instead.

    Thus, so

    <h:commandButton ...>
        <f:param name="prev" value="1" />
        <f:param name="next" value="1" />
    </h:commandButton>
    

    or so

    <input type="hidden" name="prev" value="1" />
    <input type="hidden" name="next" value="1" />
    <h:commandButton ... />
    

    Either way, the values are in a request scoped bean available as

    @ManagedProperty("#{param.prev}")
    private String prev;
    
    @ManagedProperty("#{param.next}")
    private String next;
    

    Or in a broader scoped bean as

    String prev = externalContext.getRequestParameterMap().get("prev");
    String next = externalContext.getRequestParameterMap().get("next");
    

    Please note that you confused request parameters with application scoped attributes. This is seriously a pretty major mixup which proves that you have no idea what you're doing. I strongly recommend to take a pause and go through a basic JSF tutorial once again.

  2. Dennis- Reply

    2019-11-15

    You sure about the getApplicationMap() part of FaceUtil? When I'm touching the external Context, it's to retrieve values from the request map:

    Map<String, String> pMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
    

    In your case, pMap should contain a key hideNext.

  3. Derek- Reply

    2019-11-15

    Try (String)context.getExternalContext().getRequestParameterMap().get(parameterName); In your case parameterName may be nextFlag or prevFlag

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>