holegeek
holegeek

Reputation: 107

Send JSON between two applications JSF

I want to send data between two applications by using JSON and Ajax. For the first test, i want to click on a button (in xhtml) and receive data in managedbean (in the second application).

For this, i have created :

xhtml page :

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
    <body>
        <ui:composition template="/templates/template.xhtml">
            <ui:define name="content">
                <h:outputScript library="js" name="test.js" />
                <h:form>
                <h:button  onclick="validate();" value="Tester" type="button"/> 
                </h:form>
            </ui:define>
        </ui:composition>
    </body>
    </html>

test.js :

function validate(){ 
    try{
        var myJSONObject = {"name":"hello","address":"xyz"};
        var toServer = "data=" + encodeURIComponent(myJSONObject);
        var request=new XMLHttpRequest();
        request.open("POST", "http://'xxLocalIPxx':8080/Project1/folderTest/TestBean", true);
        request.send(toServer);
        return true;
    }
    catch(err)
    {
    alert(err.message);
    }
};

ManagedBean TestBean :

public class TestBean extends HttpServlet{
    private static final long   serialVersionUID    = 1L;

    public TestBean() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // PrintWriter out = response.getWriter();
        String output = request.getParameter("params");
        System.out.println("Servlet : " + output);
    }
}

But, when i click on the button in the xhtml page, i don't execute the method doGet in the managedBean. I tried to put a breakpoint in this method but it never work.

Why ?

Thanks.

Upvotes: 0

Views: 1458

Answers (1)

BalusC
BalusC

Reputation: 1109132

You're mixing servlets and JSF backing beans. They have nothing to do with each other. The TestBean class which you've there is in essence a servlet, not a JSF backing bean. You cannot use it by registering it as a JSF managed bean by @ManagedBean on the class or <managed-bean> in faces-config.xml. It has to be registered as a fullworthy servlet. You can use the @WebServlet annotation on the class or the <servlet> entry in web.xml for this.

Assuming that your environment supports Servlet 3.0, just use @WebServlet to register it:

@WebServlet("/testservlet")
public class TestServlet extends HttpServlet {
    // ...
}

(here, /testservlet, is the URL pattern on which the servlet has to listen)

and, assuming that /Project1 is the context path, invoke it as

http://example.com:8080/Project1/testservlet

(it'd be easier if you test it first by entering the URL straight in browser's address bar)

See also:

Upvotes: 3

Related Questions