Meg
Meg

Reputation: 119

How to display string as xml in jsp page

Im working on Struts2 project, In action class im passing string to jsp page. I want to display that string content as xml in jsp page.

jsp page : response.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
    <s:property value="sampleStr" />

Action class : ResponseAction

public class ResponseAction extends ActionSupport {
private static final long serialVersionUID = 1L;
public String sampleStr;

public String execute() throws IOException {
    String responseStr = readStringFile();
    setSampleStr(responseStr);
    return SUCCESS;
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public String readStringFile() throws IOException{
      String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
              "<response>"+ "$$" +
              "</response>";
     InputStream inputStream = XmlFormatter.class.getResourceAsStream("/sample.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-16")));
        String s = "";
        List list = new ArrayList();
        String line;
        while ((line = reader.readLine()) != null) {
            list.add(line);
        }
        for (Object s1: list) {
            s= s + s1;
        }
        xmlStr =   xmlStr.replace("$$", s);
        return xmlStr;

}


public String getSampleStr() {
    return sampleStr;
}

public void setSampleStr(String sampleStr) {
    this.sampleStr = sampleStr;
}
}

Struts.xml :

<package name="default" namespace="/" extends="struts-default">
  <action name="PEConsolidation" class="com.metlife.ibit.pe.web.controller.actions.ResponseAction">
  <interceptor-ref name="defaultStack" />
    <result name="success">/WEB-INF/jsps/response.jsp</result>
  </action>
</package>

When i looks response.jsp, it display return string as text. please anyone help to display as xml content?

Upvotes: 0

Views: 686

Answers (2)

Timo
Timo

Reputation: 46

s:property has built-in escaping functionality for HTML, JavaScript and XML. By default it escapes HTML.

I think what you want to do is no escaping at all:

<s:property value="sampleStr" escapeHtml="false" />

You should also check the http headers of the response ("content-type: text/html" would be wrong in your case).

Instead of using a jsp, you could look into using a different result type, maybe write your own one.

https://struts.apache.org/core-developers/result-types.html

Upvotes: 1

Abhinav
Abhinav

Reputation: 540

I think that the browser is trying to interpret the XML tags as HTML tags and, failing to do so, is ignoring them.

You will need to replace each < and > character to &amp;lt; and &amp;gt; respectively. You can use very useful String.replaceAll() method in Java API's.

Additionally, you can check this Oracle's page out. It would be very helpful in your development process using JSP with XML technologies.

Upvotes: 0

Related Questions