String is saved wierdly in html hidden input - java

I have a String like follows which is coming from server side
String productIDs = "[{"productID":"226167","productName":"It is my life (Bingo)"},{"productID":"3193","productName":"It is your name (jingo)"},{"productID":"273838","productName":"It's the same milk/Butter i drink/ate yesterday"}]"
Now I am saving it in a hidden input field this string
<input type="hidden" class="hiddenInput" value="<%=productIDs %>" />
But when i checked it through firebug it is saved very wierdly as follows
<input type="hidden" class="hiddenInput" yesterday"}]"="" is ="" my ="" Butter ="" life ="" (Bingo)"},{"productid":"273838","productname":"It ="" crmo="" (paar)"},{"productid":"3193","productname":"It ="" milk="" same ="" flip-off="" productid":"226167","productname":"It ="" value="[{" />
Anybody has got any idea why this is happening?

Problem is with the way you're saving the string, you have to switch the type of quotes you use otherwise js doesn't know where the string ends and starts.
In your question it would look like this:
String productIDs = "[{'productID':'226167','productName':'It is my life (Bingo)'},{'productID':'3193','productName':'It is your name (jingo)'},{'productID':'273838','productName':'It's the same milk/Butter i drink/ate yesterday'}]"
You can also use \" instead of ' but that, to me, is alot more confusing.
Edit
You can do this using the following code:
strUWantToChange.replace('"',"'");

If you have quotes in your String, you need to escape them before pasting it into HTML.

As already said by other answers, quotes must be escaped. These are not the only characters that should be escaped. <, >, ' and & should systematically be escaped in HTML. The risks are
invalid HTML
broken page
XSS attacks and security vulnerabilities
Whenever you must display data for which you're not absolutely sure that it doesn't contain any of such characters (for example : data coming, directly or indirectly, from the user, free textual data in general), escape this data.
This is done, in JSP by two simple constructs:
the JSTL <c:out> tag:
the JSTL fn:escapeXml EL function: ${fn:escapeXml(productIDs)}
Scriptlets should not be used for years in JSP. Use the JSTL, other custom tags, and the EL.

Try this:
String productIDs = "[{\"productID\":\"226167\",\"productName\":\"It is my life (Bingo)\"},{\"productID\":\"3193\",\"productName\":\"It is your name (jingo)\"},{\"productID\":\"273838\",\"productName\":\"It's the same milk/Butter i drink/ate yesterday\"}]";

Related

How to display html tags in from sql query in Spring view - JSP

I'v a little problem with my Spring Boot application. I am fetching results from my MySQL and the plain text is for example:
<b>Hello World</b>
I am displaying it in the view, and the output I am getting is:
<b>Hello World</b>
I want to get this:
Hello World
How can I display those html tags (<b>, <a>, <font size> etc.)?
In a JSP, the <c:out value="${...}" /> tag automatically escapes the value so the characters <, >, &, ', and " will display correctly. This is as it should be, because without escaping your users may be vulnerable to cross-site scripting attacks.
There are two ways to insert HTML text without getting it escaped:
Ask the tag to not escape: <c:out value="${...}" escapeXml="false" />
Don't use the tag: ${...}
I'd recommend the first option, because it clearly documents that the lack of escaping is intentional.
Beware: If that text comes from a user, a malicious user may inject client-side scripts to attack all your other users.

