java.lang.NoClassDefFoundError, java.lang.ClassNotFoundException

When you add a dependency reference to a Java project, it may compile without any errors, but runtime you may get an error message similar to this:

HTTP Status 500 – Internal Server Error

Type Exception Report

Message An exception occurred processing JSP page [/index.jsp] at line [1]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: An exception occurred processing JSP page [/index.jsp] at line [1]

1: <jsp:forward page=”….html” />

Root Cause

javax.servlet.ServletException: Servlet.init() for servlet [spring] threw exception…

Root Cause

java.lang.NoClassDefFoundError: org/springframework/core/env/PropertySource…

Root Cause

java.lang.ClassNotFoundException: org.springframework.core.env.PropertySource…

If the newly added dependency also depends on another package, and that package is already in the pom.xml file, NetBeans will not show an error during build.

If the newly added dependency was recently introduced, and the version of the package already included in the pom.xml file,  references an earlier version, the runtime error will occur.

For example org.springframework.web.bind.annotation.GetMapping was introduced in Spring Web 4.0

If your pom.xml file already contains the reference to spring-web or spring-webmvc version 3, your application will fail runtime.

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

In your web browser navigate to the Maven repository at https://mvnrepository.com/artifact/org.springframework and search for the spring-web and spring-webmvc packages. Get the latest stable version numbers and update your pom.xml file.

 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.0.2.RELEASE</version>
 </dependency>

 

 

Java Spring MVC web application configuration in NetBeans 8

When you create a Java Spring MVC web application or make changes to an existing one, it is important to know the location of configuration values.

Java package name

The Java package name is stored in

  • Every .java file
    • package MY_PACKAGE_NAME
  • pom.xml file
    • <configuration>
        <mainClass>com.objectdb.Enhancer</mainClass>
          <arguments>
            <argument>MY_PACKAGE_NAME.MY_MAIN_CLASS_NAME</argument>
          </arguments>
      </configuration>
  • .jsp file
    • <%@page import=”MY_PACKAGE_NAME.*”%>
    • <jsp:useBean id=”MY_BEAN_ID” type=”MY_PACKAGE_NAME.MY_DAO_CLASS_NAME” scope=”request” />

WAR file name

The name of the WAR fle is set in the

  • pom.xml file
    • <finalName>MY_WAR_FILE_NAME</finalName>

Add references to external classes

When you copy a class from another project, you need to add references to the imported external classes. When you build your project, the missing references will be in the output window.

————————————————————-
COMPILATION ERROR :
————————————————————-
webapp/twitter_keywordsRepository.java:[3,42] error: package org.springframework.data.repository does not exist

To add the reference to the project

  1. Click the error message link in the output window,
  2. Click the light bulb in the line of the error,
  3. In the context menu select Search Dependency at Maven Repositories for
  4. Select the recommended Maven repository, and click the Add button.

The references are stored in the

  • pom.xml file under
    • <dependencies>

 

 

 

org.apache.jasper.JasperException: java.lang.IllegalStateException: No output folder

This error can happen on Linux and Windows, and the cause could be the same.

On Windows Server 2012R2 I opened a command prompt. To be able to delete a directory from the Tomcat webapps folder, I have issued the shutdown command.

When I started the server with the startup command, and navigated to my local website, my Java Spring MVC web application displayed the error message

org.apache.jasper.JasperException: java.lang.IllegalStateException: No output folder

The problem was, that the Tomcat service runs under root on Linux, and SYSTEM on Windows.

When you issue the startup command, Tomcat will run under the user account you logged in with.

Solution:

Stop and start the TomCat Linux or Windows service instead of issuing the shutdown and startup commands from the terminal or command prompt.

 

Only persistence units with transaction type JTA can be used as a container managed entity manager

NetBeans can use multiple deployment servers. When your web application uses the Entity Framework and you select the Glassfish server as the deployment server, you can get the error message when you try to run your application in the IDEÉ

Severe: Exception while preparing the app : The persistence-context-ref-name […] in module […] resolves to a persistence unit called […] which is of type RESOURCE_LOCAL. Only persistence units with transaction type JTA can be used as a container managed entity manager. Please verify your application.

