why is '<' showing as < - java

I am outputting a string form my java class like this
String numQsAdded = "<div id='message1'>"+getQuestion()+"</div>";
This string is being sent back to the client side as a XMLHttpRequest. So, in my jsp page I have a javascript alert method that prints out the string returned from the server. it translates '<' to < and '>' to >
how can i avoid this?
I have tried changing my string to:
String numQsAdded = "<div id='message1'>"+getQuestion()+">/div<";
but this has even worse effects. then '&' is translated as 'amp'

XMLHttpRequest encodes the string before sending it. You will have to unescape the string.
on the client side javascript, try using:
alert(unescape(returned_string))

< is the way to show "<" in html, which is produced from XMLHttpRequest. try using XMLRequest

It is the entity reference for "<" while &gt ; is the entity reference for ">" you will need to unescape the string using the unescape() method

Paul Fisher's answer is the right one. I'll take a moment to explain why. HTML-Encoding of content from the server is a security measure to protect your users from script injection attacks. If you simply unescape() what comes from the server you could be putting your users at risk, as well as your site's reputation.
Try doing what Paul said. It's not difficult and it's much more secure. Just to make it easier, here's a sample:
var divStuff = document.createElement('div');
divStuff.appendChild(containerElement);
divStuff.id = 'message1';
divStuff.innerHTML = getQuestion();
This is much more secure and draws a better separation for you presentation layer in your application.

It might be better to send back a raw string with your message, and leave the client Javascript to create a div with class message1 to put it in. This will also help if you ever decide to change the layout or the style of your notices.

I don't think you can avoid that. It's how "<" is represented in HTML, and the result would be OK on your HTML page.

Related

HTML entities incorrectly encoding in API call

I am about to use Paxful API method for sending a message to trade:
String message = "Do NOT PRESS 'Paid' button, until your transfer get 'Success' status.";
paxfulService.sendMessage(tradeId, message);
But here is what I see in the browser:
This is my fault, or Paxful API use unnecessary HTML encoding?
The API you are using is re-encoding the single quotes back into their hex values.
In your original message string try using ' in the place of the single quotes you have.

Charset trouble (ø as 00F8)

I am getting a string from our database (third party tool) - and I have a trouble with one
name - sometimes it is right "Tarsøy", and all runs smoothly but sometimes it is "Tars00F8y".
And this ruins the process - I have tried to write some validator function via URLDecoder.decode(name, "UTF-8") that gets a string and return validated one but not succeed.
this is how I get a sting from our base:
Database.WIKI.get(index); // the index is the ID of the string
// this is no sql DB
now about "sometimes" - it means that this code just works different =) I think that is connected with inner DB exceptions or so. So I am trying to do something like validate(Database.WIKI.get(index))
May be I should try something like Encode String to UTF-8
In Java, JavaScript and (especially interesting) JSON there exists the notation \u00F8 for ø. I think this was sent to the database, maybe from a specific browser on a specific computer locale. \u disappeared and voilà. Maybe it is still as invisible control character in the string. That would be nice for repairs.
My guess is JSON data; however normally JSON libraries should parse u-escaped characters. That is weird.
Check what happens when storing "x\\u00FDx". Is the char length 6 or maybe 7 (lucky).
Some sanity checks: assuming you work in UTF-8, especially if the data arrive by HTML or JS:
Content-Type header text/html; charset=UTF-8
(Optional) meta tag with charset=UTF-8
<form action="..." accept-charset="UTF-8">
JSON: contentType: "application/json; charset=UTF-8"

Send a tag in a url

First, sorry for my english it's not my native language.
So, I am working on an application in JSP and in one of my forms I have a field "comments". When I submit this form, the value of this field is sent to my servlet by an ajax request.
var request = 'mainServlet?command=SendRequest';
request += ('&comments=' + $('#comments').val());
But when there is a "<" or ">" in the field, $('#comments').val() translate them into "&lt" or "&gl". For exemple, is converted to &lt ;test&gl ;
And when I want to recover the value in my servlet, I do:
String comments = request.getParameter("comments");
But the url looks like : mainServlet?command=SendRequest&comments=&lt ;test&gl ;
So request.getParameter("comments"); returns an empty string.
I thought that I could replace the string like &lt by my own code and then replace it again in my servlet, but is there a simpler way to do this?
Thanks.
Edit: After, I reuse the comments in an other jsp.
I believe what you need is the encodeURIComponent function. It will convert any string into a format that you can use inside a URI.
Just remember to decode it on the receiving end, I believe the URLDecoder class can do this for you.

