Changli Zhu
Changli Zhu

Reputation: 61

java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.text.StringEscapeUtils

I am writing a character filter function, using commons-text-1.6.jar.
The log function is okay, but then this error shows up:

java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.text.StringEscapeUtils
    cc.openhome.web.EscapeWrapper.getParameter(EscapeWrapper.java:15)
    cc.openhome.controller.Login.doPost(Login.java:30)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    cc.openhome.web.EscapeFilter.doFilter(EscapeFilter.java:16)

Code:

package cc.openhome.web;

import org.apache.commons.text.StringEscapeUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrappe

public class EscapeWrapper extends HttpServletRequestWrapper {
    public EscapeWrapper(HttpServletRequest req){enter code here
        super(req);
    }

    public String getParameter(String name){
        String value = getRequest().getParameter(name);
        return StringEscapeUtils.escapeHtml4(value);
    }
}

Upvotes: 6

Views: 12276

Answers (2)

Can Sun
Can Sun

Reputation: 1

commons-text-1.12.0 with commons-lang3:3.12.0 -> FAIL

commons-text-1.12.0 with commons-lang3:3.13.0 -> SUCCESSFUL

Upvotes: 0

Volodya Lombrozo
Volodya Lombrozo

Reputation: 3466

I encountered a similar issue with commons-text-1.11.0.java. Despite having org.apache.commons.text.StringEscapeUtils present in commons-text-1.11.0.jar, I received the following exception:

java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.text.StringEscapeUtils

The problem doesn't stem from the absence of StringEscapeUtils but rather from its initialization. In fact, StringEscapeUtils has multiple static initialization blocks that run when the ClassLoader loads it for the first time. If these static blocks encounter issues during the initial loading, it results in the java.lang.NoClassDefFoundError exception.

Fix

commons-text relies on other libraries, notably commons-lang3. Inconsistencies in their versions can lead to the exception, as it was in my case:

commons-text-1.11.0 with commons-lang3:3.12.0 -> FAIL

However, upgrading commons-lang3 to 3.13.0 resolved the issue:

commons-text-1.11.0 with commons-lang3:3.13.0 -> SUCCESSFUL

While your situation may involve different versions or dependencies, the underlying cause might be the same.

Upvotes: 18

Related Questions