在 .jsp 文件中使用 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15423650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:43:53  来源:igfitidea点击:

using javascript in .jsp file

javajavascripthtmljsp

提问by user1782677

So in eclipse when you generate a .jsp file it automatically includes the following top line:

因此,在 Eclipse 中,当您生成 .jsp 文件时,它会自动包含以下第一行:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

Is there a way to also include javascript code so that I can have some of the file written in java and some written in javascript?

有没有办法也包含javascript代码,以便我可以使用java编写的一些文件和javascript编写的一些文件?

回答by blamonet

Usually I include my JavaScript in JSP like this:

通常我将我的 JavaScript 包含在 JSP 中,如下所示:

<script type="text/javascript" src="js/script.js"></script>

This way I can minimize the js code and also cache it differently than JSP files in Tomcat.

通过这种方式,我可以最小化 js 代码,并以不同于 Tomcat 中的 JSP 文件的方式缓存它。

回答by OQJF

The answer is Yes, you can add the js in jsp. And this also has benefit. It helps you to use the values stored in request and session, because the js code which contains the jsp stuff in jsp will be compiled while the *.js file will not. And also you should keep in mind that you'd better put the js code in .js file not in jsp, so the browser doesn't need to load it repeatly and code seems more clear, also good for debug. Another answer has give you the example code to import js file, so I just ignore it.

答案是肯定的,可以在jsp中加入js。这也有好处。它可以帮助您使用存储在请求和会话中的值,因为包含 jsp 中的 jsp 内容的 js 代码将被编译,而 *.js 文件将不会被编译。还要记住,js代码最好放在.js文件中,而不是jsp中,这样浏览器就不需要重复加载,代码看起来更清晰,也利于调试。另一个答案为您提供了导入 js 文件的示例代码,所以我只是忽略它。