如何从JSF生成JSON响应? [英] How to generate JSON response from JSF?
问题描述
我创建了一个页面,我想在该页面上从JSF页面获取JSON响应, 但是当我尝试获取页面时,它会显示整个HTML页面.
I have created a page where I want to get the JSON response from a JSF page, but when i try to get page it shows me whole html page.
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<title>Facelet Title</title></head><body>
[{"value": "21", "name": "Mick Jagger"},{"value": "43", "name": "Johnny Storm"},{"value": "46", "name": "Richard Hatch"},{"value": "54", "name": "Kelly Slater"},{"value": "55", "name": "Rudy Hamilton"},{"value": "79", "name": "Michael Jordan"}]
</body></html>
推荐答案
JSF是生成HTML的MVC框架,而不是某种REST Web服务框架.本质上,您正在滥用JSF作为Web服务.您的具体问题仅是由于将<html>
标记等放置在视图文件您自己中引起的.
JSF is a MVC framework generating HTML, not some kind of a REST web service framework. You're essentially abusing JSF as a web service. Your concrete problem is simply caused by placing <html>
tags and so on in the view file yourself.
如果您真的坚持,那么始终可以使用<ui:composition>
而不是<html>
来实现.您还需要确保使用正确的内容类型application/json
,这在JSF中默认为text/html
.
If you really insist, then you can always achieve this by using <ui:composition>
instead of <html>
. You also need to make sure that the right content type of application/json
is been used, this defaults in JSF namely to text/html
.
<ui:composition
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<f:event type="preRenderView" listener="#{bean.renderJson}" />
</ui:composition>
使用
public void renderJson() throws IOException {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseContentType("application/json");
externalContext.setResponseCharacterEncoding("UTF-8");
externalContext.getResponseOutputWriter().write(someJsonString);
facesContext.responseComplete();
}
但是我强烈建议您看一下JAX-RS或JAX-WS,而不是滥用JSF作为JSON Web服务.使用正确的工具完成工作.
But I strongly recommend to look at JAX-RS or JAX-WS instead of abusing JSF as a JSON web service. Use the right tool for the job.
- How to implement JAX-RS RESTful service in JSF framework
- Servlet vs RESTful
- What is the need of JSF, when UI can be achieved from CSS, HTML, JavaScript, jQuery?
这篇关于如何从JSF生成JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!