在 JavaScript 中使用 JSP 代码 [英] Using JSP code in JavaScript
问题描述
我想在 JavaScript 中使用 JSTL 的 fmt 标记来本地化我的警报消息.我的 JavaScript 文件是一个独立文件,当我在 js 中包含 fmt 标签时,文件浏览器会给出 JavaScript 错误.是否可以使用 web.xml 配置将 .js
文件视为 .jsp
文件?任何人都可以请建议我该怎么做?
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?
推荐答案
是否可以使用 web.xml 配置将 .js 文件视为 .jsp 文件?
is it possible to treat .js file as .jsp file using web.xml configuration?
是:
<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>
但是,这样做并没有实际优势,因为 JavaScript 文件的 URL 不必以.js"结尾.决定文件是否为 JavaScript 文件的是它所提供的 MIME 媒体类型.您可以使用以下方法从 JSP 设置:
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>
(另外:在当前的浏览器中,即使没有正确设置 Content-Type,与 <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.)
我想在javascript中使用JSTL的fmt标签
I want to use JSTL's fmt tag in javascript
这可能不是一个好主意.fmt 标签处理字符的 HTML 转义,但您想要的是 JavaScript 字符串文字转义,例如反斜杠转义引号字符.JSTL 不提供此功能.您的 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.
此外,从 JSP 中提供通常包含的脚本可能会导致性能和缓存不佳.
Also, serving commonly-included scripts from JSP risks poor performance and cacheing.
我建议在 JavaScript 中使用独立的语言查找系统.例如,包括每个语言的外部脚本:
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>
(更改en"以匹配您想要的任何语言),并在该文件中定义如下查找:
(changing 'en' to match whichever language you want), and in that file define a lookup like:
var msg= {
messageName: 'Message in English',
...
};
然后在脚本中为每个可本地化的字符串查找 msg.messageName
.
Then look up msg.messageName
for each localisable string in the script.
这篇关于在 JavaScript 中使用 JSP 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!