When you first run the application NetBeans asks you to select the deployment server you want to use.

If only the Glassfish server is available, and Tomcat is installed on your workstation, add Tomcat to the available deployment servers.

Install Tomcat

For the Tomcat installation see Tomcat web server installation

Add Tomcat to the NetBeans server list

  1. In the Tools menu select Servers
  2. Click the Add Server button
  3. In the list select the Apache Tomcat or TomEEE server
  4. Click the Browse… button
  5. Select the Tomcat directory on your workstation
  6. Enter a Tomcat username and password for NetBeans, and click the Finish button.
  7. The user will be created in the tomcat-users.xml file in the Tomcat conf directory
  8. Click the Close button.

Select the Deployment Server

  1. Right-click the NetBeans project and select Run
  2. In the Select deployment server window select Apache Tomcat or TomEE

If the Select deployment server window does not pop up

  1. Right-click the NetBeans project and select Set Configuration -> Customize
  2. On the Run tab select the Apache server.

Starting of Tomcat failed, the server port 8080 is already in use

  1. If the Glassfish server already started, Tomcat cannot use the same ports and an error message will appear in the NetBeans RunOutput tab
  2. To stop the Glassfish server, restart your workstation.

Deploy a WAR file of a Java web application on the Apache Tomcat web server

There are two ways to deploy a WAR file of a Java web application on the Apache Tomcat web server

Using the command line

  1. Copy the WAR file into the webapps folder of the Tomcat installation directory,
  2. Make sure the CATALINA_HOME environment variable points to the Tomcat directory (not the bin subdirectry)
  3. Open a Terminal window or Command Prompt,
  4. Navigate to the bin directory of the Tomcat web server installation directory,
  5. Execute
    startup
  6. Tomcat will unzip the war file into a directory named after the WAR file and display the message similar to this.

    C:\Program Files\apache-tomcat-8.5.23\bin>startup
    Using CATALINA_BASE: “C:\Program Files\apache-tomcat-8.5.23”
    Using CATALINA_HOME: “C:\Program Files\apache-tomcat-8.5.23”
    Using CATALINA_TMPDIR: “C:\Program Files\apache-tomcat-8.5.23\temp”
    Using JRE_HOME: “C:\Program Files\Java\jre-9.0.1”
    Using CLASSPATH: “C:\Program Files\apache-tomcat-8.5.23\bin\bootstrap.jar;C:\Program Files\apache-tomcat-8.5.23\bin\tomcat-juli.jar”C:\Program Files\apache-tomcat-8.5.23\bin>

Using the Tomcat user interface

  1. Remote into the web server,
  2. Copy the WAR file to a temp directory,
  3. Open the Tomcat web user interface at http://localhost:8080/manager
  4. Log in with the credentials specified for the manager-gui role in the tomcat-users.xml file of the conf Tomcat folder,
  5. In WAR file to deploy section click the Choose File button and select the WAR file,
  6. Click the Deploy button,
  7. Tomcat will unzip the war file into a directory named after the WAR file in the webapps folder of the Tomcat installation directory.

Create a WAR file for a Java web application in NetBeans

Configure the web application

Add the web.xml file

The wb.xml file contains the web application configuration values for the webserver. I has to be in the WEB-INF directory of the web applicaion. To add the web.xml file to your NetBeans Java web application

  1. Right-click the Netbeans project, and select New -> Other
  2. In the New File window select XML -> XML Document, and click the Next button,
  3. In the New XML Document window enter web.xml as the name of the file, and click the Browse… button to select the location,
  4. Select the src\main\webapp\WEB-INF folder, and click the Select Folder button,
  5. In the New XML Document window click the Next button,
  6. In the New File window keep the Well-formed Document radio button selected and click the Finish button,
  7. NetBeans creates the XML file in the Web PAges WEB-INF folder on the web project.

Build the WAR file

To create a WAR file for a Java web application in NetBeans 8.2

  1. In the NetBeans IDE select the Files tab,
  2. Right-click the pom.xml file and select Run Maven > Goals…
  3. In the Run Maven window enter compile war:war into the Goals field,
  4. Select the Remember as checkbox and enter Compile war for the name,
  5. The WAR file is generated in the target directory of the Java web project.
  6. The next time you want to build the WAR file, the Compile war option will be visible in the Run Maven menu.

