I get html code from server to build freemarker.ftl.
Example:
Server return:
String htmlCode="<h1>Hello</h1>";
freemarker.ftl
${htmlCode}
except:Hello
actually: <h1>Hello</h1>
what can i do?
By default FreeMarker has no auto-escaping on, so it should print that value as HTML. But as it doesn't as you say, I can imagine two possibilities:
You are inside <#escape x as x?html>...</#escape>, or that was added to the template by a custom TemplateLoader. In that case, in 2.3.x you have to write <#noescape>${htmlCode}</#noescape>. (In 2.4 it will be much less verbose if everything goes as planned.)
That value was escaped before it reaches FreeMarker. So the template already gets <h1>Hello</h1> as the string.
Related
I have an html form:
<form>
<input type="hidden" id="hiddenField"/>
...Other form fields
</form>
In this form I want to set a hidden field with xml data.
Can anyone suggest if it is fine to set the hidden field directly with xml data.
i.e. in my javascript function is it safe to directly set the hidden field with xml like: $(#hiddenFiled).val(xml); and get the xml in my java servlet?Please suggest.
No you can't keep xml without encoding
You can opt either
var stringValue=escape(xml);
var xmlValue= unescape (stringValue)
in javascript
Though these methods has been depreciated in newer versions so you could find it in another library like http://underscorejs.org/#escapeUnderScoreJs
Also don't keep XML in hidden field if it holds andy sensitive information.
Hidden form fields are not for session tracking.
We have two mechanism for session tracking, they are cookies and URL rewriting, the latest for the people that doesn't have cookies enabled in their browsers, I could only understand sending a session id in a hidden field when you have your own session tracker and are not using the one that is already with your server container (HttpSession and all), but why re-invent the wheel?
Hidden fields are for passing information between pages, sometimes I use a and I clearly don't want that information displayed to the user
Posting XML without javascript or browser plugins is impossible. You should not send it directly as a form parameter. See this answer for more info:.
Use a library that would encode them while sending to server, and decode them at the server side.
Underscore.js provides such functionality. See the documentation:
escape_.escape(string)
Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.
_.escape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
unescape_.unescape(string)
The opposite of escape, replaces &, <, >, ", ` and ' with their unescaped counterparts.
_.unescape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
However, do keep in mind that usually browsers have limits over the amount of data that you can send through GET request (around 255 bytes). Hence it's always a good option to use POST instead of GET even when sending encoded XML.
Hello I want to ask what can be the source of problem with bad encoding on the page.
This problem is very specific, because first part of page has good encoding and second part is broken.
Moreover it appears only in some scenarios, not allways.
The most weird thing is that starts to appear in the middle of one message and after this message, the rest of page has badly encoded characters.
This message is included in JSP with this part of code <fmt:message key="the.text.wchich.makes.problems"/>
Problem is not related to JSP, because bad encoding appears in the middle of message.
Gratulujeme, toto číslo si môžete zarezervovať kliknutím na tlačidlo Pokračovať.
But sometimes it outputs as
Gratulujeme, toto číslo si môžete zarezervovať kliknut�m na tlaÄidlo PokraÄovaÅ¥.
or
Gratulujeme, toto číslo si mô�¾ete zarezervovaÅ¥ kliknutÃm na tlaÄidlo PokraÄovaÅ¥.
So it is probably not the fault of badly entered text in database.
We are using Liferay 6.0, jsp, spring. Localized strings are stored in Oracle 11g database.
So, how is it possible that encoding begin to break in the middle of page?
You might need to specify encoding in your JSPs as:
<%# page contentType="text/html; charset=UTF-8" %>
You should be able to achieve the same result via CharacterEncodingFilter with forceEncoding parameter set and mapped to * path + INCLUDE dispatch.
This is just one suggestion. Try to set locale from themeDisplay object.
<fmt:setLocale value="<%=themeDisplay.getLocale() >"/>
see if it helps to fmt:message to identify proper locale of message.
Note: This expects that you should have proper locale set for user or at portal level.
The reason for this "escapes" me.
JSON escapes the forward slash, so a hash {a: "a/b/c"} is serialized as {"a":"a\/b\/c"} instead of {"a":"a/b/c"}.
Why?
JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required, like Harold L points out:
The JSON spec says you CAN escape forward slash, but you don't have to.
Harold L answered Oct 16 '09 at 21:59
Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out:
This is because HTML does not allow a string inside a <script> tag to contain </, so in case that substring's there, you should escape every forward slash.
Seb answered Oct 16 '09 at 22:00 (#1580667)
Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/". (Yuck)
The JSON spec says you CAN escape forward slash, but you don't have to.
I asked the same question some time ago and had to answer it myself. Here's what I came up with:
It seems, my first thought [that it comes from its JavaScript
roots] was correct.
'\/' === '/' in JavaScript, and JSON is valid JavaScript. However,
why are the other ignored escapes (like \z) not allowed in JSON?
The key for this was reading
http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by
http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of
the slash escape allows JSON to be embedded in HTML (as SGML) and XML.
PHP escapes forward slashes by default which is probably why this appears so commonly. I suspect it's because embedding the string "</script>" inside a <script> tag is considered unsafe.
Example:
<script>
var searchData = <?= json_encode(['searchTerm' => $_GET['search'], ...]) ?>;
// Do something else with the data...
</script>
Based on this code, an attacker could append this to the page's URL:
?search=</script> <some attack code here>
Which, if PHP's protection was not in place, would produce the following HTML:
<script>
var searchData = {"searchTerm":"</script> <some attack code here>"};
...
</script>
Even though the closing script tag is inside a string, it will cause many (most?) browsers to exit the script tag and interpret the items following as valid HTML.
With PHP's protection in place, it will appear instead like this, which will NOT break out of the script tag:
<script>
var searchData = {"searchTerm":"<\/script> <some attack code here>"};
...
</script>
This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES flag but most developers will not use this since the original result is already valid JSON.
Yes, some JSON utiltiy libraries do it for various good but mostly legacy reasons. But then they should also offer something like setEscapeForwardSlashAlways method to set this behaviour OFF.
In Java, org.codehaus.jettison.json.JSONObject does offer a method called
setEscapeForwardSlashAlways(boolean escapeForwardSlashAlways)
to switch this default behaviour off.
I am sending emails using amazon java sdk. I have to send html template as mail. I have written a program for this and it is working fine. But now I am storing the whole html code in a single String. But whenever i need to edit the template, I have to edit the program (I mean the String variable). And also I have to take care the special characters like " \ ...etc in that html code. Please suggest me an elegant way to solve this issue.
Use a template engine for that and store your template externally either in class path or on a file system. Here is a question that may help you selecting one: https://stackoverflow.com/questions/2381619/best-template-engine-in-java
Use Apache Common Lang api's StringEscapeUtils#escapeHtml, It escapes the characters in a String using HTML entities and return a new escaped String, null if null string input.
For example:
"US" & "UK"
becomes:
"US" & "UK".
Check the Apache Velocity Project. You can create template for several things. From it's user-guide page
Velocity can be used to generate web pages, SQL, PostScript and other output from templates. It
can be used either as a standalone utility for generating source code and reports, or as an
integrated component of other systems.
You can use a VTL(Velocity Template Language) . A example from above link
<HTML>
<BODY>
Hello $customer.Name!
<table>
#foreach( $mud in $mudsOnSpecial )
#if ( $customer.hasPurchased($mud) )
<tr>
<td>
$flogger.getPromo( $mud )
</td>
</tr>
#end
#end
</table>
Better and easiest way is reading the html file line by line using simple file reading operation and append this each line to a single String. And also I found this solution (also a better one, if you are ready to add one more library file to your project) from SO.
Say you have a standard template with included (parsed) header, body, footer templates.
In the body template a variable like $subject is defined and you want that also displayed in the header template.
In some other template languages like HTML::Mason(perl based) you would evaluate the body template first to pick up the $subject variable but store it's output temporarily in a variable so your final output could end up in the correct order (header, body, footer)
In velocity it would look something like
set ($body=#parse("body.vm"))
parse("header.vm")
${body}
parse("footer.vm")
This however doesn't seem to work, any thoughts on how to do this?
Either of the two solutions above would work. The VelocityLayoutServlet solution requires an extra package (also from Velocity) called Velocity Tools. I'm partial to this approach (and variants) myself.
A third method is simply to put the #parse within quotes:
set ($body="#parse('body.vm')")
Within a #set, anything in double quotes is evaluated. Strings within single quotes are passed in literally.
You can do this using VelocityLayoutServlet which is part of VelocityTools.
This allows you to define a layout for your application -- let's call it application.vm -- in which you can parse in headers, footers etc and declare where the main body content is placed using the screen_content declaration, e.g:
<html>
<head>
<title>$subject</title>
</head>
<body>
#parse("header.vm")
$screen_content
#parse("footer.vm")
</body>
</html>
VelocityLayoutServlet will evalulate the templates (and, hence, variables) before rendering which allows you to set a $subject variable in your body template, e.g:
#set($subject = "My Subject")
<div id="content">
</div>
More detailed information can be found in the Velocity documentation.
If I understand you correctly, you want to have a Velocity variable named $subject interpolated into the header.vm and the body.vm templates. Right now, the variable is defined in the body.vm template, so you cannot refer to it in the earlier template header.vm.
Why don't you abstract out the definition of $subject into its own template snippet, called globals.vm say, then include that in the top-level template. So you'd have:
#parse("globals.vm")
#parse("header.vm")
#parse("body.vm")
#parse("footer.vm")