Book Image

Spring MVC Cookbook

By : Alexandre Bretet, Alex Bretet
Book Image

Spring MVC Cookbook

By: Alexandre Bretet, Alex Bretet

Overview of this book

Spring MVC is a lightweight application framework that comes with a great configuration by default. Being part of the Spring Framework, it naturally extended and supported it with an amazing set of recognizable annotations. External libraries can be plugged in and plugged out. It also possesses a request flow. Complete support of REST web services makes the Spring architecture an extremely consistent choice to support your front-end needs and Internet transformations. From the design of your Maven modules, you will achieve an Enterprise-standard for a stateless REST application based on Spring and Spring MVC with this book. This guide is unique in its style as it features a massive overview of practical development techniques brought together from the Spring ecosystem, the new JEE standards, the JavaScript revolution and Internet of Things. You will begin with the very first steps of Spring MVC's product design. Focused on deployment, viability, and maintainability, you will learn the use of Eclipse, Maven, and Git. You will walk through the separation of concerns driven by the microservices principles. Using Bootstrap and AngularJS, you will develop a responsive front-end, capable of interacting autonomously with a REST API. Later in the book, you will setup the Java Persistence API (JPA) within Spring; learn how to configure your Entities to reflect your domain needs, and discover Spring Data repositories. You will analyze how Spring MVC responds to complex HTTP requests. You will implement Hypermedia and HATEOAS to guide your customer's stateless conversation with the product and see how a messaging-service based on WebSocket can be configured. Finally you will learn how to set up and organize different levels of automated-tests, including logging and monitoring.
Table of Contents (16 chapters)
Spring MVC Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Configuring Eclipse for Java 8, Maven 3, and Tomcat 8


This recipe entails configuration technics to develop efficiently on Eclipse with Java, Maven, and Tomcat.

Getting ready

Once the different products are installed, there are a couple of steps that we need to follow, mainly to make Eclipse work properly with Java SE 8, Maven 3, and Tomcat 8. In this recipe, we will also look at how to customize the Eclipse configuration file (Eclipse.ini) in order to make the most of the platform that runs Java and to make sure that it will cope with any significant growth of the application.

How to do it...

