Adding HTML hyperlinks to java resource bundle properties files - java

I'm using Java Resource Bundles to manage messages.
I need to display a message in a JSF page and the message also contains some HTML markup.
Unfortunately the HTML code is also displayed on screen instead of been rendered as HTML by the browser:
I.E
Click me here
My message in properties file:
clickme=Click me here
My JSF:
<h:outputText value="#{messages['clickme']}" />
Any ideas?
Thanks

JSF/Facelets escapes by default HTML special characters in order to prevent XSS attacks when redisplaying user-controlled data. You can turn it off on a per-<h:outputText> basis by explicitly setting the escape attribute to false.
<h:outputText value="#{messages['clickme']}" escape="false" />
You only need to make absolutely sure that you don't do this for unsanitized user-controlled data, which is everything which comes in with a HTTP request such as headers, cookies, parameters, body, etc.

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.

How to solve encoding problems when using strange characters of titles in JSF and Primefaces

I am in trouble with encoding values. Well I am developing a web page with spanish content, and it uses tittles like ó,á,è, etc, or characters like ñ. Then when I pressed the button to save the values, I guess the ajax event for a button didn't take the encodig, them I add encoding='ISO-8859-1', and it worked. But I have an autocomplete for countries in primefaces that also use an ajax event to proccess information, and for this field the encoding doesn't work and before to add encoding='ISO-8859-1' it worked. Well when solve one, the other one failed, and vice versa.
Happen that I need the country to consult the states and list them.
Web code:
<p:autoComplete id="pais" value="#{personal.pais}"
completeMethod="#{personal.listPaises}" forceSelection="true" required="true" effect="fade" scrollHeight="400"
var="p" itemLabel="#{p}" itemValue="#{p}" requiredMessage="Es necesario seleccionar país" label="País" validator="#{personal.validatePaises}" >
<p:column style="width:80%" >
#{p}
</p:column>
<p:ajax event="itemSelect" update="departamento" />
</p:autoComplete>
Java Code:
public void setPais(String pais) {
int codPais = pDao.getPaisCod(pais);
departamentosList = pDao.listDepatamentosByPais(codPais);
this.pais = pais;
}
For example if I choose España as Country in jsf form, in the bean is taken as Espa±a.
I need unify the encodig.
Thanks a lot.
You should just use UTF-8, it will support any character and more importantly it is the only encoding that everything has in common. Often something will only work with UTF-8, such as many JSON implementations. And when that isn't the case, JSON cannot support ISO-8859-1 anyways.
For instance, primeface's Ajax uses jQuery.param, which uses encodeURIComponent, which uses URL encoding that is based on UTF-8.
So if you want to unify encoding, UTF-8 is your only option.
Btw, by "use UTF-8", I don't mean just to put UTF-8 in a random place that seems right but actually ensure UTF-8 is the declared and physical encoding everywhere in your project.
I know that my problem was with ajax request of autocomplete and commandButton.Then I tried everything and didn't work. well I solve my problem changing my jsf commandButton to Primefaces commandButton.
Before
<h:commandButton value="submit" action="Periodico?faces-redirect=true" actionListener="#{personal.insertarUsuario}" />
After
<p:commandButton value="submit" action="Periodico?faces-redirect=true" actionListener="#{personal.insertarUsuario}" />
And so I solve my problem. Thanks a lot for your time and answers

How to use JSF tags in resource bundles / How to rewrite URLs in a resource bundle?

