How to display string as xml in jsp page - java

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?

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

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 &lt; and &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.

Related

Adding #RequiredStringValidator causing result not to be found

I have an Apache Struts web application. All of my actions are defined in my struts.xml file. I am trying to add support to my action classes to have validation annotations added to my project.
To try and get this working I added the struts2-convention-plugin.jar and also commons-lang.jar.
I then added an annotation on top of my action method.
jsp
<s:form id="tradingOutageFrm" action="addTradingOutageDo.action"
validate="true" theme="simple">
struts.xml
<action name="addTradingOutageDo" class="com.myproject.action.TradingOutageAction"
method="addDo">
<result name="success" type="tiles">page.tradingOutageAdd</result>
</action>
My action class
public class TradingOutageAction extends ActionSupport {
#RequiredStringValidator(type = ValidatorType.SIMPLE,
fieldName = "storeNo",
message = "Please enter a store.")
public String addDo() throws Exception {
try{
Map<String, Object> session = ActionContext.getContext().getSession();
String userId = session.get("userid").toString();
tradingOutage.setStoreNo(storeNo);
tradingOutage.setStoreServer(storeServer);
tradingOutageDAO.insertOutage(userId, startDate, startTime,
endDate, endTime, tradingOutage);
addActionMessage(MessageConstants.RECORD_INSERTED);
}catch(Exception e){
addActionError(MessageConstants.UPDATE_FAILED + " " + e.getMessage());
}
return SUCCESS;
}
Without the annotation everything works fine but with the annotation I get a
No result defined for action com.myproject.action.TradingOutageAction and result input.
Can anyone help me with what might be wrong here.

Declatring Struts 2 actions as annotation

I found a code for a class in the internet which using Spring and Struts2.
I only know how to declare actions in the XML file, so in that class I found this :
#ParentPackage(value = "showcase")
public class Languages extends ActionSupport {
//deleted code
#Action(value = "/languages", results = {
#Result(type = "json", name = "success", params = {
"root", "languages"
})})
public String execute() throws Exception {
if (term != null && term.length() > 1) {
ArrayList<String> tmp = new ArrayList<String>();
for (String staticLanguage : staticLanguages) {
if (StringUtils.contains(staticLanguage.toLowerCase(), term.toLowerCase())) {
tmp.add(staticLanguage);
}
}
languages = tmp.toArray(new String[tmp.size()]);
}
return SUCCESS;
}
//deleted code
So what is the equivalent for this using the XML file for Struts2?
It's not equivalent, but is mapped to the same URL.
<package name="mypackage" namespace="/" extends="showcase">
<action name="languages" class=com.struts.Languages">
<result type="json">
<param name="root">languages</param>
</result>
</action>
</package>

XML Value extraction using Java JAXB

