How to implement AJAX using jQuery.post in JSF?

前端 未结 1 408
天命终不由人
天命终不由人 2021-01-28 13:58

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 t

1条回答
  •  一生所求
    2021-01-28 14:49

    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 in the view to invoke a method before the view is rendered and to set request parameters as bean properties (note that this effectively also works on GET requests).

    
        
        
    
    

    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.

    0 讨论(0)
提交回复
热议问题