Getting wrong characters in parameter - java

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.

Related

Output string as html in freemarker

So we are storing html in out data model. I need to output this into a freemarker template:
example:
[#assign value = model.value!]
${value}
value = '<p>This is <a href='somelink'>Some link</a></p>'
I have tried [#noescape] but it throws an error saying there is no escape block. see FREEMARKER: avoid escaping HTML chars. This solution did not work for me.
[#noescape] or <#noescape> is only valid when used inside an [#escape] tag. Your data is probably stored with the HTML encoded. You need to get the backend to un-encode the html.
Otherwise you'll need to do something like...
${value?replace(">", ">")?replace("<", "<")}
But that isn't a good approach because it won't catch all the encoded values and shouldn't be done in the view layer.

Displaying a JSF requestLink parameter containing a + sign

Strange one this. I have a tag in my JSF page which contains a parameter that contains a + sign. When the resulting hyperlink is clicked the URL converts the + sign to a space, as this is how spaces in URLs are represented.
Is there any way of encoding this parameter to display "%2b" (which is the urlencoded string) instead of +? I am using JSF 1.2
<hx:requestLink styleClass="requestLink" id="link31"
action="#{sellingMarginBean.changeView}">
<h:outputText styleClass="outputText" id="text81"
value="#{varsummaryDataList.tier.description}"></h:outputText>
<f:param
value="#{varsummaryDataList.tier.tierCode}"
name="tierCode" id="param51"></f:param>
</hx:requestLink>
If I change the value of tierCode to replace any '+' with '%2b' before putting out to the screen this works, but it's a hack at best as it means creating a custom method on my Tier domain object or cycling through summaryDataList and performing the replace.
Thanks in advance
Steve
According to this post by BalusC:
JSP/Servlet request: during request processing an average application server will by default use the ISO 8859-1 character encoding to URL-decode the request parameters. You need to force the character encoding to UTF-8 yourself. First this: "URL encoding" must not to be confused with "character encoding". URL encoding is merely a conversion of characters to their numeral representations in the %xx format, so that special characters can be passed through URL without any problems. The client will URL-encode the characters before sending them to the server. The server should URL-decode the characters using the same character encoding.
So probably your client and server are not using the same URL(URI)-encoding. Your best bet is to force the server itself to use UTF-8 encoding. That depends on what server you're using.
You could also use JSTL's fn:replace for your parameter, as an alternative but more "hacky" solution. Remember to define the JSTL taglib in your namespace set (xmlns:fn="http://java.sun.com/jsp/jstl/functions").
<f:param
value="#{fn:replace(varsummaryDataList.tier.tierCode, '+', '%2b'}"
name="tierCode" id="param51" />
See also:
POST parameters using wrong encoding in JSF 1.2
JSF 2.0 request.getParameter return a string with wrong encoding
How can I manipulate a String in a JSF tag?

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}">

Get parameter with the character '#' from a query string on java

I am trying to get a request string that has the character # and my parameter is got only until the #. But the thing is that I need to have this character, can't remove it.
Any idea?
Encode the # if it has to be there. A literal # indicates a fragment id and can't be used in a URI for any other purpose. w3schools has encoding tables so you can look up the values yourself, too.
You need to encode the parameter value correctly.
If the URL is generated by a JSP, make sure to use the JSTL c:url tag:
<c:url value="/path/to/myServlet">
<c:param name="param1" value="#paramValue"/>
</c:url>
If you're using straight Java, use URLEncoder.encode().
If the URL is static, use %23paramValue instead of #paramValue

firefox a href # symbol causes setter not to be called

Morning all,
It early Monday morning and I'm struggling to understand why the followng line works in IE and not in FF.
<a class="button" href="#" onclick="setMaintenanceMode(false);">disable</a>
In both IE and FF the URL when you hover over the button is...
http://localhost:8080/mainapp/secure/gotoDevice.action?hardwareId=1&storeCode=2571#
When the button is clicked, the following method is called...
function setMaintenanceMode(enabled) {
var url = '<s:url action="secure/setMaintenanceMode"/>' + '&ModeEnabled=' + enabled;
document.location.href = url;
}
The URL that docuement is sent to is (in both browsers)...
/mainapp/secure/gotoDevice.action?hardwareId=1&storeCode=2571&ModeEnabled=false
The problem is that in IE the method on the struts action 'setSetCode()' is called, but from FF its not! If I remove the hash ahref above FF works, but IE doesn't (href="#").
I've tried changing the '&ModeEnabled=' to '&ModeEnabled=', but no success.
I've looked on google and the struts forum, but no success.
I'm tempted to rip out all the ahref's and replace them with Dojo buttons and see if that works, but before I do, I just wondered if anyone could shead some light on why.
My guess is that ahref is the wrong thing to use, but why?
If anyone could help me understand why though it would be appreciated.
Thanks
Jeff Porter
EDIT: The return false is part of the solution. The problem seems to be that the url..
/mainApp/secure/setMaintenanceMode.action?hardwareId=5&storeCode=2571&ModeEnabled=true
has the & inside it, if I go to this url as it is, then it works in IE, but not in FF.
if I change both to be & then it works in IE & FF.
if I change both to be & then it still works in IE but not FF.
Any ideas?
Note:
Seems that struts 2.0.9 does not support the property escapeAmp on the <s:url tag:
By default request parameters will be separated using escaped ampersands (i.e., &). This is necessary for XHTML compliance, however, when using the URL generated by this tag with the <s:property> tag, the escapeAmp attribute should be used to disable ampersand escaping.
soultion: return false on the onclick and upgrade to new struts + set escapeAmp param.
else, url = url.replace("&", "&");.
Try returning false from the javascript method
function setMaintenanceMode(enabled) {
var url = '<s:url action="secure/setMaintenanceMode"/>' + '&ModeEnabled=' + enabled;
document.location.href = url;
return false;
}
<a class="button" href="#" onclick="return setMaintenanceMode(false);">disable</a>
This should stop the javascript onclick event reaching the browser.
onclick="setMaintenanceMode(false); return false;"
The onclick is working, but then the href does immediately, as well. You need to return false from the click handler to signal that href should not be followed.
IE likely guesses at what you mean, and does the wrong thing.
the URL has the & inside it, if I go to this url as it is, then it works in IE, but not in FF.
I doubt it – it shouldn't work in either. It's not browser-dependent, but server-dependent.
The string a=b&c=d is split into parameters by the server framework. Servlet requires that only & be used to separate parameters, so it will return a=b and amp;c=d. The latter parameter obviously won't be recognised by the application which is expecting c.
The HTML specification for various reasons strongly recommends that ; also be allowed as a separator, in which case you'd get a=b, a stray amp which without an equals sign would be meaningless and discarded, and c=d. So despite the mis-encoding of the ampersand it would still work. Unfortunately, Servlet ignores this recommendation.
By default request parameters will be separated using escaped ampersands (i.e., &).
Oh dear! How unfortunate. You shouldn't escape ampersands at the point of joining parameters into a URL. You should simply join the parameters with a single ampersand, and then, if you need to put the finished URL into an attribute value of text content, HTML-encode the entire URL. Struts's default behaviour is simply wrong here.
In your case you are not outputting the URL to an attribute value or text content, you're writing it into a string literal in a script block:
var url = '<s:url action="secure/setMaintenanceMode"/>' + '&ModeEnabled=' + enabled;
In a script block in old-school HTML, HTML-escaping does not apply. (In XHTML in native XML it does, but let's not think about that yet.)
However, you still do need to think about JavaScript escapes. For example what if there were an apostrophe in the setMaintenanceMode link? It would break the string. Or if somehow you had a </ sequence in the string it'd break the entire script block.
What you really want to be doing is making the URL (without any ampersand-escaping), and then use a JavaScript string literal backslash-escape on it. Best would be to use an existing JSON encoder which will turn any Java value into a JavaScript literal, putting the surrounding quotes in for you too if it's a string. You can also on most JSON encoders tell it to JS-escape the < and & characters, which means not having to worry about XHTML parsing if you decided to serve the page as XML in the future.
I'm tempted to rip out all the ahref's and replace them with buttons
Well certainly if you have a thing you click on that isn't a link to another location, but simply does something to the page via script, then that's not a link really, and you'd be much better off marking it up as a <button> or <input type="button">, and using CSS to restyle it not to look like a button if you don't want it to.
However (again), this all seems rather pointless, as at the moment you are replacing the behaviour of a link with behaviour that just like a link only not as flexible. What's wrong with simply:?
disable

Categories

Resources