我正在尝试使用jQuery.post
从我的jsf页面向服务器发送一些数据。我已将与同一页面的url放在用于处理请求的url中。我能够获取数据,但无法将回复发送回jQuery.post
来电。
我的伪代码:
jQuery.post('localhost/mypage.jsf', { data: 'xyz' }, function(res){
console.log(res);
});
我能够在我的处理程序类中获取data
变量,但无法发回响应。
关于如何做得更好的任何想法?
答案 0 :(得分: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或者甚至是普通的servilla servlet。另请参阅Servlet vs RESTful。