Java: Carriage returns populating a var in js code?

I am not sure if this is possible, but I'm trying to find a front-end solution to this situation:
I am setting a JavaScript variable to a dynamic tag, populated by backend Java code:
var myString = '#myDynamicContent#';
However, there are some situations, in which the content from the output contains a carriage return; which breaks the code:
var mystring = '<div>
Carriage Return happened above and below.
</div>';
Is there anyway I can resolve this problem on the front-end? Or is it too late in the script to do something about it, because the dynamic tag will run before any JavaScript runs (thus the script is broken by that point)?
I'm sure my JS could be cleaned up (just thought this was a fun problem), but you could search out the comment in the JS.
Lets say your JS looks like this (noticed I added a tag to the comment so we know we're going after the correct one, and there is a div to just for testing):
<script id="testScript">
/*<captureMe><div>
Carriage Return happened above and below.
</div>
*/
var foo = 'bar';
</script>
<div id='test'>What do I see:</div>
Just use this to grab the comment:
var something = $("#testScript").html();
var newSomething = '';
newSomething = something.substr(something.indexOf("/*<captureMe>")+13);
newSomething = newSomething.substr(0, newSomething.indexOf("*/"));
$('#test').append('<br>'+newSomething); // just proving we captured the output, will not render returns or newline as expected by HTML
Technically, it works :), scripting-scripting...
Charbs
JavaScript supports strings that can span multiple lines by putting a backslash (\) at the end of the line, for example:
var myString = 'foo\
bar';
So you should be able to do a Java replace when you write in your server-side variable:
var myString = '#myDynamicContent.replaceAll("\\n", "\\\\n")#';
Replace the \n and/or \r with \\n and/or \\r respectively ... but it has to be done in the server-side language (in your case Java); it can't be done in JavaScript.
Building off of #Charbs' answer, you could avoid the JavaScript comments if you give your script tag a different mime type, so the browser won't try to evaluate it as JavaScript:
<script id="testScript" type="text/notjs" style="display:none">#myDynamicContent#</script>
And then just grab it like this (using jQuery):
var myString = $('#testScript').text();
To me it looks like you're doing token replacement instead of using a template engine. If you like token replacement you might Snippetory too, as it creates similar code. However it has a number of additional features. Using
var myString = '{v:myDynamicContent enc="string"}'
would create
var mystring = '<div>\r\n Carriage Return happened above and below.\r\n </div>'
And thus solve your problem. But you would have to change your code behind, too.

Set [Automatically wrap text] in Java mail

i have an account register function, after user inputted personal data, an confirm email will be sent to that customer with a generated link. The problem is that: because the link is too long, it is broken into two lines (The second line is from character 76) and the second line does not belong the the first line (User cannot click on the whole link). I think this problem may come from the word wrap or something like that
In Outlook Express, under menu->Tools->Options->Send->HTML setting, we can set number of characters that the email content should be wrapped in each line by changing the value. Is there any way to set this function using core Java Mail?
Thank you in advance.
Word wrapping is done by the viewer (i.e. Outlook Express) not when sending email. I would guess that you are sending plain text emails and relying on the viewers to try and identify that it contains links. Try sending HTML mail and using ''
No, JavaMail is a library allowing you to send/receive email through Java. It is not an application like Outlook/Outlook Express or Thunderbird for that matter.
That said, you can write code that does the formatting before it invokes JavaMail to send the email out.
First, you can't set a setting in java mail to change a client's formatting.
Second, while my solution might not be the best answer to the question. It should help with the problem you are having.
Before adding your link into the body of the mail make sure you;
Put the link on a new line. "\n" ;)
Make a little method using URL shortening API like bitlyj for bit.ly to shorten the URL. Add the shortened link and walla!
msg.setContent("This is an example of adding a shortened URL\n"
+ shortLink("http://www.longlink.com")
+ "\n", "text/plain");
public String shortLink(String link) {
Url url = as("Username", "APIKey").call(shorten(link));
return url.getShortUrl();
}
Using this approach you shouldn't have any issues with word wrap stuff.

Categories