Let's take a look at the following steps to configure Eclipse on your desktop:

  1. You can start by creating a shortcut on your desktop to point to the Eclipse executable:

    • On Windows, the executable file is Eclipse.exe and is located at the eclipse directory root

    • On Linux/Mac, the file is named Eclipse and is also is located at the eclipse directory root

  2. Then, we need to customize the eclipse.ini file:

    In the Eclipse directory, where you have previously extracted the Eclipse archive, you can find the eclipse.ini file. It is a text file that contains a few command-line options in order to control the Eclipse startup.

    • The Eclipse community recommends to specify the path to our JVM here. Hence, depending on your system, add the following two lines at the top of the file:

    For Windows, add the following:

    -vm 
    C:\java\jdk1.8.0_25\jre\bin\server\jvm.dll
    

    For Linux/Mac, add this:

    -vm 
    /usr/java/jdk1.8.0_25/jre/lib/{your.architecture}/server/libjvm.so
    

    The following is an optional setting that you can consider:

    • If your development machine has at least 2 GB of RAM, you can enter the following options to make Eclipse run faster than the default settings. This section is optional because Eclipse's default settings are already optimized to suit most users' environment:

      -vmargs
      -Xms128m
      -Xmx512m
      -Xverify:none
      -Dosgi.requiredJavaVersion=1.6
      -XX:MaxGCPauseMillis=10
      -XX:MaxHeapFreeRatio=70
      -XX:+UseConcMarkSweepGC
      -XX:+CMSIncrementalMode
      -XX:+CMSIncrementalPacing
      

      If your machine has less than 2 GB of RAM, you can still enter this set of options without overriding the default –Xms and –Xmx arguments.

      Tip

      All the options under -vmargs are arguments that will be passed to the JVM at startup. It is important not to mess up the Eclipse options (the top part of the file) with the VM arguments (the bottom part).

  3. After this we will go through the following steps to start Eclipse and set the workspace:

    Launch the executable described in the Step 2.

    • For our project, specify the path: <home-directory>/workspace

    This path is different for each Operating System:

    • C:\Users\{system.username}\workspace: This is the path on Windows

    • /home/usr/{system.username}/workspace: This is on Linux

    • /Users/{system.username}/workspace: This is on Mac OS

    • Click on OK and let the Eclipse program start

    Note

    The workspace is the place from where you manage your Java projects. It can be specific to one application, but not necessarily.

  4. Then, we need to check the JRE definitions:

    Here, a couple of settings need to be verified in Eclipse:

    1. Open the Preferences menu under Window (on Mac OS X the Preference menu is under the Eclipse menu).

    2. In the navigation panel on the left-hand side, open the Java hierarchy and click on Installed JREs under Java.

    3. On the central screen, remove any existing JREs that you may already have.

    4. Click on the Add… button to add a standard JVM.

    5. Enter C:\java\jdk1.8.0_25 (or /usr/java/...) as JRE home.

    6. And enter jdk1.8.0_25 as JRE name.

    Note

    We tell Eclipse to use the Java Runtime Environment of JDK 8.

    After completing these steps, you should end up with the following configuration:

  5. Now, we will check the compiler compliance level:

    1. In the navigation panel, click on Compiler under Java.

    2. Check that the Compiler compliance level is set to 1.8 in the drop-down list.

  6. After this, we need to check the Maven configuration:

    1. Still in the navigation panel of the Preferences menu, open the Maven hierarchy and navigate to Maven | Installations.

    2. We will specify here which Maven installation we plan to use. For the purpose of this book, the embedded Maven will be perfect.

    3. Back in the navigation panel, go to Maven | User Settings.

    4. Set the local repository to <home-directory>/.m2/repository.

      Note

      In this local repository, our local cached versions of the required artefacts will reside. It will prevent our environment from having to download them on each build.

    5. For the User Settings field, create a settings.xml file in the .m2 directory: <home-directory>/.m2/settings.xml.

    6. Edit the settings.xml file and add the following block:

      (You can also copy/paste it from the chapter_1/source_code/.m2 directory):

      <settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
        <profiles>
          <profile>
            <id>compiler</id>
              <properties>
                <JAVA_HOME>C:\java\jdk1.8.0_25</JAVA_HOME>
              </properties>
          </profile>
        </profiles>
        <activeProfiles>
        <activeProfile>compiler</activeProfile>
        </activeProfiles>
      </settings>

      Tip

      If you are not on a Windows machine, change JAVA_HOME in this file to your JDK installation directory (/usr/java/jdk1.8.0_25).

    7. Go back to the navigation panel and click on Maven. Follow the configuration given in this screenshot:

    8. Click on OK to save these configuration changes.

  7. Now we will install Tomcat 8 in the Eclipse IDE. For this, go through these steps:

    1. Download a ZIP archive for the latest Core version of Tomcat8 from the Tomcat website: http://tomcat.apache.org/download-80.cgi.

    2. Extract the downloaded archive to the following directory:

      • On Windows, extract the archive at C:\tomcat8

      • On Linux, extract the archive at /home/usr/{system.username}/tomcat8

      • On Mac OS X, extract the archive at /Users/{system.username}/tomcat8

      Note

      Depending on your system, you must be able to access the bin directory from the hierarchy: C:\tomcat8\bin, /home/usr/{system.username}/tomcat8/bin or /Users/{system.username}/tomcat8/bin.

    3. In Eclipse, select the Preferences menu under Windows, and in the navigation panel on the left-hand side, open the Server hierarchy and then select Runtime Environments.

    4. On the central window, click on the Add… button.

    5. In the next step (the New Server environment window), navigate to Apache | Apache Tomcat v8.0.

    6. Also, check this option: Create a New Local Server.

    7. Click on the Next button.

    8. Fill in the details in the window as shown in the following screenshot:

    Note

    If you are on Linux (or Mac OS X), replace C:\tomcat8 with your Tomcat installation directory.

How it works...

We are going to review in this section the different elements and concepts that this recipe took us through.

The eclipse.ini file

As we've already seen, the eclipse.ini file controls the Eclipse startup. It is an extra component that makes the Eclipse platform very configurable. You can find the list of command-line arguments that can be used in their documentation at

http://help.eclipse.org/luna/topic/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html

It is important to acknowledge the following warnings that this documentation mentions:

  • All lines after -vmargs are passed as arguments to the JVM; all arguments and options for Eclipse must be specified before -vmargs (just like when you use arguments on the command line)

    Note

    This explains why we have inserted the –vm option at the top of the file.

  • Any use of -vmargs on the command line replaces all -vmargs settings in the .ini file unless --launcher.appendVmargs is specified either in the .ini file or on the command line

Setting the –vm option

Setting the -vm option allows us to be sure of the JVM implementation on which Eclipse runs as a program. You might have noticed that we've targeted the JVM as a library (*.dll / *.so). It has better performance on startup and also identifies the program process as the Eclipse executable and not just as the Java executable.

If you wonder which JVM Eclipse uses when a –vm option is not set, be aware that Eclipse DOES NOT consult the JAVA_HOME environment variable. (Eclipse wiki).

Instead, Eclipse executes the Java command that parses your path environment variable.

Customizing JVM arguments

