Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

How to generate JSON response from JSF?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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>

with

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();
}

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.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...