java.lang.NoClassDefFoundError: Could not initialize class org.springframework.web.util.NestedServletException

I met an issue but I cannot figure out the cause of this problem because the error quite general.

java.lang.NoClassDefFoundError: Could not initialize class org.springframework.web.util.NestedServletException at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:980) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:845) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1160) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1092) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134) at org.eclipse.jetty.server.Server.handle(Server.java:518) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:308) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:244) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:246) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:156) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572) at java.lang.Thread.run(Thread.java:745)

This is my project structure:

Project Structure

It's just a very simple project that I use Embedded Jetty with SpringMVC.

This is the pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.biendltb</groupId>
<artifactId>com.biendltb.world_map</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>com.biendltb.world_map</name>

<properties>
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <jetty.version>9.3.8.v20160314</jetty.version>
    <spring.version>4.2.5.RELEASE</spring.version>
    <servlet.version>2.5</servlet.version>
</properties>

<dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- SPRING DEPENDENCY -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.2.5.RELEASE</version>
    </dependency>


    <!-- JETTY DEPENDENCY -->
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-server</artifactId>
        <version>${jetty.version}</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-servlet</artifactId>
        <version>${jetty.version}</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-webapp</artifactId>
        <version>${jetty.version}</version>
    </dependency>

    <!-- SERVLET DEPENDENCY -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${servlet.version}</version>
    </dependency>

    <!-- COMMON LOGGING DEPENDENCY -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.3</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
                <compilerArguments>
                    <endorseddirs>${endorsed.dir}</endorseddirs>
                </compilerArguments>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${endorsed.dir}</outputDirectory>
                        <silent>true</silent>
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>7.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.3.7.v20160115</version>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <warSourceDirectory>WebContent</warSourceDirectory>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.3</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <createDependencyReducedPom>false</createDependencyReducedPom>
                        <transformers>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>com.biendltb.main_server.TripMapServer</mainClass>
                            </transformer>
                        </transformers>
                        <filters>
                            <filter>
                                <artifact>*:*</artifact>
                                <excludes>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.7</version>
            <dependencies>
                <dependency>
                    <groupId>org.apache.maven.shared</groupId>
                    <artifactId>maven-filtering</artifactId>
                    <version>1.3</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <targetPath>webapp</targetPath>
            <directory>src/main/webapp</directory>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
</build>

This is the main class:

public class TripMapServer {

    private static final int DEFAULT_PORT = 8080;
    private static final String CONTEXT_PATH = "/";
    private static final String MAPPING_URL = "/*";
    private static final String CONFIG_LOCATION = "com.biendltb.config";
    private static final String DEFAULT_PROFILE = "dev";

    public static void main(String[] args) throws Exception {
        new TripMapServer().startJetty(getPortFromArgs(args));
    }

    private static int getPortFromArgs(String[] args) {
        if (args.length > 0) {
            try {
                return Integer.valueOf(args[0]);
            } catch (NumberFormatException ignore) {
            }
        }
        return DEFAULT_PORT;
    }

    private void startJetty(int port) throws Exception {
        Server server = new Server(port);
        server.setHandler(getServletContextHandler(getContext()));
        server.start();
        server.join();
    }

    private static ServletContextHandler getServletContextHandler(WebApplicationContext context) throws IOException {
        ServletContextHandler contextHandler = new ServletContextHandler();
        contextHandler.setErrorHandler(null);
        contextHandler.setContextPath(CONTEXT_PATH);
        contextHandler.addServlet(new ServletHolder("default", new DispatcherServlet(context)), MAPPING_URL);
        contextHandler.addEventListener(new ContextLoaderListener(context));
        contextHandler.setResourceBase(new ClassPathResource("webapp").getURI().toString());
        return contextHandler;
    }

    private static WebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(CONFIG_LOCATION);
        context.getEnvironment().setDefaultProfiles(DEFAULT_PROFILE);
        return context;
    }
}

And this is the class WebConfig.java instead .xml file:

