Handle line breaks from backing bean in JavaScript - java

I'm trying to use a string from my backing bean which may contain line breaks as a parameter for my JavaScript method:
Snippet from xhtml:
<a4j:commandLink id="showEntry"
immediate="true"
styleClass="smallSpaceLeft"
action="#{bean1.method()}"
onclick="jsMethod('#{entry.text}')"
value="#{messages['general.click']}" />
Everything works fine, except the string contains any line breaks.
E.g.: #{entry.text} = "First line.\nSecond line."
The html-output looks like:
<a class="smallSpaceLeft" href="#" id="j_id279:0:showEntry"
name="j_id279:0:showEntry" onclick="jsMethod('First line.
Second line.');A4J.AJAX.Submit('j_id272',event,
{'similarityGroupingId':'j_id279:0:showEntry','parameters':
{'j_id279:0:showEntry':'j_id279:0:showEntry'} } );return false;">Click me</a>
So the JavaScript is broken as a line break ends a command. How can I avoid this?

You cannot handle it in javascript, you must replace the linebreaks before you print the code.
In strings you may prepend a backslash before the linebreak. But as there may be more questionable characters I would prefer to URL-encode the string and then decode it in javascript by using decodeURIComponent() .

Related

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>

JSF 2.0; escape="false" alternative to prevent XSS?

In my jsf webapplication i'm using a messages.properties to output some text. This text could have html line breaks so format the outputtext.
That all works fine, if i set the escape="false" attribute to the outputtext.
The problem is, this attribute with value "false" doesn't prevent vor XSS (cross site scripting) so i remove this attribute and use default-value "true".
So, i dont want to split all text lines to seperate properties in my messages.properties like in this example:
mytext = This is my text<br />with line break and user value {0}...
after:
mytext1 = This is my text
mytext2 = with line break and user value {0}...
is there any way, other than escape="false" but that prevent from xss?
thanks!
It should be possible to just escape the user supplied parameter using the standard jstl functions in the http://java.sun.com/jsp/jstl/functions namespace:
<h:outputFormat value="#{bundle.myMessage}" escape="false">
<f:param value="#{fn:escapeXml(param)}"/>
</h:outputFormat>
XSS can't happen if you're outputting some HTML from a safe source which is not input or editable by the user. You can safely use escape="false" in this case.

Removing HTML entities while preserving line breaks with JSoup

I have been using JSoup to parse lyrics and it has been great until now, but have run into a problem.
I can use Node.html() to return the full HTML of the desired node, which retains line breaks as such:
Glóandi augu, silfurnátt
<br />Blóð alvöru, starir á
<br />Óður hundur er í vígamóð, í maga... mér
<br />
<br />Kolniður gref, kvik sem dreg hér
<br />Kolniður svart, hvergi bjart né
But has the unfortunate side-effect, as you can see, of retaining HTML entities and tags.
However, if I use Node.text(), I can get a better looking result, free of tags and entities:
Glóandi augu, silfurnátt Blóð alvöru, starir á Óður hundur er í vígamóð, í maga... mér Kolniður gref, kvik sem dreg hér Kolniður svart,
Which has another unfortunate side-effect of removing the line breaks and compressing into a single line.
Simply replacing <br /> from the node before calling Node.text() yields the same result, and it seems that that method is compressing the text onto a single line in the method itself, ignoring newlines.
Is it possible to have the best of both worlds, and have tags and entities replaced correctly which preserving the line breaks, or is there another method or way of decoding entities and removing tags without having to replace them manually?
(disclaimer) I haven't used this API ...
but a quick look at the docs suggests that you could visit each descendent node and dump out its text contents. Breaks could be inserted when special tags like <br> are encountered.
The TextNode.getWholeText() call also looks useful.
based on another answer from stackoverflow I added a few fixes and came with
String text = Jsoup.parse(html.replaceAll("(?i)<br[^>]*>", "br2nl").replaceAll("\n", "br2nl")).text();
text = text.replaceAll("br2nl ", "\n").replaceAll("br2nl", "\n").trim();
Hope this helps

out.println() does not work

I have homework which I have to use scriptlets in ,
I need to make new line in my jsp page usint out object
I tried to use
<%
out.println();
out.newLine();
%>
but both doesn't work !!! I treid to use
out.flush()
but it doesn't work!!
Perhaps out.println("<br>"); is what you're after. (Remember that the browser in which you're viewing the jsp-page in, interprets the output of your script as HTML, which basically ignores newline characters.)
You can look at the source of the page to see what the jsp-page actually generates.
If you really want to see the verbatim output of the jsp-script, you could do
out.println("<html><body><pre>");
// ...
out.println("</pre></body></html>");
#Alaa - out.newLine() does work. It just doesn't do what you are expecting it to do ... assuming that your JSP is generating an HTML page.
When you use out.newLine(), it adds a newline character to the content stream that you are generating. If you use view source on the page in your web browser you can see the newline character.
But a newline character in an HTML document typically does not result in a line break in the displayed page as rendered by a browser. To get the browser to render line break in the displayed page, you typically* need to output a <br /> element.
* - Actually, there are other ways to get the visual equivalent of a line break involving CSS, etcetera. And within a <pre>...</pre> a raw newline character does get rendered as a line break.
Remember the JSP code is outputting HTML. The HTML will then be rendered by the browser. A single blank line in HTML may not be shown as a blank line on the screen when the HTML is rendered.
You need to either examine the HTML source in the browser and look for the blank line. Or else try output more significant HTML to verify the JSP scriptlets are working like:
<%
out.println("<p>hello</p>");
%>

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