Tomcat – UnsupportedClassException

我在Tomcat Web应用程序中部署已编译的类时遇到问题:我正在部署一个要从servlet调用的类,但是当我运行应用程序时,它无法告诉我ServletException: Error allocating the servlet instance由于一个ServletException: Error allocating the servlet instanceServletException: Error allocating the servlet instance UnsupportedClassVersionError: Bad version number in .class file

根据经理的报告,Tomcat正在使用Java 1.5.0_06。 我的类是使用Java 1.6.0_14编译的。 在已经存在的任何类上运行javap告诉我“主要版本46,次要版本0”,它应该是1.2.0初始,并且不再可用于下载。 我能找到的最老的是1.2.1_004,它甚至都没有编译。

我是否需要将我的Java版本与Tomcat环境或已经存在的类匹配? 现在使用更现代的Java重新编译整个项目对我来说是不可行的,尽管我很乐意这样做。

这很简单:使用比Tomcat下面的Java运行时更高版本的Java编译器编译应用程序。

更新

java编译器javac支持这些选项

 -source release Specifies the version of source code accepted. The following values for release are allowed: 1.3 the compiler does not support assertions, generics, or other language features introduced after JDK 1.3. 1.4 the compiler accepts code containing assertions, which were introduced in JDK 1.4. 1.5 the compiler accepts code containing generics and other language features introduced in JDK 5. The compiler defaults to the version 5 behavior if the -source flag is not used. 5 Synonym for 1.5 

……甚至更重要的是,

 -target version Generate class files that will work on VMs with the specified version. The default is to generate class files to be compatible with the JDK 5 VM. When the -source 1.4 or lower option is used, the default target is 1.4. The versions supported by javac are: 1.1 Generate class files that will run on VMs in JDK 1.1 and later. 1.2 Generate class files that will run on VMs in JDK 1.2 and later, but will not run on 1.1 VMs. 1.3 Generate class files that will run on VMs in JDK 1.3 and later, but will not run on 1.1 or 1.2 VMs. 1.4 Generate class files that will run on VMs in JDK 1.4 and later, but will not run on 1.1, 1.2 or 1.3 VMs. 1.5 Generate class files that are compatible only with JDK 5 VMs. 5 Synonym for 1.5 

…这将允许您为特定版本的JVM编译代码。

换句话说,你可以继续使用你的1.6编译器,只需在它上面抛出这些选项,你就可以让它生成Tomcat能够处理的1.5代码。

我是否需要将我的Java版本与Tomcat环境或已经存在的类匹配?

您需要确保使用您正在使用的JVM支持的版本(小于或等于)编译代码; 但不,这不需要是与Tomcat代码库构建相同的版本 – 两个代码库可以是jvm版本彼此独立,只要它们都被您正在使用的jvm支持。

您可以将Tomcat使用的JDK更新为1.6,而不是将源重新编译为1.5兼容。

您应该能够通过将JAVA_HOME环境变量设置为指向Java 1.6安装来更改此设置。

我刚才得到了相同的UnsupportedClassVersionError问题。 根本原因不是我自己编译的代码,而是一些需要的库,这些库是用较新的JDK编译的。