Problems with passing Euro Sign as URL parameter - javascript

I am trying to pass the Euro ( € ) sign as url parameter in my spring jsp. What is the right way to do so ? I tried the following with no avail. Problem is the character is getting encoded properly but not getting decoded from my destination jsp.
I am using
<%#page contentType="text/html;charset=UTF-8" %>
Here is the calling jsp:
<script>
...
// params contains the euro sign
document.location='dest.jsp?p='+escape(params);
In the dest.jsp
<input type="hidden" id="par" value="${param.p}">
and in a script in the same page
console.log($('#par').val())
when I use escape(params) I get the url as %u20AC . But no (empty) values in the dest.jsp
when I use encodeURI(params) or encodeURIComponent I get url as € . But the value in dest.jsp as ⬠- something which I can't use to render as euro sign

I'm going to assume you are using Tomcat because that's what I tested with and we get the same result.
What you will want to do is open up your Tomcat servlet.xml file and find the HTTP connector and add the useBodyEncodingForURI attribute with the value true.
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1"
redirectPort="8443" useBodyEncodingForURI="true">
</Connector>
Then, you will want to register a CharacterEncodingFilter to set the HttpServletRequest character encoding.
You can read more about this behavior in my answer here:
Character encoding in query string, hebrew

You need indeed to encode the € sign which should give %E2%82%AC using UTF-8. You need to be careful with the encoding you use on both ends.
Something like URLEncoder.encode(url, "UTF-8") on the client would do.
If you are using Spring, org.springframework.web.util.UriUtils has also nice utilities you can use.
If the decoding issue is on the server, you need first to make sure that your web container decodes the URI with the proper encoding.
Tomcat decodes URI with ISO-8859-1 by default so you need to update your connector configuration
<Connector port="8080" ...
URIEncoding="UTF-8"/>

See the following answers
Spring MVC: How to store € character?
Getting question mark instead accented letter using spring MVC 3
I think that org.springframework.web.filter.CharacterEncodingFilter should help here.
Try it with and without your encodeURI(params)

Related

In URL `%` is replaced by `%25` when using `queryParams` while routing in Angular

I wanted to navigate to a URL using queryParams while Routing in Angular.
<a routerLink='/master' [queryParams]="{query:'%US',mode:'text'}"><li (click)="search()">Search</li></a>
The URL I wanted to navigate is:
http://localhost:4200/master?query=%US&mode=text
But when I click on search it navigates me to:
http://localhost:4200/master?query=%25US&mode=text
I do not know why 25 is appended after the % symbol. Can anyone tell me a cleaner way to navigate correctly.
In URLs, the percent sign has special meaning and is used to encode special characters. For example, = is encoded as %3D.
Certain special characters are not allowed in url. If you want to use those in url you have to encode them using encodeURIComponent javascript function.
%25 is actually encoded version of % character. Here browser is encoding them itself.
When trying to get queryParams from url , you can decode them using decodeURIComponent.
For more information check : https://support.microsoft.com/en-in/help/969869/certain-special-characters-are-not-allowed-in-the-url-entered-into-the
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent

How to escape database path

I have a field in a notesdocument containing a path to a database using backslases (i.e Folder1\Folder2\start.nsf)
and I am trying to redirect users when clicking a div with the following client side code
location.href= "#{javascript:dbdoc.getItemValueString('DatabasePath')}"
but the back slases are not returned , all I get is a string with all the folders without slashes so the url do not work
how can I escape the path correctly so that the link works?
Thanks
Thomas
Use JavaScript's escape function:
location.href= "#{javascript:escape(dbdoc.getItemValueString('DatabasePath'))}"

What is the right way to deal with special characters in resource URIs? How to properly escape?