I need a help in the following scenario. I have got a XML String response. In that XML response I need to extract three values. I could not achieve it. I have specified the XML response and the value I need. Also I created set of .java file using pojo one line tool.
My XML Response:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<control>
<status>success</status>
<senderid>XXXXX</senderid>
<controlid>ControlIdHere</controlid>
<uniqueid>false</uniqueid>
<dtdversion>3.0</dtdversion>
</control>
<operation>
<authentication>
<status>success</status>
<userid>XXXXX1</userid>
<companyid>XXXXX</companyid>
<sessiontimestamp>2014-08-22T07:12:37-07:00</sessiontimestamp>
</authentication>
<result>
<status>success</status>
<function>readByQuery</function>
<controlid>testControlId</controlid>
<data listtype="customer" count="100" totalcount="5142" numremaining="5042">
<customer>
<name>A</name>
<id>12</id>
</customer>
<customer>
<name>A</name>
<id>12</id>
</customer>
<customer>
<name>A</name>
<id>12</id>
</customer>
</data>
</result>
</operation>
In this XML response I would need the following values
Like count=100, totalcount=5142
My object class is like this
public class Data {
private String totalcount;
private Sodocument[] sodocument;
private String numremaining;
private String count;
private String listtype;
public String getTotalcount ()
{
return totalcount;
}
public void setTotalcount (String totalcount)
{
this.totalcount = totalcount;
}
public Sodocument[] getSodocument ()
{
return sodocument;
}
public void setSodocument (Sodocument[] sodocument)
{
this.sodocument = sodocument;
}
public String getNumremaining ()
{
return numremaining;
}
public void setNumremaining (String numremaining)
{
this.numremaining = numremaining;
}
public String getCount ()
{
return count;
}
}
XMLInputFactory xif = XMLInputFactory.newFactory();
Reader reader = new StringReader(response.toString());
XMLStreamReader xsr = xif.createXMLStreamReader(reader);
JAXBContext jc = JAXBContext.newInstance(Data.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Data jb = unmarshaller.unmarshal(xsr,Data.class).getValue();
System.out.println(jb.getCount());
This is my JAXB class. For the value getCount gives me null response. Can somebody help me on fixing this?
The generated class is too long for me to paste here but here is what you can try:
1) Use freeformatter.com/xsd-generator.html to generate an xsd from your xml. Copy and paste the generated xsd to a file.
2) Use xjc (comes with jdk installation) to generate the java class. It is a command line tool and you just have to run "xjc generated.xsd" and it will generate the annotated version of your class. The generated file will be for the entire xml response - so your class will really be Response.java, not Data.java and you then can drill into the Data element and it's attributes.
Add these annotations:
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Data {
#XmlAttribute
private String totalcount;
#XmlElement
private Sodocument[] sodocument;
#XmlAttribute
private String numremaining;
#XmlAttribute
private String count;
#XmlAttribute
private String listtype;
...
But note that Sodocument[] sodocument (which should be a List!) does not match <customer>. Not sure what the model is - could it be another element as well (depending on listtype!)

get body content of html file in java

i'm trying to get body content of html page.
suppose this html file:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="../Styles/style.css" rel="STYLESHEET" type="text/css" />
<title></title>
</head>
<body>
<p> text 1 </p>
<p> text 2 </p>
</body>
</html>
what i want is :
<p> text 1 </p>
<p> text 2 </p>
so, i thought that using SAXParser would do that (if you know simpler way please tell me)
this is my code, but always i get null as body content:
private final String HTML_NAME_SPACE = "http://www.w3.org/1999/xhtml";
private final String HTML_TAG = "html";
private final String BODY_TAG = "body";
public static void parseHTML(InputStream in, ContentHandler handler) throws IOException, SAXException, ParserConfigurationException
{
if(in != null)
{
try
{
SAXParserFactory parseFactory = SAXParserFactory.newInstance();
XMLReader reader = parseFactory.newSAXParser().getXMLReader();
reader.setContentHandler(handler);
InputSource source = new InputSource(in);
source.setEncoding("UTF-8");
reader.parse(source);
}
finally
{
in.close();
}
}
}
public ContentHandler constrauctHTMLContentHandler()
{
RootElement root = new RootElement(HTML_NAME_SPACE, HTML_TAG);
root.setStartElementListener(new StartElementListener()
{
#Override
public void start(Attributes attributes)
{
String body = attributes.getValue(BODY_TAG);
Log.d("html parser", "body: " + body);
}
});
return root.getContentHandler();
}
then
parseHTML(inputStream, constrauctHTMLContentHandler()); // inputStream is html file as stream
what is wrong with this code?
How about using Jsoup? Your code can look like
Document doc = Jsoup.parse(html);
Elements elements = doc.select("body").first().children();
//or only `<p>` elements
//Elements elements = doc.select("p");
for (Element el : elements)
System.out.println("element: "+el);
Not sure how your grabbing the HTML. If its a local file then you can load it directly into Jsoup. If you have to fetch it from some URL then I normally use Apache's HttpClient. A quick start guide is here: HttpClient and does a good job of getting you started.
That will allow you to get the data back doing something like this:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
//
// here you can do things like add parameters used when connecting to the remote site
//
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
Then (as has been suggested by Pshemo) I use Jsoup to parse and extract the data Jsoup
Document document = Jsoup.parse(HTML);
// OR
Document doc = Jsoup.parseBodyFragment(HTML);
Elements elements = doc.select("p"); // p for <p>text</p>

Passing id value to action class

I want to pass textfield with id value pat to the getautocomplete.action in Struts 2. Here I am using TINY.box to pop up the next page.
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
T$('tiny_patient').onkeypress = function(){
TINY.box.show('getautocomplete.action',1,0,0,1)
}
</script>
You need to append the id pat and its value to the url that you pass to the show function. For example
var url = 'getautocomplete.action?pat=' + $("#pat").val();
You can then use the variable url in your show function.
You also need to add the following in your action class. This also depends on the java type of pat. I am using String,
private String pat;
public String getPat()
{
return pat;
}
public void setPat(final String value)
{
this.pat = value;
}
Note
It is recommended to get your url using the following instead of hard-coding the extension
<s:url id="url_variable" namespace="/namespace_of_action" action="action_name" />
var url = '<s:property value="url_variable" />?pat=' + $("#pat").val();
If you are trying to populate the box based on previous box selection or any server side process you have to use ajax.
In your action class , write a getter-setter for variable named "pat" like this:
private string pat;
public getPat()
{
.........
}
public setPat(String pat)
{
this.pat=pat;
}
and change
TINY.box.show('getautocomplete.action',1,0,0,1)
to
TINY.box.show('getautocomplete.action?pat="xyz"',1,0,0,1)
Hope this will solve your problem unless you have an idea about ajax.
Try
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
document.getElementById("tiny_patient").onkeypress = function(e){
TINY.box.show("<s:url action='getautocomplete'/>"+"?pat="+document.getElementById("pat").value,1,0,0,1)
}
</script>

Categories