How do I encode/decode between Javascript and ColdFusion? - javascript

I have a ColdFusion form and set a field value by copying it from another form with the Javascript below. (This is actually from a popup input window where you can paste large texts).
form1.remark.value = form2.remark.value;
After this happens, form1 is submitted for further processing by another process.cfm page.
The problem is the remark.value contains complex text, including XML, but it is encoded when it arrives at the process.cfm page. I'm looking for a way to correctly encode it in the Javascript portion and then decode it at process.cfm using ColdFusion code so that I get back the original text, including XML tags.
How is this best accomplished?

If you're trying to use the value of the submitted form field as the value of a JavaScript variable on the next page, then you need to use the built-in (as of ColdFusion 10) function encodeForJavaScript.
<cfoutput>var myJSvar = '#encodeForJavaScript(form.myField)#';</cfoutput>
This will properly escape the string value of form.myField, so that it can be used with JavaScript.
If you're on CF 8 or 9, the OWASP JAR file is loaded into CF (if you're patched up correctly), and you can access the same functions directly by instantiating the correct Java class.
<cfset application.xssEncoder = createObject("java", "org.owasp.esapi.esapi").encoder() />
<cfoutput>
var myJSvar = '#application.xssEncoder.encodeForJavaScript(form.myField)#';
</cfoutput>

I think you can use StringEscapeUtils class of java like this:
<cfset objEscapeUtil = createObject("java", "org.apache.commons.lang.StringEscapeUtils")>
<cfset unescapedString = objEscapeUtil.unescapeJavaScript(escapedString)>

Related

Get and iterate Java list in Javascript [duplicate]

I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.

How a Session variable set in Server be accessed in External javascript file? [duplicate]

I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.

How to access c:set variable from jsp to javascript not working [duplicate]

I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.

Is there a javascript equivalent of htmlencode / htmldecode from asp.net?

The problem is this:
You have a textbox, you type in some text, send it to the server. On another page, that value is retrieved and displayed on screen in a textbox and a label.
It's important to stop scripting attacks, and asp.net won't let you submit unsafe code, so on submit you javascript replace < with < and the same for >
When the values are retrieved from the server, they will come back with < and > which is fine for displaying in the label, but when put into the textbox, they must be replaced back to < and >
The data should be stored securely in the database as other people might use this content. From a safety point of view I'd like to call htmlencode on it then store it. It is this encoded html I'd like to display in the label on the client, but the decoded version I'd like to display in the textbox.
So what I need, is a htmldecode solution in javascript. htmlencode/decode replaces more than just < > and without a definitive list I can't create my own method. Is there a solution out there?
Instead of trying to turn a string of text into HTML and then adding it to the document using innerHTML; use standard DOM methods.
myElement.appendChild(
document.createTextNode(myString)
);

JavaScript variable to ColdFusion variable

I have a tricky one.
By means of a <cfoutput query="…"> I list some records in the page from a SQL Server database.
By the end of each line viewing I try to add this in to a record in a MySQL database.
As you see is simple, because I can use the exact variables from the output query in to my new INSERT INTO statement.
BUT: the rsPick.name comes from a database with a different character set and the only way to get it right into my new database is to read it from the web page and not from the value came in the output query.
So I read this value with that little JavaScript I made and put it in the myValue variable and then I want ColdFusion to read that variable in order to place it in my SQL statement.
<cfoutput query="rsPick">
<tr>
<td>#rsPick.ABBREVIATION#</td>
<td id="square"> #rsPick.name# </td>
<td>#rsPick.Composition#</td>
<td> Transaction done...
<script type="text/javascript">
var myvalue = document.getElementById("square").innerHTML
</script>
</td>
<cfquery datasource="#Request.Order#">
INSERT INTO products (iniid, abbreviation, clsid, cllid, dfsid, dflid, szsid, szlid, gross, retail, netvaluebc, composition, name)
VALUES ( #rsPick.ID#, '#rsPick.ABBREVIATION#', #rsPick.CLSID#, #rsPick.CLLID#, #rsPick.DFSID#, #rsPick.DFLID#, #rsPick.SZSID#, #rsPick.SZLID#, #rsPick.GROSSPRICE#, #rsPick.RETAILPRICE#, #rsPick.NETVALUEBC#, '#rsPick.COMPOSITION#','#MYVALUE#' )
</cfquery>
</tr>
</cfoutput>
ColdFusion is processed on the server before the page is served. JavaScript is processed in the browser after the page is served. Therefore, the only way for JavaScript to serve a value to ColdFusion is either:
a) Set the variable to a form field and then post the page back to the server.
b) Send the variable back to Coldfusion via Ajax.
I think there is a safer and more reliable way to do what you need without the JavaScript.
If you are creating the page you would know what is in the DOM element "square" because you put it there. If you are doing this based on the dynamic input of the user then you would need to use a CFAJAXPROXY or simply a form post to a different page for doing the insert.
Also it's frightening to take unsanitized input from a DOM and insert into a database. Use cfqueryparam to protect against injection attacks.
Your misconception starts with this thought:
"The only way to get it right is to read the value from a web page via JavaScript."
Sorry if this sounds harsh now, but this is complete nonsense. Forget that idea. It is neither possible to read a JavaScript variable from ColdFusion the way you try it, nor is it even necessary.
For starters, I'm not sure why it must be via ColdFusion that you move values from one database to another. Database servers are perfectly able to talk directly to each other, for example via the "Linked Server" feature in MS SQL Server (see this howto).
If it must be ColdFusion, try this:
<cfoutput query="rsPick">
<cfquery datasource="#Request.Order#">
INSERT INTO products (
iniid,
/* … etc … */
name
)
VALUES (
<cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#rsPick.ID#">,
/* … etc … */
<cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#rsPick.name#">
)
</cfquery>
</cfoutput>
As long as the table data types and database connections to both databases are set up correctly, ColdFusion will handle the character encoding transparently. Note that the target DB fields should not be "less capable" than the source fields, e.g. the source should not be Unicode when the target is US ASCII.
Well, your question is really this: How do I take a string from one character encoding to another in ColdFusion?
Can you use the NVARCHAR type in SQL Server (not sure what the same thing in MySQL is) - and just store the character data as UTF8?
Also, Java is perfectly capable of dealing with the different encodings, and even provides help in the String class and the CharsetDecoder class to deal with different encodings:
String s = new String("Hello, World!");
byte[] bytes = s.getBytes("UTF-8");
String utf = new String(bytes, "UTF-8");
ColdFusion has very limited support for dealing with multiple character sets in a single request. You are almost certainly going to have to rely on the underlying Java classes to solve this problem inside of ColdFusion.
So, if you wanna to convert JS value to CFM, I feel a few steps need to do:
first of all, assign your JS value into input via javascript. after that, retrieve value from this input by submitting form.
Use JSString to convert Javascript variable to CFML variable.
<cfoutput>
var #toScript(myCFMLVaraible, "jsVar")#;
</cfoutput>

Categories

Resources