Cannot escape a quotation(") character when retriveing a string containg quotation inside a string from DB in jsp

I have saved quotation(") in a string using escape character i database. That is working ok. But when i am retrieving the value in a jsp field from database, the string is being ended at the first quotation it gets in the whole string. I am giving an example below:
Lets take a string that i have stored in database as -
" Hello David. This is a "customer"."
Now, i am somehow need to save the string back from databse into a hidden field in a jsp page like below-
<input type="hidden" name="string_from_database" id="string_from_database" value="<%=some varibale that holds the data from database%>">
issue is -
Part of the string is getting exposed (means it is being written on top of the page) which i do not want. In this case,the below phrase is written on the beginning of the jsp page, which i don't want.
customer".
kindly suggest on how to resolve this issue.
Using this function you could replace the quote marks with the html entity variant ". Here's a simple function for it. Hope it fits into your templating system, but should be easy to modify if not.
function escapeQuotes(str){
return str.replace(/"/g,'"');
}
Here's a working fiddle
Use Jstl rather than scriptlets for further Explanation
use EL - Expression Language (${variable}) to get the Value eg. ${welcome}
<c:out value="${some varibale that holds the data from database}"/>

Process Thymeleaf variable as HTML code and not text

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>
Staring with Thymeleaf 3.0 the html friendly tag would be:
<div class="mailbox-read-message" data-th-utext="*{body}">

Thymeleaf string substitution and escaping

I have a string which contains raw data, which I want escaped. The string also contains markers which I want to replace with span tags.
For example my string is
"blah {0}something to span{1} < random chars <"
I would like the above to be rendered within a div, and replace {0} with and {1} with
I have tried a number of things, including doing the substitution in my controller, and trying to use the th:utext attribute, however I then get SAX exceptions.
Any ideas?
You can do this using i18n ?
something like:
resource.properties:
string.pattern=my name is {0} {1}
thymeleaf view:
<label th:text="#{__${#string.pattern('john', 'doe')}__}"></label>
The result should be:
my name is john doe
Im not sure this is a good way. But I hope it could help you
It looks using message parameters is the right approach to output formatted strings. See http://www.thymeleaf.org/doc/usingthymeleaf.html#messages
I suspect you need to pass character entity reference in order to avoid SAX exceptions
<span th:utext = "#{string.pattern(${'<span>john</span>'}, ${'<span>doe</span>'})}"/>
Alternatively place the markup in your .properties file:
string.pattern=my name is <span>{0}</span> <span>{1}</span>

Getting wrong characters in parameter

In files.jsp I am using following anchor and JSTL c:url combination -
<c:url value="downloadfile.jsp" var="dwnUrl" scope="request">
<c:param name="fileType" value="PDF"/>
<c:param name="fileId" value="${file.fileId}"/>
<c:param name="fileName" value="${file.fileName}"/>
</c:url>
Download
On downloadfile.jsp getting the file name value in JavaScript variable as -
selectedFile = <c:out value='${param.fileName}'>
Now, if file name contains some extra character e.g. XYZ 2/3" Technical then on the other page I am getting some different character as - XYZ 2/3#034; Technical
However, if I print request.getParameter("fileName"), its giving correct name. What is wrong?
The <c:out> by default escapes XML entities, such as the doublequote. This is done so to get well-formed XML and to avoid XSS.
To fix this, you should either get rid of <c:out>, since JSP 2.0, EL works perfectly fine in template text as well:
selectedFile = '${param.fileName}';
.. or, if you're still on legacy JSP 1.2 or older, set its escapeXml attribute to false:
selectedFile = '<c:out value="${param.fileName}" escapeXml="false">';
Note that I have added the singlequotes and semicolon to make JS code valid.
Needless to say, you'll need to keep XSS risks in mind if you do so.
The funky characters in your <c:param> values are being URL encoded by <c:url> as they should be. As far as downloadfile.jsp is concerned, the servlet container takes care of URL decoding incoming variables so you don't have to. This is normal behavior and shouldn't pose any problems for you.
If you simply turn escapeXml to false as #BalusC suggests, you will add an XSS vunerability to your page. Instead, you should encode the user input at the time of injection into the destination language, and escape characters that would be evaluated in the destination language. In this case, if the user input contained a single quote character (I'm assuming the string literal in your original example was supposed to be wrapped in single quotes, but the same would be true for double quotes if you were using them), any JavaScript code that followed it would be interpreted by the browser and executed. To safely do what you are trying to do, you should change the line in downloadfile.jsp to:
selectedFile = '${fn:replace(param.fileName, "'", "\'")}';
That will escape only single quotes, which would otherwise end the string literal declaration.
If you were using double quotes, then this would be appropriate:
selectedFile = "${fn:replace(param.fileName, '"', '\"')}";
It is worth noting that escapeXml could be appropriate for escaping JavaScript string literals (and it often is) when the string literal will eventually be dumped into HTML markup. However, in this case, the value should not be XML escaped as it is evaluated in the context of a file path, rather than in the context of HTML.

Categories

Resources