@Configuration
@EnableWebMvc
@Import({DefaultConfig.class})
@ComponentScan(basePackages = {"com.biendltb.controller"})
public class WebConfig extends WebMvcConfigurerAdapter{
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Autowired
    public Environment env;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(stringConverter());
    }

    private StringHttpMessageConverter stringConverter() {
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
        return stringConverter;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/src/main/resources/").setCachePeriod(Integer.MAX_VALUE);
        registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(Integer.MAX_VALUE);
        registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(Integer.MAX_VALUE);
        registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(Integer.MAX_VALUE);
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/src/main/resources/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

Please help figure out the cause or how to trace that error.

Thank you very much!

NoClassDefFoundError usually means that you are missing a jar file at runtime, but not always, and not in your case. Other errors with the class loader can also cause it.

I was getting this same error on org.springframework.web.util.NestedServletException. I ran Jetty in the debugger and set a breakpoint in org.springframework.web.servlet.FrameworkServlet at the place where it tries to construct the NestedServletException, so I could see what the exception it was trying to nest.

It turned out it was a StackOverflowError, and the class loader was failing to load the NestedServletException class because the JVM was out of stack frames. The Jetty ServletHolder was calling the Spring DispatcherServlet, which was forwarding it back to the ServletHolder, causing it to call the DispatcherServlet again.

java.lang.NoClassDefFoundError: Could not initialize class org , NoClassDefFoundError usually means that you are missing a jar file at runtime, but not always, and not in your case. Other errors with the class loader can also cause it. I was getting this same error on org. springframework. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more java.lang.NoClassDefFoundError: Could not initialize class org.springframework.orm.hibernate4.LocalSessionFactoryBuilder

I suggest you clear your .m2 folder, It may happen that some of jar files are corrupted during download.

Please comment if it did not helped you!

[Solved] java.lang.NoClassDefFoundError: Could not initialize class , If you are working on spring MVC web application and you are trying to use Could not initialize class org.hibernate.validator.engine. at java.lang.reflect. at org.springframework.beans.factory.support. at org.apache.tomcat.util.net. nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.springframework.jdbc.support.SQLErrorCodesFactory Ask Question Asked 6 years, 4 months ago

You are missing a class at runtime. Debug the startup and set an exception breakpoint on NoClassDefFoundError. Than you will see which class cannot be found. Search for that class in your IDE or the web to find out which dependency you are missing.

"java.lang.NoClassDefFoundError: Could not initialize class sun.awt , NoClassDefFoundError: Could not initialize class net.oschina.j2cache. ReportMessage Handler dispatch failed; nested exception is java.lang. Exceptionorg.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is org.springframework.web.servlet.mvc.​method.annotation. TkAuthTest.logsUserIn:58 NoClassDefFound Could not initialize class org.mockit TkAuthTest.logsUserOut:110 NoClassDefFound Could not initialize class org.mock CcStrictTest.canDecodeAnonymousIdentity:65 NoClassDefFound Could not initializ TkMethodsTest.callsActOnProperMethods:47 NoClassDefFound Could not initialize

java.lang.NoClassDefFoundError: Could not initialize class net , org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class  Real cause of this exception is that ClassLoader, which is loading this application (could be web-app class loader, if you are running on Tomcat server) is not able to find class "org.springframework.web.context.ContextLoaderListener" but manifestation and trigger could vary from one case to another.

GeoServer / Re: [Geoserver-users] Monitoring Extension Issue, is java.lang.NoClassDefFoundError: Could not initialize class org.bytedeco.​javacv. package com.esense.touch.utils; import org.bytedeco.javacv. Do you get the same error when running this example with the following Spring framework I can used in my application and It was working in local Is their a way to enable the sword actually blocking on your screen when you're on 1.14 but have the plugin installed? if not can we see it in a future

Handler dispatch failed; nested exception is java.lang , org.springframework.web.util. Handler dispatch failed; nested exception is java​.lang.NoClassDefFoundError: Could not initialize class  Spring: java.lang.NoClassDefFoundError: Can not initialize class I am developing a little web application in Spring MVC. I get the exception every time I try to get my custom class in any controller, in case if this class uses another custom class.

Comments
  • Thanks for your sharing. This error is de facto caused by various reasons and your shared case is one of them. Unfortunately, I didn't keep my old code to test it again but I hope the others who face the same problem may find it helpful. Cheers!
  • Thank you for your advice but it still cannot solve my problem :(
  • Hi Stefan, the problem happened in my Spring Controller when I return a ModelAndView. The problem is in deeper level of SpringMVC so I just can set the try catch exception at here. But it also not figure out clearly the error. I think problem might be in my SpringMVC configuration. Anyway, thank you for your help :)
  • Hi, I am getting the same error, what was the setting that helped you out??
  • Not necessarily. Any failure by the ClassLoader to load a class can cause a NoClassDefFoundError. In my case, the code had caught a StackOverflowError and was trying to wrap it in a NestedServletException, but the ClassLoader couldn't load the NestedServletException class due to JVM being out of stack frames, causing the NoClassDefFoundError.