Jquery html() encoding error in chrome - java

I'm developing an Java Web Application, I used some jQuery and a REST web services that output an JSON object with a list of Javascript objects using AJAX. All is ok but when I try to fill a table created with Javascript using jQuery.html() to a valid div, all hell broke loose in Chrome, including this
Error: INVALID_STATE_ERR: DOM Exception 11
in the Javascript console.
The problem is like this, try this in chrome Javascript console:
$('#ValidadorWrapper').html("<div>AMOXICILIN 100 C&psulapsula</div>");
But if we delete the ampersand, it works
$('#ValidadorWrapper').html("<div>AMOXICILIN 100 Camp;psulapsula</div>");
This problem happens only in Chrome, I suspect it has something to do with the encoding characters but I cant' find any way of doing it. Obviously I need to input an & ( i mean the & entity) in this document.
Some steps I have tried and didn't work:
I'm using the gson library to output a String to an JSP page. My JSP page have this header <%#page pageEncoding= "UTF-8" contentType="text/html; charset=UTF-8" %> . This was my first attempt and didn't work when an ampersand appeared in my JSON object (well any special char).
My second attempt was using the HTMLEntities Java library to encode all special chars. This is the actual version and it still doesn't work
Using unicode chars like \u0026 doesnt work either
There is something more strange. Apparently if I use $('#ValidadorWrapper').html("AMOXICILIN 100 \u0026"); it works!, but this is just an example. I'm trying to fill an HTML table with my object so I really need to put that data inside html (table) tags

Try this:
$('<div></div>').appendTo('#ValidadorWrapper').text('AMOXICILIN 100 Cápsulapsula');

Related

Navigate results in content space

I hope you get my problem.
out.println("<li class='has-sub'><a href='#'>" + k1.getKName() + "</a>\n");
I have a JSP and inside this java code. The result is a navigation on the left side with several categories and subcategories. So this is one category element. As you can see, I didn't put anything in the href. What I want to do is, that when I click on this category, I will get the articles of this category in the content space on the right side.
So, what do I have to do with servlets or JSPs in order to give a result to the content space. I can't just call a servlet there of course, because that means that I get the result of the servlet inside the href obviously.
I am sorry if this is a silly question, but I really don't know how to solve this :(
Further to previous comments you do not need web services. You can do this using ajax and a normal Servlet. You might want to look at using JQuery to help with the Ajax part. Here's some JQuery documentation around the load() function which will:
Load data from the server and place the returned HTML into the matched
element.
https://api.jquery.com/load/
Your link will look something like (if k1 is a bean in some scope then you can use EL rather than scriptlets):
<a href='javascript:loadData(${k1.id});'>${k1.name}</a>
Your Javascript will look something like:
function loadData(id){
var url = "/pathToMyServlet?id=" + id;
$( "#result" ).load( url );
}
which will call your Servlet and insert the HTML returned to an element on your page with the ID 'result'.
Your Servlet then needs to generate the data and forward to a simple JSP which returns the results (and only the results) i.e. it does not need to be a fully formed HTML page but should only contain the table of results or whatever.
And stop using scriptlets:
How to avoid Java code in JSP files?

send HTML from servlet to JSP dynamically

