Why able to embed jstl in javascript? - javascript

How can the Javascript engine interpret the below code?
I thought just the JSTL tags embedded within html are interpreted?
<script type="text/javascript">
<c:choose>
<c:when test="${fn:contains(val, 'test')}">
alert('test);
</c:when>
</c:choose>
</script>

The JavaScript engine doesn't interpret the JSTL because it doesn't see it. The JSTL is handled server-side before the response is sent to the browser. The JSTL/Java side of things only cares about JSTL/Java code - everything else is basically passed through in the response as-is. So it doesn't matter if you include a script element or JavaScript or other html elements, all will become part of the response.
Within your browser if you select "View Page Source" you'll see the code as received by the browser - you'll note it doesn't include any JSTL.
In your specific example, the response will - depending on the result of the JSTL test - either include a script element with that one line alert('test') or just an empty script element.

You need to run a Java Servlet / JSP server (i. e. Tomcat) that processes your JSP files with embeded JSTL tags. The browser doesn't see the JSTL tags then anymore.

Related

How to use jstl tags inside .js file? [duplicate]

I want to use JSTL's fmt tag in JavaScript to localize my alert messages.
My JavaScript file is a standalone file and when I include fmt tag in js, the file browser gives JavaScript errors. Is it possible to treat .js file as .jsp files using web.xml configuration?
Can anyone please suggest how can I do that?
is it possible to treat .js file as .jsp file using web.xml configuration?
Yes:
<servlet>
<servlet-name>scriptjsp</servlet-name>
<jsp-file>/script.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>scriptjsp</servlet-name>
<url-pattern>/script.js</url-pattern>
</servlet-mapping>
But, there is no actual advantage in doing this, because JavaScript files do not have to have URLs ending in ‘.js’. What determines whether a file is a JavaScript file is what MIME media type it is served as. You can set this from JSP using:
<%# page contentType="text/javascript" %>
at the top. Then you can link directly to:
<script type="text/javascript" src="/script.jsp"></script>
(Aside: in current browsers, scripts linked to with the <script> tag will work even without having the Content-Type properly set, but that's probably not something to rely on.)
I want to use JSTL's fmt tag in javascript
This is probably not a good idea. The fmt tag deals with HTML-escaping for characters, but what you want is JavaScript string literal escaping, for example to backslash-escape quote characters. JSTL doesn't provide this capability. You'll get unexpectedly-escaped ‘&’ characters showing up in your JavaScript strings, and use of apostrophe or double quote in messages will break the whole script.
Also, serving commonly-included scripts from JSP risks poor performance and cacheing.
I'd suggest an independent language lookup system in JavaScript. For example, include a per-language external script:
<script type="text/javascript" src="/script/lang/en.js"></script>
(changing 'en' to match whichever language you want), and in that file define a lookup like:
var msg= {
messageName: 'Message in English',
...
};
Then look up msg.messageName for each localisable string in the script.
If your javascript is 'inline' with the rest of your JSP page, then simply use the technique suggested by Kees de Kooter.
If your javascript needs to be in an external file (For sharing across pages, for example) then simply put it in its own JSP file.
<%#page contentType="text/javascript" %>
<fmt:message key="some.message" var="someMessage"/>"
<fmt:message key="another.message" var="anotherMessage"/>"
var someMessage = "${someMessage}"
var anotherMessage = "${anotherMessage}"/>"
And include it like this...
<script src="yourScript.jsp" language="JavaScript" type="text/javascript"></script>
You can then refer to 'someMessage' and 'anotherMessage' from within the file that includes the JSP, or from any javascript file that is included after 'yourScript.jsp.
Note the use of the contentType attribute - 'text/javascript' prevents the JSP parser from complaining that the output isn't well formed XML - and that the tage refers to a JSP file.
A combination of this technique and that suggested by #Magner should bring you to a sensible solution.
EDIT: Changed the example to use 'text/javascript' insetad of 'text/plain' - thanks to #bobince for making me realise this error (Even though 'text/plain' works, it's more correct to use 'text/javascript'). Also, if the number of strings that need to be internationalised is small, and/or you can justify having your 'resources' in more than one place - one for the server side stuff and another for the client side stuff - #bobince's technique of using dynamic includes is a good one.
I would suggest you write a servlet that generates an array or javascript object that contains all the localized information you desire. You can use Java resource bundles which can be shared by both the client and server sides, then you don't have to intermix JSP code and Javascript code, and the servlet response will be cached by the browser.
Create a servlet, map it to a path, have it read the locale from a request parameter then generate the Javascript code.
Use a line like <script src="/mydict?lang=en"></script>
then load you script afterwards <script src="/myscript.js"></script>
You should strive to keep your javascript code in a separate file from the jsp-code. This is to get browser caching, easier maintenance, reuse across pages, and to allow compression.
I suggest that you create a global object for text in the jsp, to be used by your javascript files. Like this:
<script>
var text = text || {}; // play well with other jsps on the page
text.this_page_name = {
required_field_error: "<fmt:message key="required.field.error"/>",
system_error: "<fmt:message key="system.error"/>"
};
</script>
Later you use it in your javascript:
alert(text.this_page_name.required_field_error);
You could do the following. You store the translated message in a variable that can be resolved later on in the JSP.
<fmt:message key="your.alert" var="theAlert"/>
<script type="text/javascript">
alert("${theAlert}");
</script>
You can't use tags in JavaScript but there is a workaround: Put the tag into an hidden DIV (<div style="display: none;" id="msg"><fmt:...>
Now you can use JS to look up the DIV by its ID and get the innerHTML.
That said, fmt is just a wrapper for Java's i18n functions which you can use directly between <% %>.
If you are going for only alert messages
just use this tag in your javascript
Suppose you have following in your Javascript:
alert("Confirm Deletion");
This can be internationalized by adding bean:message tag in your javascript
alert('<bean:message key="msg.confirm"/>');
and add key value in property file
msg.delete=Confirm Deletion

How to include a file in Javascript and Jsp?

Ok,i know in Php you can use include for a Php file...for example...
include("array.php");
Is there a way to do this in Javascript and Jsp?
From what i read i cant use for example include("array.javascript"); or include("array.jsp");
I want to load the array from a different file and i know how to do it with Php,but not with Javascript or Jsp. Any help?
I think you are a bit confused, JSP is an XML-based language executed at the server side that gets transformed into Java the first time is processed by the servlet container (server) whilst JavaScript is an interpreted language executed by the user's browser, not the server. PHP is also executed at the server-side and that include function has nothing to do with JavaScript.
Now, to port that behaviour to JSP you would use a JSP tag, more specifically, the <jsp:include /> tag:
<jsp:include page="array.jsp" />
But if what you are trying to is to link your JSP with a JavaScript file then you should use a better option which consist of using the standard HTML <script> tag:
<script type="text/javascript" src="array.js" />

Referencing ASPX controls from an External JS file

I have a question. I have a aspx control (for e.g textbox). I reference it using document.getElementById('<%=textbox.ClientID%>').value. When I have the code in the same aspx file it works. But as soon reference it from an external file (example MyJSFunctions.js), I cannnot. I get an error saying "the object does not exist or it is null"
I have included the name of the js file like
I did this because I like having all my js functions in a seperate file nad doing this also reduces the load overhead.
Why is this happening? Can I accomplish the same using jquery?
You will need to parametise your Javascript to accept the desired argument, then pass the inline ASP.NET script within the server-side page or control as the value of such. This will allow the engine to render the inline code appropriately.
It happens because the server renders your pages (not in the sense of a browser rendering HTML, but rather the ASP.NET engine making transformations to turn your .NETified web mark-up into standard web mark-up) prior to pushing them down to the client - this will only happen for "registered" types, and that doesn't (and shouldn't) include Javascript files (although you can technically register items to handle, unless you have a bespoke module to handle compilation of inline scripting among Javascript, then it would err anyway.)
jQuery essentially being something of a Javascript framework, you're in the same boat with that, so to speak.
As an example, consider the following...
Your script file:
function doSomethingJavascripty(withThisClientID) {
//do something with...
document.getElementById(withThisClientID).value;
}
Your ASPX page:
<script type="text/javascript" src="/path/to/script.js"><script>
<script type="text/javascript">
//call your function when appropriate...
doSomethingJavascripty('<%=textbox.ClientID%>');
</script>
One thing you could do is have the following Javascript code in your ASPX page:
var myTextbox = '<%=textbox.ClientID%>';
Then, in your external JS file (make sure this is after the above line), have:
document.getElementById(myTextbox).value
Another alternative is just hardcode in the ClientID into your code, but note you'll break it if you change the ID or parent container of that textbox control in the future.

Javascript in HTML and ASP file

Since JavaScript can be written (or contained) within an HTML file or in an ASP file, is there any difference?
ASP runs on the server-side. Any HTML or JavaScript generated by this is simply sent to the browser, which is where the HTML is rendered and JavaScript is executed.
ASP is a server side technology that (usually) outputs an HTML document when executed.
Any JavaScript you write might be part of the HTML document (and thus identical to any JS you might put in a static HTML document) or it might be written as server side code (in which case it will execute on the server, have access to ASP APIs instead of Browser APIs, and will generate output instead of being output).
The marvellous thing about Javascript and server-side programming languages like ASP and PHP is that they can be (sort of) intertwined. So, for example, if you have a server-side variable that you want to be able to mess about with using Javascript, you can include it in the JS when you output the page:
// THIS IS THE ASP CODE
string mystring = "This is my ASP string";
string html = "<script type=\"text/javascript\">var mystring = "+mystring+"</script>";
// then output the html
That's a terrible, badly-coded example, but you hopefully get the idea. You can emit Javascript to the page using ASP variables and the like. It's very handy.
One difference I can think of is, the way you bind HTML/ASP controls
--HTML button control--
<input type = "button" id = "myButtonHTML" />
--ASP button control--
<asp:button runat = "server" id = "myButtonASP" />
the way you bind this in javascript will be as follows
--HTML control--
document.getElementById("#myButtonHTML").value
AND
--ASP control--
document.getElementById("#myButtonASP.ClientID").value

Using JSP code in JavaScript

I want to use JSTL's fmt tag in JavaScript to localize my alert messages.
My JavaScript file is a standalone file and when I include fmt tag in js, the file browser gives JavaScript errors. Is it possible to treat .js file as .jsp files using web.xml configuration?
Can anyone please suggest how can I do that?
is it possible to treat .js file as .jsp file using web.xml configuration?
Yes:
<servlet>
<servlet-name>scriptjsp</servlet-name>
<jsp-file>/script.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>scriptjsp</servlet-name>
<url-pattern>/script.js</url-pattern>
</servlet-mapping>
But, there is no actual advantage in doing this, because JavaScript files do not have to have URLs ending in ‘.js’. What determines whether a file is a JavaScript file is what MIME media type it is served as. You can set this from JSP using:
<%# page contentType="text/javascript" %>
at the top. Then you can link directly to:
<script type="text/javascript" src="/script.jsp"></script>
(Aside: in current browsers, scripts linked to with the <script> tag will work even without having the Content-Type properly set, but that's probably not something to rely on.)
I want to use JSTL's fmt tag in javascript
This is probably not a good idea. The fmt tag deals with HTML-escaping for characters, but what you want is JavaScript string literal escaping, for example to backslash-escape quote characters. JSTL doesn't provide this capability. You'll get unexpectedly-escaped ‘&’ characters showing up in your JavaScript strings, and use of apostrophe or double quote in messages will break the whole script.
Also, serving commonly-included scripts from JSP risks poor performance and cacheing.
I'd suggest an independent language lookup system in JavaScript. For example, include a per-language external script:
<script type="text/javascript" src="/script/lang/en.js"></script>
(changing 'en' to match whichever language you want), and in that file define a lookup like:
var msg= {
messageName: 'Message in English',
...
};
Then look up msg.messageName for each localisable string in the script.
If your javascript is 'inline' with the rest of your JSP page, then simply use the technique suggested by Kees de Kooter.
If your javascript needs to be in an external file (For sharing across pages, for example) then simply put it in its own JSP file.
<%#page contentType="text/javascript" %>
<fmt:message key="some.message" var="someMessage"/>"
<fmt:message key="another.message" var="anotherMessage"/>"
var someMessage = "${someMessage}"
var anotherMessage = "${anotherMessage}"/>"
And include it like this...
<script src="yourScript.jsp" language="JavaScript" type="text/javascript"></script>
You can then refer to 'someMessage' and 'anotherMessage' from within the file that includes the JSP, or from any javascript file that is included after 'yourScript.jsp.
Note the use of the contentType attribute - 'text/javascript' prevents the JSP parser from complaining that the output isn't well formed XML - and that the tage refers to a JSP file.
A combination of this technique and that suggested by #Magner should bring you to a sensible solution.
EDIT: Changed the example to use 'text/javascript' insetad of 'text/plain' - thanks to #bobince for making me realise this error (Even though 'text/plain' works, it's more correct to use 'text/javascript'). Also, if the number of strings that need to be internationalised is small, and/or you can justify having your 'resources' in more than one place - one for the server side stuff and another for the client side stuff - #bobince's technique of using dynamic includes is a good one.
I would suggest you write a servlet that generates an array or javascript object that contains all the localized information you desire. You can use Java resource bundles which can be shared by both the client and server sides, then you don't have to intermix JSP code and Javascript code, and the servlet response will be cached by the browser.
Create a servlet, map it to a path, have it read the locale from a request parameter then generate the Javascript code.
Use a line like <script src="/mydict?lang=en"></script>
then load you script afterwards <script src="/myscript.js"></script>
You should strive to keep your javascript code in a separate file from the jsp-code. This is to get browser caching, easier maintenance, reuse across pages, and to allow compression.
I suggest that you create a global object for text in the jsp, to be used by your javascript files. Like this:
<script>
var text = text || {}; // play well with other jsps on the page
text.this_page_name = {
required_field_error: "<fmt:message key="required.field.error"/>",
system_error: "<fmt:message key="system.error"/>"
};
</script>
Later you use it in your javascript:
alert(text.this_page_name.required_field_error);
You could do the following. You store the translated message in a variable that can be resolved later on in the JSP.
<fmt:message key="your.alert" var="theAlert"/>
<script type="text/javascript">
alert("${theAlert}");
</script>
You can't use tags in JavaScript but there is a workaround: Put the tag into an hidden DIV (<div style="display: none;" id="msg"><fmt:...>
Now you can use JS to look up the DIV by its ID and get the innerHTML.
That said, fmt is just a wrapper for Java's i18n functions which you can use directly between <% %>.
If you are going for only alert messages
just use this tag in your javascript
Suppose you have following in your Javascript:
alert("Confirm Deletion");
This can be internationalized by adding bean:message tag in your javascript
alert('<bean:message key="msg.confirm"/>');
and add key value in property file
msg.delete=Confirm Deletion

Categories