[英]How to compile a javascript file as a jsp?
I would like to be able to use the JSP servlet on my JavaScript files for i18n purposes. 我希望能够将JavaScript文件上的JSP servlet用于i18n。 Take the following JavaScript for example:
以以下JavaScript为例:
function you_did_it_wrong() {
alert("<fmt:message key="you.did.it.wrong" />");
}
I have tried to set up the JspServlet in my web.xml like this: 我试图像这样在我的web.xml中设置JspServlet:
<servlet>
<servlet-name>preprocessor</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>preprocessor</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
But when I call the js file, it comes back without being processed by the servlet. 但是,当我调用js文件时,它会返回,而不会被servlet处理。
Bozho gave the right hint. 博佐给出了正确的提示。 However, I'd like to answer the concrete problem.
但是,我想回答具体的问题。
The given code snippet will fail when the fmt
taglib is not declared in top of file: 当未在文件顶部声明
fmt
taglib时,给定的代码片段将失败 :
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setLocale value="${language}" />
<fmt:setBundle basename="com.example.i18n.text" />
So just ensure that it is there above in your JS file. 因此,只需确保它在JS文件中位于上方即可。
The JSP servlet entry looks fine, although I think I would rather have used just this: JSP servlet条目看起来不错,尽管我认为我宁愿使用以下代码:
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
( jsp
is the servlet-name
of the Tomcat's builtin JspServlet
which you can locate in its /conf/web.xml
) (
jsp
是Tomcat内置JspServlet
的servlet-name
,您可以在其/conf/web.xml
找到它)
There are better ways to do that than serving .js files through the jsp servlet. 有比通过jsp servlet提供.js文件更好的方法。
Check this question . 检查这个问题 。 I ended up having all variables declared in the
.js
file, and having them passed through an init method: 我最终在
.js
文件中声明了所有变量,并让它们通过init方法传递:
init({somgMsg: '<fmt:.../>', anotherMsg: '<fmt:... />'});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.