The suggested JVM argument list comes from Piotr Gabryanczyk's work on the Java memory management model. Initially, for JetBRAINS IntelliJ settings, this configuration is also useful for an Eclipse environment. It helps in the following tasks:

  • Preventing the garbage collector from pausing the application for more than 10 ms (-XX:MaxGCPauseMillis=10)

  • Lowering the level from which the garbage collector starts to 30% of the occupied memory (-XX:MaxHeapFreeRatio=70)

  • Imposing the garbage collector to run as a parallel thread, lowering its interference with the application (-XX:+UseConcMarkSweepGC)

  • Choosing the incremental pacing mode for the garbage collector, which generates breaks in the GC job so that the application can definitely stop freezing (–XX:+CMSIncrementalPacing)

The instantiated objects throughout the program's life cycle are stored in the Heap memory. The suggested parameters define a JVM startup Heap space of 128 mb (-Xms) and an overall 512 mb maximum heap space (–Xmx). The heap is divided in two subspaces, which are as follows:

  • Young generation: New objects are stored in this area. For the leading Hotspot or OpenJDK JVMs, the young memory space is divided in two:

    • Eden: New objects are stored in this subdivision area. Objects with short lives will be deallocated from here.

    • Survivor: This is a buffer between the young and old generation. The survivor space is smaller than the Eden and it is also divided in two (the FROM and TO areas). You can adjust the ratio between Eden and Survivor objects with -XX:SurvivorRatio (here, -XX: SurvivorRatio=10 means YOUNG = 12, EDEN = 10, FROM = 1 and TO =1).

      Tip

      The minimum size of the young area can be adjusted with -XX:NewSize. The maximum size can be adjusted with -XX:MaxNewSize.

  • Old generation: When objects in Eden or Survivor spaces are still referenced after enough garbage collections, they are moved here. It is possible to set the Young area size as a ratio of the Old area size with -XX:NewRatio. (That is, -XX:NewRatio=2 means HEAP = 3, YOUNG = 1 and OLD =2).

    Tip

    The maximum size for the new generation space -XX:MaxNewSize must always remain smaller than half the heap space (-Xmx/2) because the garbage collector may move all the Young space to the Old space.

With Hotspot or OpenJDK, the permanent generation space was used to store information related to the classes' definition (structure, fields, methods, and so on.). You may have already encountered a PermGen space OutOfMemoryError exception when the loaded structure becomes too big. In this situation, the solution is to increase the -XX:MaxPermSize argument. It is no longer necessary with JDK8.

For this purpose, the Permanent Generation (PermGen) space has been replaced by a metadata space that is not part of the heap but of the native memory. The default maximum size of this space is unlimited. However, we can still restrict it with -XX:MetaspaceSize or -XX:MaxMetaspaceSize.

Changing the JDK compliance level

Downgrading a compliance level allows us to run a lower version of a Java compiler than the one the JDK is natively identified to. It impacts the Eclipse builds, errors, and warnings and also the JavaDocs. It is obviously not possible to set a higher compilation version than the native version of a compiler.

Configuring Maven

Inside Eclipse, most of the Maven configuration comes from the m2eclipse plugin (also called Maven integration for Eclipse). This plugin is included, by default, in Eclipse Luna. It is then not necessary to download it manually. After the Maven configuration that we went through, m2eclipse is also very helpful to trigger Maven operations from the IDE context and to provide assistance to create Java Maven projects. You will learn more about m2eclipse in the next section.

We then installed a basic settings.xml file. This file is used to configure Maven without being bound directly to any projects. The most common uses of settings.xml are probably profile definition and credential storage to access the repository manager(s).

With Maven profiles, you have the possibility to run a build for a specific environment and to match a specific configuration (variable values, set of dependencies, and so on.). Maven profiles can be cumulated with each other. They can be activated through a command line, declaratively in the Maven settings or from the environment configuration such as files being present or missing on the filesystem, the used JDK, and so on.

Tip

In our settings.xml file, we have defined a compiler profile with its own JAVA_HOME property. The compiler profile is activated by default to be declaratively defined in the <activeProfiles> section. Maven will consult the settings.xml file before looking up the system variables.

A repository manager

A repository manager is a third-party application that manages all the required binaries and dependencies that a developed application may need. Acting as a buffering proxy between development environments and public repositories, a repository manager provides control of critical parameters such as build time, availability of dependencies, visibility and access restriction, and so on.

Famous solutions include Apache Archiva, Artifactory, Sonatype Nexus. In the context of our application, we won't make use of a repository manager.

Tomcat 8 inside Eclipse

Eclipse for JEE developers allows the integration of Tomcat with other application servers within the development environment. This is made possible through the provided Web Tools Platform (WTP) plugins that can manage web artefacts, their compilation, and their deployment into the web server.

In the servers tab (made visible earlier), double-clicking on the created Tomcat v8.0 server, opens a configuration window and enables the possibility of setting up parameters that are normally defined in the server.xml Tomcat file, which is located in the tomcat8\conf directory.

By default, WTP abstracts this configuration and doesn't impact the genuine server.xml file. This behavior can be changed by activating the Publish module contexts to separate XML files option in the Server configuration window.

There's more...