I'm trying a write a couple small lines of html in my java class that gets some data from another API. I get the data in a JSON string, and would then like to display some of it on a webpage.
To create the HTML, I try:
StringBuilder sb = new StringBuilder();
for(int i=0;i<leads.size();i++){
sb.append("<p>Name: "+leads.get(i).getFirstName()+" "+leads.get(i).getLastName()+"</p>");
sb.append("<p>Email: "+leads.get(i).getEmail()+"</p>");
sb.append("<br />");
}
fullLeadData = sb.toString();
But what ends up being displayed is a literal interpretation of the html tags. Is there a way that I can create this string so that the tags will stay as tags and not the escaped characters?
The java class is a managed bean, so in the html I have:
<body>
<div id="display">
#{PortalView.fullLeadData}
</div>
</body>
Where fullLeadData is the string with the html.
Seems like you're using JSF. Try this:
<div id="display">
<h:outputText value="#{PortalView.fullLeadData}" escape="false"/>
</div>
You may need to replace the escape sequences. The common ones being
‘&’ (ampersand) ‘&‘
‘"’ (double quote) ‘"‘
”’ (single quote) ‘'‘
‘<’ (less than) ‘<‘
‘>’ (greater than) ‘>‘
Related
I want to put one condition in thymeleaf, If my object contain url so i want to print anchor tag with Url so i can open it and if not, then a message should be display.
<span th:utext="${#strings.contains({resultModel.results},'s3')} ? '<a target="_blank" href="${resultModel.results}" >URL</a>' : ${resultModel.results}"></span>
I want to get URL as a java object in href. Please suggest href="${resultModel.results}"
If i use href="http://google.co.in" so it is working but while using href="${resultModel.results}" i am not getting value.
Note: In Above html code else condition is working and getting message as a results.
I wouldn't try and combine that logic... Avoid putting html in html by just splitting the tags out the inner html into its own tags.
<th:block th:with="condition=${#strings.contains(resultModel.results, 's3')}">
<a th:if="${condition}" target="blank" th:href="${resultModel.results}">URL</a>
<span th:unless="${condition}" th:text="${resultModel.results}" />
</th:block>
So I am trying to build some HTML markup in a Spring controller. Sample code:
append(sb ,"<div class="myDiv">");
which is generating the following HTML source on browser:
<div class=""myDiv"">
append code:
private void append(StringBuilder sb, String value) {
sb.append(value).append(System.getProperty("line.separator")).append('\n');
}
My question is, Why generated HTML code has an extra set of "" around text myDiv? My controller method is that produces this HTML:
#RequestMapping(value = "/getSerialRanking", method = RequestMethod.POST, produces = MediaType.TEXT_HTML_VALUE)
#ResponseBody
public String getSerialRankings(#RequestParam(value = "serialNumber", required = false) String serial){
In html single word properties without quotes are legal so
<div class=myDiv>
is converted by your browser to this
<div class="myDiv">
Based on that knowledge I'm assuming your Spring Controller is auto converting the value to <div class=""myDiv""> Then your browser converts the " to a legal HTML entity ".
The " is ignored until it reaches the browser where it is converted to a legal HTML entity "
Finally I think your safe to remove the " for this case. Or if your using more than one words in your HTML property go with #ElliottFrisch solutions:
append(sb ,"<div class=\"myDiv\">");
append(sb ,"<div class='myDiv'>");
Don't use HTML quotes, I think you want to change
append(sb ,"<div class="myDiv">");
to escape the double quotes like
append(sb ,"<div class=\"myDiv\">");
or HTML allows you to mix quotes, so you could say
append(sb ,"<div class='myDiv'>");
I have a web application running Java Tapestry, with a lot of user-inputted content. The only formatting that users may input is linebreaks.
I call a text string from a database, and output it into a template. The string contains line breaks as /r, which I replace with < br >. However, these are filtered on output, so the text looks like b<br>text text b<br> text. I think I can use outputRaw or writeRaw to fix this, but I can't find any info for how to add outputRaw or writeRaw to a Tapestry class or template.
The class is:
public String getText() {
KMedium textmedium = getTextmedium();
return (textmedium == null || textmedium.getTextcontent() == null) ? "" : textmedium.getTextcontent().replaceAll("\r", "<br>");
}
The tml is:
<p class="categorytext" id="${currentCategory.id}">
${getText()}
</p>
Where would I add the raw output handling to have my line breaks display properly?
To answer my own question, this is how to output the results of $getText() as raw html:
Change the tml from this:
<p class="categorytext" id="${currentCategory.id}">
${getText()}
</p>
To this:
<p class="categorytext" id="${currentCategory.id}">
<t:outputraw value="${getText()}"/>
</p>
Note that this is quite dangerous as you are likely opening your site to an XSS attack. You may need to use jsoup or similar to sanitize the input.
An alternative might be:
<p class="categorytext" id="${currentCategory.id}">
<t:loop source="textLines" value="singleLine">
${singleLine} <br/>
</t:loop>
</p>
This assumes a a getTextLines() method that returns a List or array of Strings; it could use the same logic as your getText() but split the result on CRs. This would do a better job when the text lines contain unsafe characters such as & or <. With a little more work, you could add the <br> only between lines (not after each line) ... and this feels like it might be a nice component as well.
I'm working with JSP pages, and I need to append some HTML and Java codes inside a DIV, I only remember that I should escape " like this \", but I don't know about the other characters and I don't know if all non-letter characters should be escaped, here is the String.
String s ="<% ResultSet joinedRooms = myJavaDB.updateJoinedRooms(loginBean.getId());
while(joinedRooms.next()){%> <div id="<%=joinedRooms.getString(1)%>" class="chatRoom">
<div class="chatRoomName"><%=myJavaDB.getRoomName(joinedRooms.getInt(1))%></div></div><% } %>"
No need to roll your own, take a look at Apache Commons StringEscapeUtils.
I am using \n in my java bean and output of the variable in console is displayed correctly. Whereas while fetching this value from bean to JSF \n seems not working.......
can any one suggest me how can i make \n work in of JSF.
The simplest way would be to apply CSS white-space: pre on the parent element containing the text of which you would like to preserve newline \n characters. Given this CSS style class:
.preformatted {
white-space: pre;
}
You could apply this as follows:
<div class="preformatted">#{bean.text}</div>
or
<h:panelGroup layout="block" styleClass="preformatted">#{bean.text}</h:panelGroup>
or
<h:outputText value="#{bean.text}" styleClass="preformatted" />
etc.
This style property is by the way also exactly what the <textarea> element is by default using. You could also make use of it and make it uneditable by setting disabled="true" or readonly="true".
<h:inputTextarea value="#{bean.text}" disabled="true" />
You can of course also replace all occurrences of \n by the HTML <br/> element. This way you can display it in an element which does not use white-space: pre and/or is not a <textarea> element. One of the ways is using fn:replace().
<h:outputText value="#{fn:replace(bean.text,'\\n','<br/>')}" escape="false" />
This is IMO only uglier than white-space: pre.
You should replace all \n with <br/> before you send the value to your <h:inputTextarea>.
Html uses <br/> for line break and not the \n like java.
Also, you should add escape="false" to your <h:outputText (almost sure...).
Replace all occurrences of \n with </br> before displaying it.
When looking into text recorded in my database via a <h:inputTextarea> I found that special characters were being persisted.
Thus, after investigating what I thought was some dark art of persistence, I appreciated that the default display of the JSF component was in fact what was letting me down.
I shortly found that adding white-space: pre-wrap; to <p> on my stylesheet fixed this problem for my <h:outputText> tags which were being supplied with text from a JPA pojo.
In my case, I needed pre-wrap rather than pre because pre was wrapping by character, rather than by word.
Hope this helps someone!
I have solved it using the following method
Declare an inputtextarea where a user can provide multi-line description. Before saving it to database, I have replaced new line to branch
String fpDescriptionCombined = fpDescription.replaceAll("(\r\n|\n)", "<br />");
During showing in screen, i again replaced branch to new line
String finalStr = splitStr.replaceAll("<br />", "\n");
In screen, I used above-mentioned CSS
.showLineBreak {
white-space: pre;
}
<h:outputText value="${templateListController.getFlowPointDescriptionForTab(eachFPType)}" style="display:block;width:860px;" styleClass="showLineBreak" />
I had to do this because my description can be exported/imported via csv. So adding multi-line description will be treated as a new record if not handled properly