Building HTML in Servlet adding extra quotes - java

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'>");

Related

How to insert HTML code in a context variable with thyme leaf [duplicate]

I'm using Thymeleaf to process html templates, I understood how to append inline strings from my controller, but now I want to append a fragment of HTML code into the page.
For example, lets stay that I have this in my Java application:
String n="<span><i class=\"icon-leaf\"></i>"+str+"</span> \n";
final WebContext ctx = new WebContext(request, response,
servletContext, request.getLocale());
ctx.setVariable("n", n);
What do I need to write in the HTML page so that it would be replaced by the value of the n variable and be processed as HTML code instead of it being encoded as text?
You can use th:utext attribute that stands for unescaped text (see documentation). Use this with caution and avoid user input in th:utext as it can cause security problems.
<div th:remove="tag" th:utext="${n}"></div>
If you want short-hand syntax you can use following:
[(${variable})]
Escaped short-hand syntax is
[[${variable}]]
but if you change inner square brackets [ with regular ( ones HTML is not escaped.
Example within tags:
<div>
[(${variable})]
</div>

Thymeleaf ignores "\n" in String returned from method

In my HTML I'm using paragraph that gets content by calling method via thymeleaf:
<p data-th-text="${fund.formatDescription()}"></p>
Method:
private String description;
public String formatDescription() {
return description.replace(";", " \n ");
}
I want my description to have end lines in palce of every semicolon. So that's why I added \n. But thymeleaf ingores new lines and returns continuous text. I tried adding <br/> but it ends up not interpreted as html. What should I add in place of semicolon to force new line in the description?
Html ignores newlines (this isn't thymeleaf's fault). You can either:
Put the description into <pre></pre> tags (or use the css white-space property on the <p> element).
Instead of replacing ; with \n, replace it with <br /> and use th:utext instead of data-th-text. (This means that html will be unescaped, so you better make sure users can't put other html into the description field or you open yourself up to html attacks).
I made a Thymeleaf dialect that makes it easy to keep the line breaks, if the css white-space property isn't an option.
It also bring support for BBCode if you want it.
You can either import it as a dependency (it's very light) or just use it as inspiration to make your own.
Check it out here :
https://github.com/oxayotl/meikik-project

Thymeleaf print JSON string as JSON object into a javascript variable

In Specific
I need a way to print JSON representation of a string value into the html page via thymeleaf.
In detail
I'm having a model attribute which contains a string which is actually a string representation of the JSON
My thymeleaf code
<script th:inline="javascript">
var value = [[${data.scriptValue}]];
</script>
print the variable as below
var value = '[[\"asd\",\"3\"],[\"asd\",\"1\"],[\"asdasd\",\"1\"]]';
But I want something like this as a javascript/JSON array
var value = [["asd","3"],["asd","1"],["asdasd","1"]];
How to do this in thymeleaf?
Note: I know I can do this from JSON.Parse but i need a way to do this from thymeleaf :)
Update - 2015/12/24
This feature is available in Thymeleaf 3
Refer The Thymeleaf textual syntax in https://github.com/thymeleaf/thymeleaf/issues/395
// Unescaped (actual answer)
var value = [(${data.scriptValue})];
//or
var value = [# th:utext="${data.scriptValue}"/];
// Escaped
var value = [[${data.scriptValue}]];
//or
var value = [# th:text="${data.scriptValue}"/];
It's not possible at Thymeleaf 2. As Patric LC mentioned, there are two issues reported for this.
unescaped inline for scripts/css #12
Use Jackson for Javascript inlining of JSON #81
#Faraj, new version of Thymeleaf provides this functionality. They implement features for the issues that you mentioned. You can look here:
http://www.thymeleaf.org/doc/articles/thymeleaf3migration.html
The main features:
Three textual template modes: TEXT, JAVASCRIPT and CSS.
New syntax for elements in textual template modes: [# ...] ... [/].
Inlined output expressions allowed, both escaped ([[...]]) and unescaped ([(...)]).
Intelligent escaping of JavaScript (as literals) and CSS (as identifiers).
Parser-level (/*[- ... -]*/) and prototype-only (/*[+ ... +]*/) comment blocks.
Natural templates applied to JAVASCRIPT scripts and CSS style sheets by means of wrapping elements and/or output expressions inside comments (/*[# ...]*/).

concatenating strings and variables

i have problems while concatenating strings and variables. I tried to add quotes and slashes, i tried to move them back and forth, but i wasnt able to find a solution.
I have a class that 'write' a div. I wrote this
String var = "width:100px";
String div ="<div class=\"divClass\" style="+var+">";
The code i wrote give me
<div class="divClass" style=width:100px>
But, in order to write a good code i would need this
<div class="divClass" style="width:100px">
with the value of style between quote "".
You need to escape the " symbol
String var = "\"width:100px\"";
String div ="<div class=\"divClass\" style="+var+">";
Then div would be
<div class="divClass" style="width:100px">
The reason we need to do this is that we need to tell the compiler that the quotes symbol " is a part of the String and we are not closing the String literal yet.
Example
System.out.println("hello"); => hello
System.out.println("\"hello\""); => "hello"
When the compiler sees \" it reads \ and knows that it has to ignore the next character ie ".
try
String var = "\"width:100px\"";
as you will need to escape your quotes
Just try like this.
String var = "width:100px";
String div ="<div class=\"divClass\" style=\""+var+"\">";

Escape characters in JQuery containing Java Codes

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.

Categories