Is there an easy way to send HTML from a servlet to a JSP, using AJAX.
I've already figured out how to make AJAX work with servlets dynamically, but now I want to press a button on a form and generate HTML based on text-input.
Is it possible, and if so, how, to send just pieces of HTML to an existing HTML page?
Example,
I have a basic form where you can input your age, and based on the age the text has a different size/color. So, you send for example, 25 as your age to the servlet, and it send back a piece of HTML like this <p STYLE="font-size: age;"> to the page.
Through ajax call you can get the output result either a string, html or a Json object that will be parsed and results can be displayed over JSP/HTML. So for sure you can send html code segment from servlet to jsp through ajax call.
For example you can use this approach--
1. Take a string variable in your servlet.
2. Put appropriate html string as per your conditions in this string variable
3. send this string as a response from servlet like:
response.setCharacterEncoding("UTF-8");
response.getWriter().write("your string variable here");
4. In your ajax call do like this:
success : function(dataString) {
document.getElementById("containerId").innerHTML=dataString;
},
where containerId is the id of html element (like div or span) where you want to display output html.
The easiest approach, without client-side javascript libraries, would be to point an HTML form to an iframe, just like
<iframe name="myIframe"...>
<form target="myIframe"...>
And submit your form as many times as necessary. The HTML returned by the servlet would load itself in the iframe element.
If you like AJAX and client-side javascript libraries, you can find very easy programmatical ways to do this in jQuery and similar libraries.
Basically your servlet can generate any kind of content, e.g. JSON, HTML etc.
You'd then send that content back to the client and integrate it into the page.
How that is done depends on the type of content.
Example:
You issue an AJX request (e.g. by using jQuery's ajax functionality) and your servlet generates plain html. When your JavaScript receives the anser you just replace the relevant part, e.g. by replacing the content of some defined element.
If you used JSON instead, your servlet might send data only instead, e.g. a font size based on the age as in your example. You'd then use JavaScript to access that JSON data and perform relevant operations, e.g. by changing the style of the paragraph.

Security flaws : How to avert them?

I am in a bit of a pickle :
I have a lot of values which i am setting in a bean in java and then i am getting them in javascript and jsp using scriplets like this :
In My Bean.java :
public void setListValue(String s) { listValue = s; }
public String getListValue() { return listValue; }
Now in my jsp(inside a javascript function) :
input = $input({type:'hidden',id:'ListVal',name:'ListVal',
value: '<%= results.getListValue() %>'});
Sometimes i am using the scriplet code to retrieve parametres in jsp as well.
Normally if a parameter is passed from java file to java file or from jsp file to jsp file , then i use native java encoder and decoder like this :
EncodedHere = URLEncoder.encode(encodedStr,"UTF-8");
DecodedHere = URLDecoder.decode(EncodedHere,"UTF-8");
This works flawlessly for those scenarios but if i have set my variables in java and then i try to retrieve them in javascript or jsp like the afore mentioned way , it fails. I have tried the JSTL way as well , but could not make it work, seems JSTL is not suitable to get values in javascript. Now this scriplet has been flagged as security concern by many. Since it's a huge code base it's very difficult to change that as well.
Does some one have any ideas as to avert this security flaw somehow. In other words, is there a way i can encode the variable in java and get the encoded string in jsp and javascript and then decode it ?
It sounds like your security guys are worried about XSS (cross site scripting) attacks, which means data entered by the user that is re-displayed on a page could have malicious code in it. If that is the case you actually don't want to URL encode the data, you want to XML escape it, i.e replace potentially dangerous characters like < with their corresponding character entity like <. To do this in JSP you can use the <c:out> tag or the fn:escapeXML EL function. This works perfectly fine in javascript code, even if it is a little ugly. In your case it would look something like this:
First escape the javascript before you put it on the request using an escaping library the ESAPI reference implementation:
String jsEscapedValue = ESAPI.encoder().encodeForJavaScript(results.getListValue());
request.setAttribute("listValue", jsEscapedValue);
Then on the page use the <c:out> tag to HTML/XML escape it:
var myJsValue = '<c:out value="${listValue}"/>';
Make sure jstl.jar is on the classpath and be sure to include the correct tag lib at the top of your page.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Character is corrupted when use request.getParameter() in java

I have a web page where I do a search based on the text given in a text box. This text can be in any language like japanese, chinese etc (or any mbcs character).
Now when i enter a text in japanese (or any other mbcs character), the result populates the screen (form) with some wierd characters.
For Example: testテスト will turn into testãã¹ã.
When i see the post parameters in Firebug (debugging tool) i can see that the search string goes as testテスト however when i put debug statements in my code, i can see that request.getParameter("searchString") is not able to identify the japanese characters and turn them into some wierd chars.
My JSP header already has <%# page contentType="text/html; charset=UTF-8"
I have also tried putting pageEncoding="UTF-8" in this but it didn't help.
I tried setting character encoding like request.setCharacterEncoding("UTF-8") also just before doing request.getParameter but that too didn't work for me.
After going through a few forums and blogs i also tried setting useBodyEncodingForURI=true in the <Connector> of tomcat config but that also did not help me.
Can anybody suggest me something to resolve this issue?
set the following encoding in every servlet/ action
response.setContentType("UTF-8");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
also set following in first servlet/action
for japanese
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
session.setAttribute(Globals.LOCALE_KEY, new Locale("jp", "ja_JP"));

Handling Spanish characters in Java/JSP

I have a small webapp which handles a lot of Spanish text.
At one point in the code, a JSP page responds with a Json String containing some of this text. If I print the String to the Console, it looks like jibberish. But if I examine the header/content of the response in Chrome Developer Tools, it looks correct. It is transferred in the correct encoding. This part of the webapp functions as expected.
At another point in the code, a different JSP page responds with HTML. Some of this HTML contains more of the Spanish text. This time, the text is transferred (and displayed) as jibberish.
What are potential reasons that this could be happening? Both times, I'm just printing the text using out.print. Why does it work at one point, but not in other?
Examples:
// In a file who's only output is the json string
String jsonString = ...
System.err.println(jsonString); // prints jibberish
out.println(jsonString); // looks correct when the response is viewed in Chrome Developer tools, and looks correct in a browser
...
// In a file who's output is a complete html page
String spanishText = ...
out.println("<label>" + spanishText + "</label>"); // looks like jibberish when the response is viewed in Chrome developer tools, and shows up as jibberish in a browser
You need to set the encoding which the JSP/Servlet response should use to print the characters and instruct the webbrowser to use the same encoding.
This can be done by putting this in top of your JSP:
<%# page pageEncoding="UTF-8" %>
Or if you're actually doing this in a Servlet:
response.setCharacterEncoding("UTF-8");
The "jibberish" when using System.err is a different problem. You need to set the encoding of the console/logfile which is been used to print this information to. If it's for example Eclipse, then you can set it by Window > Preferences > General > Workspace > Text File Encoding.
See also:
Unicode - How to get the characters right? - Fixing JSP/Servlet response
Unicode - How to get the characters right? - Fixing development environment

Categories

Resources