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?

Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87

1 Answers1

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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555