How to include a file in Javascript and Jsp? - javascript

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" />

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

Including Javascript code from a JSP file

I have a JSP file that gives me a bunch of JS code that I need to put in my view page (particularly in my JSP file that is the view for the current URL. Using Spring MVC) . Is there a way for it?
I have already tried a bunch of suggestions from here: Including JSP code from another JSP file correctly and here https://coderanch.com/t/596663/frameworks/Calling-jsp-include-tag-javascript but none gives clear answer on it. When the view is rendered after hitting the controller it just gave a plain JS code in the window instead of embedding it as JS code.
<html>
<head> </head>
<script type="text/javascript">
<jsp:include page="./myJSPfiles/MyJSPfileforScript" />
</script>
</html>
As I said, it just gives plain JS code in the browser instead of embedding it. I am fairly new to JSPs in general. Any suggestions?
Use something like below line of code.
<script type="text/javascript" src="${pageContext.request.contextPath}/js/index.js"></script>

Using PHP file via JavaScript/Jquery using an HTML file only

I'm exploring several types of programming style in web designing. But it suddenly came to my mind. Can a PHP file be read using JQuery/JavaScript on a HTML file. An example. I would open login.php using $.ajax inside the index.html page. Take note about the extensions in the example
Calvin!, your question really is unclear!
And is denoting very few efforts...
Based on the reading of all comments, I can answer this with examples:
In a test.html file:
<span>TEST</span><br>
<?php
echo "PHP works.";
?>
outputs:
TEST
But the exact same code in a test.php file outputs:
TEST
PHP works.
NOW using jQuery in an test2.html file to access a separate PHP file asynchronously.
Assuming this basic ajax-requested-file.php which content is:
<span>Ajax content!</span>
If you call it from a test2.html file like this:
<span>TEST#2 using Ajax</span><br>
<div id="ajaxResult"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script>
$.ajax({
url:"ajax-requested-file.php",
data:"",
method:"post",
success:function(html){
$("#ajaxResult").html(html);
}
});
</script>
It outputs:
TEST#2 using Ajax
Ajax content!
Note that, if you are really attentive...
You will notice a milliseconds delay between the appearance of the first line and the second one.
Like here : https://www.bessetteweb.com/SO/43795339/test2.html
Technically you can send a PHP file to a client, but a browser cannot execute PHP code, so there is no point in serving a php script to the client side.
If you are looking for the right web site architecture you should look into the single page architectural style. With it you just create a single HTML page for your site and load any additional content via ajax requests. For changing the page content you rely on js frameworks that manipulate the html DOM tree dynamically in place.
Note that you don't have to be strict on the single page. You can apply the same style for say a handful of logically different pages in your application as well.
To read more see this article and this answer.

Why able to embed jstl in 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.

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