Spring messages in JavaScript and Thymeleaf - java

I use Thymeleaf with Spring MVC 4.1.1 and I want to be able to re-use my Spring messages (with the user's automatically detected locale) for my JavaScript files. E.g. I want to do:
$('#fooTitle').text(messages['foo.title']);
...and #fooTitle would contain the value under foo.title for the user locale.
What would be the easiest way to do this? Note that I would like a JavaScript object ("dictionary") or another data structure which is easy to navigate.

If not the easiest (but admittedly easy enough), the cleanest and most robust way is to use html5 data attributes to pass back-end data to js. This way, no matter if you move your javascript to external files, it still works. Use some element as container (choose the most proper for your case) as a carrier of the thymeleaf back-end retrieved i18n values and then access them with jQuery
in html:
<div id="container" th:attr="data-foo-title-txt=#{foo.title}"></div>
in js:
$('#fooTitle').text($("#container").data("foo-title-txt"));
See also my older similar answer, (although the OP has not left any sign of life after that :) )
,
JavaScript, Thymeleaf and localizing text

The easiest way to include localization messages would be:
$('#fooTitle').text([[#{foo.title}]])

Related

How to use JSP as a template without serving it as a webpage

Per my understanding JSP is something to serve to the client. But is it possible to use JSP simply as a template to dynamically assemble an html page, which I then serve to the client? What I mean is this
A servlet receives the call from the user
After some computation, my servlet calls the JSP to assemble the html page dynamically
The servlet gets or converts the JSP "result" (the resulting html page) to a String
The servlet can now do whatever it wants with that String. It can return it as an html webpage or it can store it in a database, or whatever. After all, the string here is a proper html page/text.
For comparison, Python has Jinja2, which does exactly what I just explained. The closest thing to Jinja2 in Java seems to be JSP.
I need a template to assemble html pages dynamically. If I can use the JSP as above then that will solve my problem in Java. Notice that I don't care for JSP per se. I just need a template similar to Jinja2 (if I could use Jinja2 in Java on App-Engine that would be ideal). Also I am very new to JSP. So if you have an answer, please format it as an example; that would be truly helpful.
I am migrating from Python App-Engine to Java App-Engine for business reasons.
This is possible, but you'll need to jump through quite a few hoops, the details of which are dependent on the specific container - in this case appengine.
A quick summary:
create a fake httpservletresponse, wrapping an output stream you access after rendering. You cannot use a httpservletresponsewrapper, even though the spec permits it this environment won't
store all request attributes in a map, you'll restore these afterwards in case they've been mutated
use requestdispatcher.include, passing in the real request and your synthetic response
restore request attributes
read string from the outputstream
Be particularly careful of side effects to your request/response, for example the constraints around only calling one of getwriter or getoutputstream, as well as finalizing the request (setting status or content length)
Or just use one of velocity, handlebars, freemarker or the various other Java templating languages. They'll all be much more straightforward.

Escape HTML in JSON with PlayFramework2

I am using PlayFramework2 and I can't find a way to properly handle HTML escaping.
In the template system, HTML entities are filtered by default.
But when I use REST requests with Backbone.js, my JSON objects are not filtered.
I use play.libs.Json.toJson(myModel) to transform an Object into a String.
So, in my controller, I use return ok(Json.toJson(myModel)); to send the response ... but here, the attributes of my model are not secured.
I can't find a way to handle it ...
Second question :
The template engine filters HTML entities by default, this means that we have to store into our database the raw user inputs.
Is it a save behaviour ?
Third questdion :
Is there in the PlayFramework a function to manualy escape strings ? All those I can find require to add new dependencies.
Thanks !
Edit : I found a way at the Backbone.js templating level :
- Use myBackboneModel.escape('attr'); instead of myBackboneModel.get('attr');
Underscore.js templating system also includes that options : <%= attr %> renders without escaping but <%- attr %> renders with escaping !
Just be careful to the efficiency, strings are re-escaped at each rendering. That's why the Backbone .create() should be prefered.
The best practices on XSS-attacks prevention usually recommend you to reason about your output rather than your input. There's a number of reasons behind that. In my opinion the most important are:
It doesn't make any sense to reason about escaping something unless you exactly know how you are going to output/render your data. Because different ways of rendering will require different escaping strategies, e.g. properly escaped HTML string is not good enough to use it in Javascript block. Requirements and technologies change constantly, today you render your data one way - tomorrow you might be using another (let's say you will be working on a mobile client which doesn't require HTML-escaping, because it doesn't use HTML at all to render data) You can only be sure about proper escaping strategy while rendering your data. This is why modern frameworks delegate escaping to templating engines. I'd recommend reviewing the following article: XSS (Cross Site Scripting) Prevention Cheat Sheet
Escaping user's input is actually a destructive/lossy operation – if you escape user's input before persisting it to a storage you will never find out what was his original input. There's no deterministic way to 'unescape' HTML-escaped string, consider my mobile client example above.
That is why I believe that the right way to go would be to delegate escaping to your templating engines (i.e. Play and JS-templating engine you're using for Backbone). There's no need to HTML-escape string you serialize to JSON. Notice that behind the scenes JSON-serializer will JSON-escape your strings, e.g. if you have a quote in your string it will be properly escaped to ensure resulting JSON is correct, because it's a JSON serializer after all that's why it only cares about proper JSON rendering, it knows nothing about HTML (and it shouldn't). However when you rendering your JSON data in the client side you should properly HTML-escape it using the functionality provided by the JS-templating engine you're using for Backbone.
Answering another question: you can use play.api.templates.HtmlFormat to escape raw HTML-string manually:
import play.api.templates.HtmlFormat
...
HtmlFormat.escape("<b>hello</b>").toString()
// -> <b>hello</b>
If you really need to make JSON-encoder escape certain HTML strings, a good idea might be to create a wrapper for them, let's say RawString and provide custom Format[RawString] which will also HTML-escape a string in its writes method. For details see: play.api.libs.json API documentation

Anchors with SafeHtml

How would you use SafeHtml in combination with links?
Scenario: Our users can enter unformatted text which may contain links, e.g. I like&love http://www.stackoverflow.com. We want to safely render this text in GWT but make the links clickable, e.g. I like&love <a="http://www.stackoverflow.com">stackoverflow.com</a>. Aside rendering the text in the GWT frontend, we also want to send it via email where the links should be clickable as well.
So far, we considered the following options:
Store the complete text as HTML in the backend and let the frontend assume it's correctly encoded (I like&love <a="http://www.stackoverflow.com">stackoverflow.com</a>) -> Introduces XSS vulnerabilities
Store plain text but the links as HTML (I like&love <a="http://www.stackoverflow.com">stackoverflow.com</a>) in the backend and use HtmlSanitizer in the frontend
Store plain text and special encoding for the links (I like&love [stackoverflow.com|http://www.stackoverflow.com]) in the backend and use a custom SafeHtml generator in the frontend
To us, the third option looks the cleanest but it seems to require the most custom code since we can't leverage GWT's SafeHtml infrastructure.
Could anybody share how to best solve the problem? Is there another option that we didn't consider so far?
Why not store the text exactly as it was entered by the user, and perform any special treatment when transforming it for the output (e.g. for sending emails, creating PDFs, ...). This is the most natural approach, and you won't have to undo any special treatment e.g. when you offer the user to edit the string.
As a general rule, I would always perform encoding/escaping/transformation only for the immediate transport/storage/output target. There are very few reasons to deviate from this rule, one of them may be performance, e.g. caching a transformed value in the DB. (In these cases, I think it's best to give the DB field a specific name like 'text_htmltransformed' - this avoids 'overescaping', which can be just as harmful as no escaping.)
Note: Escaping/encoding is no replacement for input validation.

How to implement dynamic GUI in JSP

i have a requirement where i need to display some fields on the JSP. These fields are dynamic in nature, meaning, for ex:, if i changed some value in the dropdown, some fields will be hidden and some other fields might come. I dont want to write Javascripts for show/hide of divs, rather want logic to be coded somewhere at server side.
I have an idea of implementing a custom tag library, but i wnat if i could get an out of the box solution.
any new suggestions or solutions are welcomed.
You had better do it in JavaScript. Having said that, you can send AJAX request to get the new form fields based on the input provided. For example, have a <div> to set the HTML coming from the server.
Use struts framework , there are some tags which can hide and show fields based on values
Logic/logicout tags example
If you want to use a web framework, try Struts 2. It provides tags like <s:if test="some ognl expression" ...> to selectively render html content.
Otherwise you could just go with the JSTL core tags, which provide a <c:if text="some Java EL expression" ...> and a <c:choose ...> tag ( Example ).
Remember to reload the page after changing select box values in order to update the UI.
For this some JavaScript might be needed.
DOM (Document Object Model) in Javascript is very powerful and cross browser.
to remove a node on UI
1.removeChild(nodename)
to add a node on UI
2.elementNode.insertBefore(new_node,existing_node)
I used it. it works well.
more information on DOM.
http://www.w3schools.com/dom/default.asp

suitable web framework for compositing JSON data in to HTML

I'm looking for a good web framework for compositing multiple JSON sources fetched with HTTP requests in to static HTML. I am not looking to do this on the client-side (browser, javascript), I am looking for the best server-side solution.
So, what I need to do is:
Fetch several different JSON documents over HTTP
Format that JSON as HTML content, mostly with templates but some dynamic custom HTML
Basic login/logout/preferences customization, nothing major
Mostly stateless pages; what state there is, comes already in the JSON
User / search engine friendly / bookmarkable URLs; should be customizable accurately
How I'd like to do it:
A lean solution, perhaps just a template engine
HTML templates that have no custom syntax over HTML/XML, like Wicket and almost like Tapestry
Application server that is scalable and utilizes multiple CPUs properly (for example, a single Python process does not)
Preferably Java, but if Java doesn't have anything that fits, willing to consider others
As for the template part, if this were to be in JavaScript in the browser, something like PURE would be my tool of choice.
You might want to check out RESTx. That's an open source platform for the easy creation of RESTful resources. It allows you to write custom data access and integration logic in either Java or Python. Getting data from multiple sources and combining them is what it's made for, so this should be a pretty close fit. Data output is rendered according to what the user requested. For example, a further JSON data source, or the same data rendered in HTML.
The HTML rendering is currently according to a built-in template. However, that should be easy enough to modify. I'm one of the developers on that project, so if you need some special template functionality, let me know and I will see what I can do.
To give you an example: Assume you have two JSON resources, in your code you would write this (I'm giving a Python example here, but the Java example would look very similar):
status, data_1 = accessResource("/resource/some_resource")
status, data_2 = accessResource("/resource/some_other_resource")
# data_1 and data_2 now hold a dictionary, list, etc., depending on the JSON
# that was returned.
# ... some code that combines and processes the data and produces a dict or list
# with the result. The data object you return here is then automatically rendered
# in either HTML or JSON, depending on the client request.
return Result.ok(data)
Also take a look at the example for some simple data integration here.
I think that the only framework you need is a library that reads json. The templates can very well be standard jsp pages.

Categories

Resources