Search code examples
javajavascripthtmljsf-2facelets

How to get the input form values along with whole page HTML source using JavaScript to pass it to backing bean?


In my Facelets page I have a <div> and that contains some input text boxes for user to enter values to submit. I will generate the PDF using this HTML source.

<div id="wrapper">
    <h:form prependId="false">
        <h:inputHidden id="source" value="#{bean.source}" />
        <h:inputText id="fName" value="#{bean.firstName}"/>
        <h:inputText id="lName" value="#{bean.lastName}"/>
        <h:inputText id="age" value="#{bean.age}"/>
    </h:form>
</div>

Like this I have other form fields too. When user enters all the data in the form and click on submit button I am getting the source inside this <div> using JavaScript.

function getHtml() {
    document.getElementById('source').value = document.getElementById('wrapper').innerHTML;
}

And passing to bean on click of submit.

<h:commandButton type="submit" id="appl-submit" action="#{bean.submit}"
                 value="Submit" onclick="javascript:getHtml();"/>

In the backing bean class

@ManagedBean
@SessionScoped
public class Bean{

    private String firstName;
    private String lastName;
    private int age;
    private String source;

    // Getters and setters for all properties.
}

But I am only getting the form with empty input fields instead of HTML source along with user entered values. How can I get the HTML source along with form values?


Solution

  • But I am only getting the form with empty input fields instead of HTML source along with user entered values.

    That's expected behaviour. This approach works only if you've already submitted the form and are thus redisplaying the submitted form (as kind of confirmation or so).


    How can I get the HTML source along with form values?

    That's already answered in your previous question which you never gave feedback on: Get the URL of current XHTML page which has user data filled in the form into the JSF Managed bean. In your particular case, that can even be done simpler as you've apparently a session scoped bean already (which is however still bad design as the same page in multiple browser windows/tabs in the same session may interfere with each other):

    public void submit() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = (HttpSession) externalContext.getSession(true);
        String url = request.getRequestURL().append(";jsessionid=").append(session.getId()).toString();
    
        Document doc = Jsoup.connect(url).get();
        String html = doc.select("#wrapper").html();
        // ...
    }