java.sql.SQLException: Incorrect string value: ‘\xF0\x9F\x96\xA4\xE2\x9C…’ for column

When your application tries to store 4-byte Unicode characters in a MySQL database you may get the error rmessage

java.sql.SQLException: Incorrect string value: ‘\x..\x..\x..\x..\x..\x…’ for column

 

To store 4-byte Unicode characters in MySQL you need

  • a modern version of the database engine, version 5.5 or later,
  • set the column collation to COLLATE utf8mb4_unicode_ci in the database,
  • configure MySQL to use utf8mb4 in the character columns.

 

To set the default character set and server settings to utf8mb4

  1. Open the C:\ProgramData\MySQL\MySQL Server 5.x\my.ini file
  2. Under [client] add
    default-character-set = utf8mb4
  3. Under [mysql] set the value to utf8mb4 in line
    default-character-set = utf8mb4
  4. Under [mysqld] set the value to utf8mb4 in line
    character-set-server = utf8mb4
  5. Under [mysqld] add the lines
    character-set-client-handshake = FALSE
    character-set-server = utf8mb4
    collation-server = utf8mb4_unicode_ci

Restart the MySQL server

  1. Restart the MySQL database server for the changes to take effect
  2. in MySQL Workbench reconnect the database.

Change the schema of an existing database

  1. In MySQL Workbench connect to the database server,
  2. Right-click the database and select Alter Schema,
  3. Set the collation to utf8mb4_unicode_ci collation
  4. Click the Appy button to save the changes,
  5. Click the Apply button again to confirm the instructions,
  6. Click the Finish button to execute the script.

To check the database settings execute the SQL query in MySQL Workbench

use MY_DATABASE_NAME;
SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';

It should show

+--------------------------+--------------------+
| Variable_name            | Value              |
+--------------------------+--------------------+
| character_set_client     | utf8mb4            |
| character_set_connection | utf8mb4            |
| character_set_database   | utf8mb4            |
| character_set_filesystem | binary             |
| character_set_results    | utf8mb4            |
| character_set_server     | utf8mb4            |
| character_set_system     | utf8               |
| collation_connection     | utf8mb4_unicode_ci |
| collation_database       | utf8mb4_unicode_ci |
| collation_server         | utf8mb4_unicode_ci |
+--------------------------+--------------------+

Repair and optimize all tables

Make sure you execute the mysqlcheck command to repair and optimize all tables to avoid silent update errors

On Windows

"C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqlcheck" -u root -p --auto-repair --optimize --all-databases

The utility makes it easy to execute the repair and optimize commands for every table

# For each table
REPAIR TABLE table_name;
OPTIMIZE TABLE table_name;

Package dependent Java JAR files into the project JAR file

When you execute your Java JAR file, you need to include all dependent JAR files in the “fat jar” file, so the Java virtual machine can find them at runtime.

Set up NetBeans to include the JAR files from the library

In NetBeans you need to add the list of dependent libraries to the build.xml file.

  1. On the Files tab double-click the build.xml file to open it in the editor,
  2. Add the lines below to the build.xml file before the </project> statement. Change the value of the second line to specify the name of your project.
    <target name="package-for-store" depends="jar">
        <property name="store.jar.name" value="MY_PROJECT"/>
        <property name="store.dir" value="store"/>
        <property name="store.jar" value="${store.dir}/${store.jar.name}.jar"/>
        <echo message="Packaging ${application.title} into a single JAR at ${store.jar}"/>
        <delete dir="${store.dir}"/>
        <mkdir dir="${store.dir}"/>
        <jar destfile="${store.dir}/temp_final.jar" filesetmanifest="skip">
            <zipgroupfileset dir="dist" includes="*.jar"/>
            <zipgroupfileset dir="dist/lib" includes="*.jar"/>
            <manifest>
            <attribute name="Main-Class" value="${main.class}"/>
            </manifest>
        </jar>
        <zip destfile="${store.jar}">
            <zipfileset src="${store.dir}/temp_final.jar"
            excludes="META-INF/*.SF, META-INF/*.DSA, META-INF/*.RSA"/>
        </zip>
        <delete file="${store.dir}/temp_final.jar"/>
    </target>
  3. Save the build.xml file.

