0

I'm trying to send some data from my jsf page to the server using jQuery.post. I have put the url of the same page as the url for handling the request. I'm able to get the data but not able to send a response back to my jQuery.post call.

My pseudo code:

jQuery.post('localhost/mypage.jsf', { data: 'xyz' }, function(res){
    console.log(res);
});

I'm able to get the data variable in my handler class, but not able to send back a response.

Any ideas on how I can do it better?

1 Answer 1

1

JSF is basically the wrong tool for the job. You should be using a web service framework like JAX-RS instead of a component based MVC framework like JSF.

But if you really insist, you could abuse JSF the following way to send an arbitrary response back. Make use of <f:event type="preRenderView"> in the view to invoke a method before the view is rendered and <f:viewParam> to set request parameters as bean properties (note that this effectively also works on GET requests).

<f:metadata>
    <f:viewParam name="data" value="#{bean.data}" />
    <f:event type="preRenderView" listener="#{bean.process}" />
</f:metadata>

With something like the following if you intend to return JSON with help of Google Gson or something:

public void process() throws IOException {
    String message = "Hello! You have sent the following data: " + data;
    String json = new Gson().toJson(Collections.singletonMap("message", message));

    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext ec = context.getExternalContext();
    ec.setResponseContentType("application/json");
    ec.setResponseCharacterEncoding("UTF-8");
    ec.getResponseOutputWriter().write(json);
    context.responseComplete(); // Prevent JSF from rendering the view.
}

Again, you're abusing JSF as the wrong tool for the job. Look at JAX-RS or maybe even a plain vanilla servlet. See also Servlet vs RESTful.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.