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。