Sergey Kucher
Sergey Kucher

Reputation: 4180

Invoke bean method from jsp

I would like to know how to Invoke bean method from jsp. something like. On click of button [Hey] i would like to print "Hello world". Thank you.

Upvotes: 0

Views: 3760

Answers (2)

BalusC
BalusC

Reputation: 1109625

Go ahead with JSF. Here's how your requirement would look like:

View (test.xhtml)

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <h:head>
        <title>JSF Hello World</title>
    </h:head>
    <h:body>
        <h:form>
            <h:commandButton value="Hey" action="#{bean.hey}">
                <f:ajax render=":result" />
            </h:commandButton>
        </h:form>
        <h:outputText id="result" value="#{bean.result}" />
    </h:body>
</html>

Model (Bean.java)

@ManagedBean
@RequestScoped
public class Bean {

    private String result;

    public void hey() {
        result = "Hello World!";
    }

    public String getResult() {
        return result;
    }

}

That's it.

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240966

There are multiple possible ways to do this.

  • JSF EL does this nicely.
  • You can use DWR to invoke bean's method from just making simple javascript call, it will create ajax request to invoke bean's method at server .

Upvotes: 0

Related Questions