Search code examples
javaclassloadernoclassdeffounderror

NoClassDefFoundError static flieds


@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    String reqURI = req.getRequestURI();
    reqURI = reqURI.replace(req.getContextPath(), "");
    try {
        ServiceFactory factory = ServiceFactory.getInstance();
        Service service = factory.getService(reqURI);
        service.doPost(req, resp);
    } catch (Exception e ) {
        ROOT_LOGGER.error(e.getMessage(), e);
        throw new ServletException(e);
    }
}

When i try to get ServiceFactory instance, i get NoClassDefFoundError.

It's only happens after deploying the app. If i start it through IntelliJ nothning wrong happens.

What's the problem ?

public class ServiceFactory {
    private static final Map<String, Service> SERVICE_MAP = new HashMap<>();
    private static final ServiceFactory SERVICE_FACTORY = new ServiceFactory();

private ServiceFactory() {
        init();
    }

    private static void init() {
        SERVICE_MAP.put(LOGIN_PAGE_URI, new LoginService());
        SERVICE_MAP.put(LOGOUT_PAGE_URI, new LogoutService());
        SERVICE_MAP.put(SWITCH_LANGUAGE_URI, new SwitchLanguageService());
        SERVICE_MAP.put(USERS_PAGE_URI, new AllUsersService());
        SERVICE_MAP.put(REGISTRATION_PAGE_URI, new RegistrationService());
        SERVICE_MAP.put(DELETE_USER_PAGE_URI, new DeleteUserService());
        SERVICE_MAP.put(NEW_DOCUMENT_PAGE_URI, new NewDocumentService());
        SERVICE_MAP.put(GET_FORM_AJAX_PAGE_URI, new GetFormAJAX());
    }

    public static ServiceFactory getInstance() {
        return SERVICE_FACTORY;
    }

    public Service getService(String request) {
        return SERVICE_MAP.get(request);
    }

Solution

  • From the info you are providing you probably don't include the library that is been causing NoClassDefFoundError into your class-path

    java -cp <add-jar-paths-with-file-separator> <class-to-run> <arguments>
    

    e.g.

    java -cp lib/the-jar-you-are-missing.jar;myapp.jar com.mypackage.MyClassWithMain arg1
    

    For linux replace ; character with :

    If you have a fixed path for your libraries you can also add the paths to your MANIFEST.MF

    Manifest-Version: 1.0
    ...
    Main-Class: com.mypackage.MyClassWithMain
    Class-Path: lib/the-jar-you-are-missing.jar
    

    https://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html

    Intellij won't do that for you automatically. Probably there is a way to do it but unfortunately I don't know that answer.