Topera
Topera

Reputation: 12389

How to hide the html tag in JSF to return only JSON?

I'm using JSF with Facelets 1.1.14 and need to return a JSON response to a ajax request. But I'm getting the html tag in response. How can I hide this, to sent only JSON data?

Main Page

<html xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html">
  <ui:composition template="../templates/JSONTemplate.xhtml">
    <ui:define name="content">
      <h:outputText escape="false" value="#{myjson}" />
    </ui:define>    
  </ui:composition>
</html>

Template

<html xmlns:ui="http://java.sun.com/jsf/facelets">
  <ui:insert name="content" />
</html>

Note:a templateless solution is better.

Upvotes: 0

Views: 969

Answers (2)

Topera
Topera

Reputation: 12389

SOLVED:

I just removed the xhtml file and navigation-case in faces-config.xml. Then I intercept response and write directly my json string.

// code in MyBean.java
getResponse().getWriter().append(getMyJSON());
return null;

As BalusC said, the better option is use JAX-RS, but I need a faster solution to develop.

Upvotes: 0

BalusC
BalusC

Reputation: 1108722

Just remove <html> tag.

<ui:composition template="../templates/JSONTemplate.xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:h="http://java.sun.com/jsf/html">
    <ui:define name="content">
        <h:outputText escape="false" value="#{myjson}" />
    </ui:define>    
</ui:composition>

and

<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets">
    <ui:insert name="content" />
</ui:composition>

As to a templateless solution, use JAX-RS instead of JSF. JSF is a web MVC framework, not a web service framework.

See also:

Upvotes: 2

Related Questions