问题描述
我想在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?
推荐答案
是:
<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文件不必具有以".js"结尾的URL.确定文件是否为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.)
这可能不是一个好主意. 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代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!