无法实例化javax.servlet.ServletException

问题描述 投票:14回答:3

我正在尝试使用以下代码创建类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>

我在做什么错?

java maven-2 servlets jakarta-ee java-ee-6
3个回答
22
投票
如@ 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范围内声明,您不希望将其捆绑(应为providedtest,而不是compileruntime)。 


我想知道javaee实现的提供者是否重要?通常,我使用Apache服务器,因此具有与服务器上相同的javaee实现会很棒。

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

第二个问题至关重要。 javax.servlet只是javaee-api实现的一部分,在哪里可以找到其他部分。现在,我需要“ javax / validation / Validation”。

对于Bean验证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>

如何确定哪个工件实现了javaee的各个方面。也许某处有某种“地图”?

除了BalusC的this nice answer以外,没有其他人会帮忙。


5
投票
签出this post。基本上,这些Maven库都是存根,只适合针对它们进行编译。这些无意在运行时引用。在运行时(甚至对于单元测试),您将需要引用

real jar文件,即servlet容器中的一个。


0
投票
确保1. Servlet类被声明为public。2.路径已在web.xml中正确指定,或使用批注。
© www.soinside.com 2019 - 2024. All rights reserved.