Build the project

  1. Right click the build.xml file,
  2. Select Run Target > Other Targets > package-for-store
  3. The generated file is going to be located in the store directory.

Start a new Spring MVC Java Web application development in NetBeans

When you create your first Spring MVC Java web application in the base installation of NetBeans follow the steps below

Create a project

  1. In the File menu select New Project
  2. Select the Java Web category, select the Web Application project, and click Next,
  3. Enter the name of the project and click Next,
  4. If this is the first Java web application you create in NetBeans, most likely there is no web server for Java is installed on your workstation. If this is the case, click the Add… button,
  5. Keep the GlassFish Server selected and click Next,
  6. Select the I have read… checkbox and click the Download Now… button,
  7. Keep the latest version selected and click OK,
  8. Make sure the I have read… checkbox is still selected, and click Next,
  9. Click Finish to register the domain on your workstation,
  10. The Context Path shows the address for your application. Click Finish again to continue.
  11. Select the Spring Web MVC framework and click Finish.
  12. If a library is missing from your workstation, a message pops up. Click the Resolve Problems… button for instructions,
  13. On the Resolve Project Problems window click the Resolve… button,
  14. Download the missing library to your workstation. In this case, navigate your web browser to http://www.java2s.com/Code/Jar/j/Downloadjavaeeendorsedapi70jar.htm
  15. Download the “javaee-endorsed-api-7.0.jar” library
  16. Create the folder C:\Users\YOUR_USER_NAME\AppData\Roaming\NetBeans\8.2\modules\ext\javaee7-endorsed
  17. Extract the “javaee-endorsed-api-7.0.jar” file into the new folder,
  18. On the Ant Library Manager window click the New Library… button,
  19. Enter “javaee-endorsed-api-7.0” into the Library Name field and click OK,
  20. Click the Add JAR/Folder… button,
  21. Navigate the to extracted JAR file at “C:\Users\YOUR_USER_NAME\AppData\Roaming\NetBeans\8.2\modules\ext\javaee7-endorsed” and click the Add JAR/Folder button,
  22. On the Ant Library Manager window click the OK button,
  23. On the Resolve Project Problems window click Close.

Start the application

  1. In the Project list right-click the web application project and select Run
  2. The Output window should display a similar message,
  3. Open a web browser and navigate to http://localhost:8080/MY_PROJECT_NAME, to display the index page. The server is case sensitive, so make sure the spelling of the project name is correct.

 

The application configuration files

With the default settings the index.jsp composes the index page. It is in the Web Pages/WEB-INF/jsp directory.

The web.xml file in the Configuration Files directory points to the first Java Server Pages file: redirect.jsp

The redirect.jsp file is located in the Web Pages directory

The Dispatcher

The dispatcher-servlet.xml file contains the mapping between the HTML file, controller, and view.

<property name="mappings">
  <props>
    <prop key="index.htm">indexController</prop>
  </props>
</property>

The bean section specifies the name of the view for the controller.

 <!--
 The index controller.
 -->
 <bean name="indexController"
       class="org.springframework.web.servlet.mvc.ParameterizableViewController"
       p:viewName="index" />

Web Application Build and Deployment

To generate a war file of your web application

  1. In the Project Files directory right click the pom.xml file and select Run Maven > Goals
  2. In the Goals field type
    compile war:war

    and click OK

  3. NetBeans creates the war file in the target directory.

 

Configure NetBeans for Java Web development

The base installation of NetBeans does not include the web development category.

 

To add the Java web development tools to NetBeans

  1. Start the NetBeans IDE,
  2. In the Tools menu select Plugins,
  3. On the Available Plugins tab select the Java EE Base plugin and click the Install button,
  4. If any of the installed plugins is missing the valid signature, you need to click the Continue button to allow the installation,
  5. For the plugin installation, you need to restart the NetBeans IDE,
  6. During the next start, NetBeans installs the new plugins,
  7. The Java Web category is now available.