java.lang.NoSuchMethodError:Java EE 应用程序中的 org.apache.commons.codec.binary.Base64.encodeBase64String()

2022-01-21 00:00:00 base64 jakarta-ee java

我正在开发一个需要 Base64 编码/解码的 Java EE 应用程序

I am developing a Java EE application in which I need Base64 Encoding/Decoding

所以我在我的应用程序的 WEB-INF/lib 文件夹中添加了 commons-codec-1.5.jar 并使用了

So I added commons-codec-1.5.jar in WEB-INF/lib folder of my application and used

import org.apache.commons.codec.binary.Base64;

在 Java 文件中.

in the Java file.

在编译期间,当我输入 Base64 时,它显示 encodeBase64String 方法可用.但是在运行时它会抛出这样的异常:

During compile time, when I type Base64, it shows encodeBase64String method is available. But during runtime it is throwing an exception like this:

java.lang.NoSuchMethodError:org.apache.commons.codec.binary.Base64.encodeBase64String

我在构建路径中有 JAR,但我仍然不明白为什么它会抛出上述错误.

I have the JAR in the buildpath, but still I don't understand why it throws me the above error.

推荐答案

那个方法是 在 Commons Codec 1.4 中引入.此异常表明您在 web 应用程序的运行时类路径中的其他位置有旧版本的 Commons Codec,它在类加载中具有优先权.检查 webapp 的运行时类路径涵盖的所有路径.这包括 Webapp/WEB-INF/libYourAppServer/libJRE/libJRE/lib/ext.最后删除或升级有问题的旧版本.

That method was introduced in Commons Codec 1.4. This exception indicates that you've an older version of Commons Codec somewhere else in the webapp's runtime classpath which got precedence in classloading. Check all paths covered by the webapp's runtime classpath. This includes among others the Webapp/WEB-INF/lib, YourAppServer/lib, JRE/lib and JRE/lib/ext. Finally remove or upgrade the offending older version.

更新:根据评论,您似乎找不到它.我只能建议使用较新的方法对代码进行注释,然后将以下行放在适当的位置:

Update: as per the comments, you can't seem to locate it. I can only suggest to outcomment the code using that newer method and then put the following line in place:

System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation());

这应该打印运行时加载它的 JAR 文件的绝对路径.

That should print the absolute path to the JAR file where it was been loaded from during runtime.

更新 2:这似乎指向了正确的文件.抱歉,我现在无法解释你的问题.我只能建议使用不同的 Base64 方法,例如 encodeBase64(byte[]) 然后自己构造一个 new String(bytes).或者您可以删除该库并使用不同的 Base64 编码器,例如 this one.

Update 2: this did seem to point to the right file. Sorry, I can't explain your problem anymore right now. All I can suggest is to use a different Base64 method like encodeBase64(byte[]) and then just construct a new String(bytes) yourself. Or you could drop that library and use a different Base64 encoder, for example this one.

相关文章