0

我正在尝试使用 .jsf 将一些数据从我的 jsf 页面发送到服务器jQuery.post。我已将同一页面的 url 与处理请求的 url 放在了一起。我能够获取数据,但无法将响应发送回我的jQuery.post呼叫。

我的伪代码:

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

我能够data在我的处理程序类中获取变量,但无法发回响应。

关于如何做得更好的任何想法?

4

1 回答 1

1

JSF 基本上是不适合这项工作的工具。您应该使用像 JAX-RS 这样的 Web 服务框架,而不是像 JSF 这样的基于组件的 MVC 框架。

但是,如果您真的坚持,您可以通过以下方式滥用 JSF 来发送任意响应。在视图中使用<f:event type="preRenderView">在视图呈现之前调用方法<f:viewParam>并将请求参数设置为 bean 属性(请注意,这也有效地适用于 GET 请求)。

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

如果您打算在Google Gson或其他工具的帮助下返回 JSON,则使用以下内容:

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.
}

同样,您滥用 JSF 作为工作的错误工具。看看 JAX-RS 或者甚至是一个普通的 servlet。另请参阅Servlet 与 RESTful

于 2013-01-08T16:54:15.303 回答