Our application implements APIs to access entity details via AJAX GET requests - it once used POST but we decided to change our standards.
Unfortunately we hit a design flaw recently.
Suppose our API is http://localhost/app/module/entity/detail/{id} where {id} is a Spring #PathVariable that matches that entity's primary key.
If the primary key is a numeric surrogate key (auto-increment) there is no problem then. But we thought that this all worked with String primary keys.
It happened that we found some valid production data contain slashes, backslashes and semicolons for primary key. Our tables cannot use auto-increment surrogate keys because of their gargantuar size.
More in general, we discovered that we were unprepared to handle non-alphanumeric characters.
What the defective code was originally
Here is how our application used to reach to display entity data in a single page form the entity list:
User navigates table.jsp where an AJAX list is retrieved via POST
An Angular expression constructs the link to the detail page of that entity by means of detail?entityId={{::row:idAttribute}}
A valid link is generated by Angular
Examples:
detail?entityId=5903475934 //numeric case, we have several details page with same navigation pattern
detail?entityID=AAABBBCCC
detail?entityID=DO0000099101\test
The user clicks on the link and the browser points to the corresponding address
http://localhost/blablabla/detail?entityId=DO0000099101\test //Could be escaped.... read more later
The page needs the ID code from the parameters to issue the correct AJAX call
Need to retrieve the Entity ID from the query string. The Angular controller is in a separate file that doesn't see the query string (and is included dynamically, having the same page name)
<script type="text/javascript">
var ____entityId = '${param.entityId}';
</script>
Which gets translated to
<script type="text/javascript">
var ____entityId = 'DO0000099101\test'; //Yes, I know it's incorrect because now we have a TAB
</script>
Angular fetches the Entity ID into the page scope
In the Angular controller, we do the following
$scope.entityId = ___entityId;
$http.get($const.urlController+'detail/'+$scope.entityId)
Ajax call is issued
http://localhost/blablablabla/entity/detail/DO0000099101est //URL is bad
Spring MVC decodes the #PathVariable
Unfortunately, the parameter is treated as DO0000099101est
What we tried to fix
We have tried to fix the mistake by escaping the \t as it is clear that its presence in the HTML content constitutes a bug. Javascript interprets it as a tab.
Trying to URL-escape the ID
We tried to manually navigate to http://localhost/blablabla/detail?entityId=DO0000099101%5Ctest by escaping the backslash to its URL entity. The purpose is that if this worked we could modify Angular code in the table page
The result is that the \t appeared again as it is in the Javascript fragment. From that point, the sequence is the same
<script type="text/javascript">
var ____entityId = 'DO0000099101\test';
</script>
Trying to Java-escape + URL-Escape the ID in the URL
What if the Angular table page escaped the URL by this way?
http://localhost/blablabla/detail?entityId=DO0000099101%5C%5Ctest
<script type="text/javascript">
var ____entityId = 'DO0000099101\\test'; //Looks great
</script>
Unfortunately Angular now reverses the backslash into a forward slash when performing the Ajax request
http://localhost/blablabla/detail/DO0000099101/test
Trying to perform the Ajax call manually with escaped URL
So know that the REST url is http://localhost/app/module/entity/detail/{id}, let's try to see how Spring expects the backslash to be escaped
http://localhost/app/module/entity/detail/DO0000099101%5Ctest //results in 400 error
http://localhost/app/module/entity/detail/DO0000099101\\test //Chrome reversed the backslash into a forward slash and the result is 404 as expected for http://localhost/app/module/entity/detail/DO0000099101//test
Using encodeURIComponent
We already tried this (but I didn't mention in the original post). To #Thomas comment, we tried again to encode the primary key by Javascript escaping in the controller itself.
$http.get($const.urlController+'detail/'+encodeURIComponent($scope.entityId))
The problem with this approach is that the backslash-T sequence in the URL is encoded to %09, which results in a tab decoded on the server side
Using both encodeURIComponent and a Java escape
Now we tried to use both approach #4 and fixing the hardcoded Java-escaped (i.e. \\t) into the Javascript for testing purposes.
<script type="text/javascript">
var ____entityId = 'DO0000099101\\test';
</script>
$http.get($const.urlController+'detail/'+encodeURIComponent($scope.entityId))
This time the Ajax call resulted in 400 error as case #3
http://localhost/app/module/entity/detail/DO0000099101%5Ctest //results in 400 error
Question time
I want to ask this question in two ways, one specific and one more general.
Specific: how can I properly format a #PathVariable so that it can preserve special characters?
General: in the REST world, what care is to be done when dealing with resource IDs that may contain special characters?
For the second, let me be more clear. If you control your REST application and generation of IDs, you can choose to allow only alphanumeric identifier (user-generated or random or whatever) and sleep happy.
But in our case we need to browse entities that come supplied from external systems that have broader restrictions on character sets allowed for entity primary identifiers.
And again, we cannot use auto-increment surrogate keys.

What is the correct way to embed (string) data in element attibute?

I would like to send data from the server to the client, where javascript code can access the data. This is basically a string message, what I would like to embed in my custom attribute like this:
<div my-message="here is my custom data">
After short testing I recognized the message itself can contain special char like " so the html will be incorrect after embedding.
What is the correct way to (encode?) the string data? (server side is ASP MVC)
Is there any javascript support to decode the string? Obviously say base64 can do it, but it sounds a bit weird, and also I would not like reinvent the wheel here.
For server side:
Razor
<div data-my-message="#("your string with \" goes here")">
Or if you hold the string in the Model
<div data-my-message="#Model.Message">
ASPX
<div data-my-message="<%: "your string with \" goes here" %>">
Razor's #() or ASPX's <%: %> will encode it correctly.
BTW If you want to embed your string directly in the view you can escape the " with \"
For client side:
You can read it easily with jQuery
$(selector).data("my-message")
or plain javascript
document.querySelector(selector).dataset.myMessage
Also you should prefix your custom attributes with data- as #Erik Philips says in the comments
You can use the functions encodeURI and encodeURIComponent for encoding. And for decoding the functions decodeURI and decodeURIComponents.
You can look them up for example here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
If you want to send arbitary data (i.e. arrays, objects, etc.) then I use the following:
use a data-foo attribute on the tag
json-encode the data
Use single quotes around the attribute value (JSON uses double quotes for strings)
Replace any single-quotes in the json-encoded string with the corresponding thml entity (&#8217)
Something like (I did it in PHP so the .net syntact might be slightly wrong
<% Dim Serializer As New System.Web.Script.Serialization.JavaScriptSerializer %>
<div data-foo='<%=Serializer.Serialize(MyData).Replace("'", "&#8217") %>'>Some content</div>
Where the data to use is in the variable MyData
Has the advantage that when you get out the data you get an object back automatically (at least, with jQuery but I would imagine with plain js too - if not then it's easy to recreate the object)
Update
Following the comment about double quotes, if your data is just a string then you should replace double quotes buy their html entity too. Or ensure you json-deode. It's not automatically recognised as json data and decoded if it's just a string. PHP (where I have used this more) encopdes double quotes in the string as \". I have a memnory that in vb.net you need to change Serializer.Serialize(MyData).Replace("'", "&#8217") to Serializer.Serialize(MyData).Replace("\", "\\").Replace("'", "&#8217") becuase of how it handles quotes. If the data is an object then it is automatically json-decoded when you get it out and alls is OK. if the data is just a string then don't need to json-encode maybe - just change at least one of the type of quotes (either single or double quotes) to html entities and use that quote type around the attribute.
As long as you get the quoting right it handles html in the data fine: see http://jsfiddle.net/ctueo7sr/ for a simple string example and http://jsfiddle.net/aLaLnhp2/1/ for an object example

Passing parameter by URL

I am using asp.net MVC 3.0. I want Passing parameter with URL. It works. But if my parameter value is like shahin & karina. Then it count as a two value beacuse of &. I want to inculed & as a vlue. How can I do that. Please, Anyone has solved this kind of problem.
For example:
My controller function is:
public ActionResult Index(string name)
{}
html code
<a href="/stat?name=shahin & karina">
Form the controller I got only name value is: shahin
But I need Name value is: shahin & karina
Thanks advance..
I believe all you would need to do is URL encode the ampersand (and possibly the space character).
Try something like this -
<a href="/stat?name=shahin%20%26%20karina">
%20 is an encoded space character.
%26 - is the encoded ampersand character.
I have absolutely zero knowledge or experience with asp.net but I'm fairly sure that there are native URL encoding functions...
You need to encode the URL. There is surely a library for it in .NET.
Similar tools:
http://meyerweb.com/eric/tools/dencoder/
Cheers
HH
You have to encode '&' as an HTML entity.
<a href="/stat?name=shahin%20%26%20karina" />
Try rewriting the html code as:
<a href="/stat?shahin%20%26%20karina" />
%20 is a url-encoded space and %26 is the url-encoded ampersand
You can use this tool to try encoding different strings (in this example, you would encode "shahin & karina")

Categories