Java 在 JSP 文件中导入类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2949929/
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-08-13 14:50:04  来源:igfitidea点击:

Importing a class in a JSP file

javajspservletsimportclass

提问by Michoel

I wrote some code as a Java Servlet and now I am trying to convert it to a JSP. I wrote a class in a separate file which I was using, and I can't figure out how to get the JSP file to recognize the class. I guess it has something to do with importing. I gave the class a package (package mypackagename;) name and I tried using <%@ page import="mypackagename"%>but I get an error:

我写了一些作为 Java Servlet 的代码,现在我试图将它转换为 JSP。我在我正在使用的单独文件中编写了一个类,但我不知道如何让 JSP 文件识别该类。我想这与进口有关。我给了类一个包 ( package mypackagename;) 名称,我尝试使用,<%@ page import="mypackagename"%>但出现错误:

The import "mypackagename" cannot be resolved

无法解析导入“mypackagename”

回答by BalusC

Just import it the same way as you do in a real Java class. I.e. import mypackagename.MyClassNameor import mypackagename.*and thus notimport mypackagenamewith onlythe package name.

只需像在真正的 Java 类中一样导入它。即import mypackagename.MyClassNameimport mypackagename.*因而import mypackagename具有唯一的包名。

<%@ page import="mypackagename.MyClassName" %>


That said, you should not write raw Java code in a JSP file. Scriptletsare considered poor practice. That code belongs in a real Java class. It was located perfectly fine in the Servlet class. What is it, the problem for which you think that it is the "right" solution to move it all into the view side and clutter the template text with raw Java code? Elaborate about it in a new question, then we may be able to suggest the right solutions. Maybe you weren't aware of existence and powers of taglibs like JSTL?

也就是说,您不应在 JSP 文件中编写原始 Java 代码。Scriptlet被认为是不好的做法。该代码属于真正的 Java 类。它在 Servlet 类中的位置非常好。它是什么,您认为将其全部移到视图端并使用原始 Java 代码使模板文本混乱是“正确”解决方案的问题是什么?在一个新问题中详细说明它,然后我们可能会提出正确的解决方案。也许你不知道像JSTL这样的标签库的存在和力量?

回答by zoomer.hammerball

Be sure that your class is in WEB-INF/classes directory of the web application, and modify the import of the package by package.*

确保你的class在web应用的WEB-INF/classes目录下,通过package.*修改包的import