gpt4 book ai didi

java - 无法实例化 javax.servlet.ServletException

转载 作者:搜寻专家 更新时间:2023-10-30 19:52:51 27 4
gpt4 key购买 nike

我正在尝试使用以下代码创建 javax.servlet.ServletException 类的实例

public class MyTroubleViewer {
public static void main(String[] args) {
javax.servlet.ServletException servletException = new javax.servlet.ServletException("Hello");
System.out.println(servletException.getMessage());
}
}

但是我在创建时遇到异常:

Exception in thread "main" java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/ServletException
...

Maven 帮助我处理依赖项:

<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>

我做错了什么?

最佳答案

如@user353852 所述,您当前的依赖项仅包含 Java EE 6 API,不包含任何方法体。所以你不能针对它运行代码。要在容器外运行代码,您需要获得“具体”依赖项(来自 GlassFish 存储库):

<repositories>
<repository>
<id>glassfish-repository</id>
<url>http://download.java.net/maven/glassfish</url>
</repository>
...
</repositories>

<dependencies>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.servlet</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>
...
</dependencies>

请注意,不应使用 compile 范围声明此类依赖项,您不想将其捆绑(它应该是 provided 或者 test ,但不是编译运行时)。


I wonder does the provider of the javaee implementation important? Generally I use Apache servers, so it will be great to have the same javaee implementation as it is on the server.

理论上,不会。但在实践中,我建议使用来自您将要使用的服务器(或来自 Java EE 引用实现)的实现 JAR。由于您使用的是 Java EE 6,因此在这两种情况下,这实际上意味着来自 GlassFish v3 的 JARS。

The second question is much more vital. javax.servlet is only one part of javaee-api implementation, where can I find the others. Now I need "javax/validation/Validation".

对于 Bean Validation API,您需要以下内容(Hibernate Validator 是 RI):

<repositories>
<!-- For Hibernate Validator -->
<repository>
<id>jboss</id>
<name>JBoss repository</name>
<url>http://repository.jboss.org/maven2</url>
</repository>
...
</repositories>

<dependencies>
<!-- Bean Validation API and RI -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.2.GA</version>
<scope>runtime</scope>
</dependency>
...
</dependencies>

How can I determine which artifact implements each aspect of javaee. Maybe there is some kind of a "map" somewhere?

this nice answer 外没有其他官方信息来自 BalusC 的帮助。

关于java - 无法实例化 javax.servlet.ServletException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2979968/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com