Enviornment:
JSF 2.1.7
SEAM 2.3.0
JBOSS 5.1.2
My application has a string that needs to be localized
"I agree to WorldSite's Privacy Policy and Cookie Notice"
Where the italicized Privacy Policy and Cookie Notice are hyperlinks to other pages.
Originally our facelet was set up like this:
<h:outputText value="#{messages['iAgreeTo']}" />
<h:outputLink target="_blank" value="#{bean.privacyPolicy}">#{messages['privacyPolicy']}</h:outputLink>
<h:outputText value="#{messages['and']}"/>
<h:outputLink target="_blank" value="/jsf/Notice.xhtml">
<h:outputText value="#{messages['cookieNotice']}"/>
<f:param name="content" value="Cookie-Notice"/>
<f:param name="application" value="#{bean.application}"/>
</h:outputLink>
Note: We have URL rewriting in place that takes /jsf/Notice.xhtml and rewrites to
rewrite pattern: /#{application}/Notice/#{content}
result:http://contextRoot/contextPath/myApp/Notice/Cookie-Notice
This allowed for piecemeal translations of the individual keys
iAgreeTo=I agree to WorldSite's 
privacyPolicy=Privacy Policy
and= and 
cookieNotice=Cookie Notice
But this required a workaround for some languages (in "iAgreeTo" and "and" keys)
iAgreeTo=J'accepte la 
privacyPolicy=Politique de la vie privée
and= de WorldSite et les 
cookieNotice=Note D'information sur les Cookies
Ideally I would like to be able to have the links be movable within the key. Something like this:
iAgreePhrase=I agree to WorldSite's #{messages['privacyPolicyLink']} and the #{messages['cookieNoticeLink']}
privacyPolicy=Privacy Policy
cookieNotice=Cookie Notice
//The following non-translatable keys held in a separate file
privacyPolicyLink=<h:outputLink target="_blank" value="#{bean.privacyPolicy}">#{messages['privacyPolicy']}</h:outputLink>
cookieNoticeLink=<h:outputLink target="_blank" id="cookieNoticeLink" value="/jsf/Notice.xhtml">\
#{messages['cookieNotice']}\
<f:param name="content" value="Cookie-Notice"/>\
<f:param name="application" value="#{bean.application}"/>\
</h:outputLink>
But the facelet returns the JSF tags (h:outputLink) as strings instead of expanding them to their HTML tags. I can use <a> tags, but then I'm putting rewrite logic in the properties file which is difficult to maintain
iAgreePhrase=I agree to WorldSite's #{messages['privacyPolicyLink']} and the #{messages['cookieNoticeLink']}
privacyPolicy=Privacy Policy
cookieNotice=Cookie Notice
//The following non-translatable keys held in a separate file
privacyPolicyLink=<a target="_blank" href="#{bean.privacyPolicy}">#{messages['privacyPolicy']}</a>
cookieNoticeLink=<a target="_blank" href="#{contextPath}/#{bean.application}/Notice/Terms-and-Conditions">\
#{messages['cookieNotice']}</a>
Is there a way I can achieve my desired effect without having to put rewrite logic in the resource bundle? Some thoughts I have are forcing the application container to process the facelet twice/reorder it, so it inserts the resource bundles first, and then expands the JSF tags.
Alternatively I may be able to construct the rewritten URL in a bean then call that from my resource bundle?
You seem to have got everything round the wrong way and I'm sorry to have to say that I found the question poorly analysed, overlong and confusing to read.
What you should be trying to do is use resource bundles from within JSF tags and not the other way round. Where you need to parameterise a message you use a construct such as this:
messages.properties
nameHeader=My name is {0}
index.xhtml
<h:outputFormat value="#{msgs.nameHeader}">
<f:param value="#{bean.name}"/>
</h:outputFormat>
If you have a scenario where this doesn't work you would have to build the string in a backing bean.
While Oversteer's answer is certainly applicable, this could also prove helpful. You can create URLs from EL expressions like this:
#{facesContext.externalContext.encodeActionURL('/myapp/Notice/Privacy-Policy')}
To include HTML markup in a message, you need to use escape="false" in <h:outputText/>, for example:
<h:outputText escape="false" value="#{messages['iAgreePhrase']}" />
And, in your messages.properties (or localized version):
iAgreePhrase=I agree to WorldSite's Privacy Policy and ...
This has the problem that the URL is calculable only from within an HTTP request, if you for example use the message key from within an asynchronous thread, the URL will not be calculated (there's no facesContext available).

request.getCharacterEncoding() returns NULL... why?

A coworker of mine created a basic contact-us type form, which is mangling accented characters (è, é, à, etc). We're using KonaKart a Java e-commerce platform on Struts 1.
I've narrowed the issue down to the data coming in through the HttpServletRequest object. Comparing a similar (properly functioning) form, I noticed that on the old form the request object's Character Encoding (request.getCharacterEncoding()) is returned as "UTF-8", but on the new form it is coming back as NULL, and the text coming out of request.getParameter() is already mangled.
Aside from that, I haven't found any significant differences between the known-good form, and the new-and-broken form.
Things I've ruled out:
Both HTML pages have the tag: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
Both form tags in the HTML use POST, and do not set encodings
Checking from Firebug, both the Request and Response headers have the same properties
Both JSP pages use the same attributes in the <%#page contentType="text/html;charset=UTF-8" language="java" %> tag
There's nothing remotely interesting going on in the *Form.java files, both inherit from BaseValidatorForm
I've checked the source file encodings, they're all set to Default - inherited from Container: UTF-8
If I convert them from ISO-8859-1 to UTF-8, it works great, but I would much rather figure out the core issue.
eg: new String(request.getParameter("firstName").getBytes("ISO-8859-1"),"UTF8")
Any suggestions are welcome, I'm all out of ideas.
Modern browsers usually don't supply the character encoding in the HTTP request Content-Type header. It's in case of HTML form based applications however the same character encoding as specified in the Content-Type header of the initial HTTP response serving the page with the form. You need to explicitly set the request character encoding to the same encoding yourself, which is in your case thus UTF-8.
request.setCharacterEncoding("UTF-8");
Do this before any request parameter is been retrieved from the request (otherwise it's too late; the server platform default encoding would then be used to parse the parameters, which is indeed often ISO-8859-1). A servlet filter which is mapped on /* is a perfect place for this.
See also:
Unicode - How to get the characters right?
The request.getCharacterEncoding() relies on the Content-Type request attribute, not Accept-Charset
So application/x-www-form-urlencoded;charset=IS08859_1 should work for the POST action. The <%#page tag doesn't affect the POST data.

Spring MVC: Relative URL problems

I have a controller bound the URL: "/ruleManagement".
Inside my JSP, I have a form that forwards (on submit) to "ruleManagement/save" url. When there are errors with the input fields, I want it to return back the original form View. This is where the problem starts...
Problem 1) Now that the URL is "/ruleManagement/save", my form submit now points to "/ruleManagement/ruleManagement/save".
Problem 2) I tried using spring:url tag to generate the absolute paths for me, which usually works great. But when I put a spring:url tag inside of a tag, the spring:url tag does not get parsed correctly.
<form:form action="<spring:url value='/ruleManagement/save' ...>" method="post">
When I analyze the DOM after the page loads, my form tag looks something like:
<form action='<spring:url value="/ruleManagement/save" />' ... >
If I don't use the spring:url tag, and instead use just "/ruleManagement/save", the url generated excludes my application name in the url, which is also wrong.
How do I generate a consistent URL pattern across all Views regardless of path? If the answer is "using spring:url", how do I get that content inside a form:form tag?
Custom tags in JSP can't be used in attributes of other custom tags, so you need to store intermediate result in a request attribute (using var to redirect output of the tag to the request attribute is a common idiom supported by many tags):
<spring:url var = "action" value='/ruleManagement/save' ... />
<form:form action="${action}" method="post">
I too would love to be able to generate a consistent URL path across all Views! Is this possible with <spring:url .../>.
To answer your second question & tacking on to axtavt's answer, embed the <spring:url ... /> into the form action after adding the property htmlEscape="true"
Example: <form:form action="<spring:url value="/ruleManagement/save" htmlEscape="true" .../>" method="post">

Categories

Resources