In this chapter, we will cover the following recipes:
Installing Java, Maven, Tomcat, and Eclipse on Mac OS
Installing Java, Maven, Tomcat, and Eclipse on Ubuntu
Installing Java, Maven, Tomcat, and Eclipse on Windows
Creating a Spring web application
Running a Spring web application
Using Spring in a standard Java application
In this chapter, we will first cover the installation of some of the tools for Spring development:
Maven: This is a build tool similar to Ant. It makes it easy to add Spring libraries to a project. Gradle is another option as a build tool.
Tomcat: This is a web server for Java web applications. You can also use JBoss, Jetty, GlassFish, or WebSphere.
Eclipse: This is an IDE. You can also use NetBeans, IntelliJ IDEA, and so on.
Then, we will build a Spring web application and run it with Tomcat.
Finally, we'll see how Spring can also be used in a standard Java application (not a web application).
We will first install Java 8 because it's not installed by default on Mac OS 10.9 or higher version. Then, we will install Maven 3, a build tool similar to Ant, to manage the external Java libraries that we will use (Spring, Hibernate, and so on). Maven 3 also compiles source files and generates JAR and WAR files. We will also install Tomcat 8, a popular web server for Java web applications, which we will use throughout this book. JBoss, Jetty, GlassFish, or WebSphere could be used instead. Finally, we will install the Eclipse IDE, but you could also use NetBeans, IntelliJ IDEA, and so on.
Install Java first, then Maven, Tomcat, and Eclipse.
Download Java from the Oracle website http://oracle.com. In the Java SE downloads section, choose the Java SE 8 SDK. Select Accept the License Agreement and download the Mac OS X x64 package. The direct link to the page is http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html.
Open the downloaded file, launch it, and complete the installation.
In your
~/.bash_profile
file, set theJAVA_HOME
environment variable. Changejdk1.8.0_40.jdk
to the actual folder name on your system (this depends on the version of Java you are using, which is updated regularly):export JAVA_HOME="/Library/Java/JavaVirtualMachines/ jdk1.8.0_40.jdk/Contents/Home"
Open a new terminal and test whether it's working:
$ java -version java version "1.8.0_40" Java(TM) SE Runtime Environment (build 1.8.0_40-b26) Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)
Download Maven from the Apache website http://maven.apache.org/download.cgi. Choose the Binary zip file of the current stable version:
Uncompress the downloaded file and move the extracted folder to a convenient location (for example,
~/bin
).In your
~/.bash_profile
file, add aMAVEN HOME
environment variable pointing to that folder. For example:export MAVEN_HOME=~/bin/apache-maven-3.3.1
Add the
bin
subfolder to yourPATH
environment variable:export PATH=$PATH:$MAVEN_HOME/bin
Open a new terminal and test whether it's working:
$ mvn –v Apache Maven 3.3.1 (12a6b3... Maven home: /Users/jerome/bin/apache-maven-3.3.1 Java version: 1.8.0_40, vendor: Oracle Corporation Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_... Default locale: en_US, platform encoding: UTF-8 OS name: "mac os x", version: "10.9.5", arch... …
Download Tomcat from the Apache website http://tomcat.apache.org/download-80.cgi and choose the Core binary distribution.
Uncompress the downloaded file and move the extracted folder to a convenient location (for example,
~/bin
).Make the scripts in the
bin
subfolder executable:chmod +x bin/*.sh
Launch Tomcat using the
catalina.sh
script:$ bin/catalina.sh run Using CATALINA_BASE: /Users/jerome/bin/apache-tomcat-7.0.54 ... INFO: Server startup in 852 ms
Tomcat runs on the
8080
port by default. In a web browser, go tohttp://localhost:8080/
to check whether it's working.
Download Eclipse from http://www.eclipse.org/downloads/. Choose the Mac OS X 64 Bit version of Eclipse IDE for Java EE Developers.
Uncompress the downloaded file and move the extracted folder to a convenient location (for example,
~/bin
).Launch Eclipse by executing the
eclipse
binary:./eclipse
We will first install Java 8. Then, we will install Maven 3, a build tool similar to Ant, to manage the external Java libraries that we will use (Spring, Hibernate, so on). Maven 3 also compiles source files and generates JAR and WAR files. We will also install Tomcat 8, a popular web server for Java web applications, which we will use throughout this book. JBoss, Jetty, GlassFish, or WebSphere could be used instead. Finally, we will install the Eclipse IDE, but you could also use NetBeans, IntelliJ IDEA, and so on.
Install Java first, then Maven, Tomcat, and Eclipse.
Add this PPA (Personal Package Archive):
sudo add-apt-repository -y ppa:webupd8team/java
Refresh the list of the available packages:
sudo apt-get update
Download and install Java 8:
sudo apt-get install –y oracle-java8-installer
Test whether it's working:
$ java -version java version "1.8.0_40" Java(TM) SE Runtime Environment (build 1.8.0_40-b25) Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25…
Download Maven from the Apache website http://maven.apache.org/download.cgi. Choose the Binary zip file of the current stable version:
Uncompress the downloaded file and move the resulting folder to a convenient location (for example,
~/bin
).In your
~/.bash_profile
file, add aMAVEN HOME
environment variable pointing to that folder. For example:export MAVEN_HOME=~/bin/apache-maven-3.3.1
Add the
bin
subfolder to yourPATH
environment variable:export PATH=$PATH:$MAVEN_HOME/bin
Open a new terminal and test whether it's working:
$ mvn –v Apache Maven 3.3.1 (12a6b3... Maven home: /home/jerome/bin/apache-maven-3.3.1 Java version: 1.8.0_40, vendor: Oracle Corporation …
Download Tomcat from the Apache website http://tomcat.apache.org/download-80.cgi and choose the Core binary distribution.
Uncompress the downloaded file and move the extracted folder to a convenient location (for example,
~/bin
).Make the scripts in the
bin
subfolder executable:chmod +x bin/*.sh
Launch Tomcat using the
catalina.sh
script:$ bin/catalina.sh run Using CATALINA_BASE: /Users/jerome/bin/apache-tomcat-7.0.54 ... INFO: Server startup in 852 ms
Tomcat runs on the 8080 port by default. Go to
http://localhost:8080/
to check whether it's working.
Download Eclipse from http://www.eclipse.org/downloads/. Choose the Linux 64 Bit version of Eclipse IDE for Java EE Developers.
Uncompress the downloaded file and move the extracted folder to a convenient location (for example,
~/bin
).Launch Eclipse by executing the
eclipse
binary:./eclipse
We will first install Java 8. Then, we will install Maven 3, a build tool similar to Ant, to manage the external Java libraries that we will use (Spring, Hibernate, and so on). Maven 3 also compiles source files and generates JAR and WAR files. We will also install Tomcat 8, a popular web server for Java web applications, which we will use throughout this book. JBoss, Jetty, GlassFish, or WebSphere could be used instead. Finally, we will install the Eclipse IDE, but you could also use NetBeans, IntelliJ IDEA, and so on.
Install Java first, then Maven, Tomcat, and Eclipse.
Download Java from the Oracle website http://oracle.com. In the Java SE downloads section, choose the Java SE 8 SDK. Select Accept the License Agreement and download the Windows x64 package. The direct link to the page is http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html.
Open the downloaded file, launch it, and complete the installation.
Navigate to Control Panel | System and Security | System | Advanced system settings | Environment Variables….
Add a
JAVA_HOME
system variable with theC:\Program Files\Java\jdk1.8.0_40
value. Changejdk1.8.0_40
to the actual folder name on your system (this depends on the version of Java, which is updated regularly).Test whether it's working by opening Command Prompt and entering
java –version
.
Download Maven from the Apache website http://maven.apache.org/download.cgi. Choose the Binary zip file of the current stable version:
Move the extracted folder to it.
Navigate to Control Panel | System and Security | System | Advanced system settings | Environment Variables….
Add a
MAVEN_HOME
system variable with the path to the Maven folder. For example,C:\Users\jerome\Programs\apache-maven-3.2.1
.Open the
Path
system variable.Append
;%MAVEN_HOME%\bin
to it.Test whether it's working by opening a Command Prompt and entering
mvn –v
.
Download Tomcat from the Apache website http://tomcat.apache.org/download-80.cgi and choose the 32-bit/64-bit Windows Service Installer binary distribution.
Tomcat runs on the 8080 port by default. Go to
http://localhost:8080/
to check whether it's working.
Download Eclipse from http://www.eclipse.org/downloads/. Choose the Windows 64 Bit version of Eclipse IDE for Java EE Developers.
Uncompress the downloaded file.
Launch the
eclipse
program.
In this recipe, we will build a simple Spring web application with Eclipse. We will:
Create a new Maven project
Add Spring to it
Add two Java classes to configure Spring
Create a "Hello World" web page
In the next recipe, we will compile and run this web application.
In this section, we will create a Spring web application in Eclipse.
Under Maven, select Maven Project and click on Next >.
Select the Create a simple project (skip archetype selection) checkbox and click on Next >.
For the Group Id field, enter
com.springcookbook
. For the Artifact Id field, enterspringwebapp
. For Packaging, selectwar
and click on Finish.
Open Maven's pom.xml
configuration file at the root of the project. Select the pom.xml tab to edit the XML source code directly. Under the project
XML node, define the versions for Java and Spring. Also add the Servlet API, Spring Core, and Spring MVC dependencies:
<properties> <java.version>1.8</java.version> <spring.version>4.1.5.RELEASE</spring.version> </properties> <dependencies> <!-- Servlet API --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> </dependencies>
Create the Java packages
com.springcookbook.config
andcom.springcookbook.controller
; in the left-hand side pane Package Explorer, right-click on the project folder and select New | Package….In the
com.springcookbook.config
package, create theAppConfig
class. In the Source menu, select Organize Imports to add the needed import declarations:package com.springcookbook.config; @Configuration @EnableWebMvc @ComponentScan (basePackages = {"com.springcookbook.controller"}) public class AppConfig { }
Still in the
com.springcookbook.config
package, create theServletInitializer
class. Add the needed import declarations similarly:package com.springcookbook.config; public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[0]; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{AppConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
This section will give more you details of what happened at every step.
The generated Maven project is a pom.xml
configuration file along with a hierarchy of empty directories:
pom.xml src |- main |- java |- resources |- webapp |- test |- java |- resources
The declared Maven libraries and their dependencies are automatically downloaded in the background by Eclipse. They are listed under Maven Dependencies in the left-hand side pane Package Explorer.
Tomcat provides the Servlet API
dependency, but we still declared it because our code needs it to compile. Maven will not include it in the generated .war
file because of the <scope>provided</scope>
declaration.
AppConfig
is a Spring configuration class. It is a standard Java class annotated with:
@Configuration
: This declares it as a Spring configuration class@EnableWebMvc
: This enables Spring's ability to receive and process web requests@ComponentScan(basePackages = {"com.springcookbook.controller"})
: This scans thecom.springcookbook.controller
package for Spring components
ServletInitializer
is a configuration class for Spring's servlet; it replaces the standard web.xml
file. It will be detected automatically by SpringServletContainerInitializer
, which is automatically called by any Servlet 3. ServletInitializer
extends the AbstractAnnotationConfigDispatcherServletInitializer
abstract class and implements the required methods:
getServletMappings()
: This declares the servlet root URI.getServletConfigClasses()
: This declares the Spring configuration classes. Here, we declared theAppConfig
class that was previously defined.
We created a controller class in the com.springcookbook.controller
package, which we declared in AppConfig
. When navigating to http://localhost:8080/hi
, the hi()
method will be called and Hello, world. will be displayed in the browser. This will be explained further in Chapter 3, Using Controllers and Views.
In this recipe, we will use the Spring web application from the previous recipe. We will compile it with Maven and run it with Tomcat.
Here are the steps to compile and run a Spring web application:
In
pom.xml
, add this boilerplate code under theproject
XML node. It will allow Maven to generate.war
files without requiring aweb.xml
file:<build> <finalName>springwebapp</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.5</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build>
In Eclipse, in the left-hand side pane Package Explorer, select the
springwebapp
project folder. In the Run menu, select Run and choose Maven install or you can executemvn clean install
in a terminal at the root of the project folder. In both cases, atarget
folder will be generated with thespringwebapp.war
file in it.Copy the
target/springwebapp.war
file to Tomcat'swebapps
folder.Launch Tomcat.
In a web browser, go to
http://localhost:8080/springwebapp/hi
to check whether it's working.
In pom.xml
the boilerplate code prevents Maven from throwing an error because there's no web.xml
file. A web.xml
file was required in Java web applications; however, since Servlet specification 3.0 (implemented in Tomcat 7 and higher versions), it's not required anymore.
On Mac OS and Linux, you can create a symbolic link in Tomcat's webapps
folder pointing to the .war
file in your project folder. For example:
ln -s ~/eclipse_workspace/spring_webapp/target/springwebapp.war ~/bin/apache-tomcat/webapps/springwebapp.war
So, when the.war
file is updated in your project folder, Tomcat will detect that it has been modified and will reload the application automatically.
In this recipe, we will build a standard Java application (not a web application) using Spring. We will:
In this section, we will cover the steps to use Spring in a standard (not web) Java application.
Open Maven's pom.xml
configuration file at the root of the project. Select the pom.xml tab to edit the XML source code directly. Under the project
XML node, define the Java and Spring versions and add the Spring Core dependency:
<properties> <java.version>1.8</java.version> <spring.version>4.1.5.RELEASE</spring.version> </properties> <dependencies> <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> </dependencies>
Create the
com.springcookbook.config
Java package; in the left-hand side pane Package Explorer, right-click on the project and select New | Package….In the
com.springcookbook.config
package, create theAppConfig
class. In the Source menu, select Organize Imports to add the needed import declarations:@Configuration public class AppConfig { }
Create a User
Java class with two String
fields:
public class User { private String name; private String skill; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSkill() { return skill; } public void setSkill(String skill) { this.skill = skill; } }
In the AppConfig
class, define a User
bean:
@Bean public User admin(){ User u = new User(); u.setName("Merlin"); u.setSkill("Magic"); return u; }
Create the
com.springcookbook.main
package with theMain
class containing themain()
method:package com.springcookbook.main; public class Main { public static void main(String[] args) { } }
In the
main()
method, retrieve the User singleton and print its properties:AnnotationConfigApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class); User admin = (User) springContext.getBean("admin"); System.out.println("admin name: " + admin.getName()); System.out.println("admin skill: " + admin.getSkill()); springContext.close();
Test whether it's working; in the Run menu, select Run.
We created a Java project to which we added Spring. We defined a User
bean called admin
(the bean name is by default the bean method name). Spring beans are explained in the next chapter.
In the Main
class, we created a Spring context object from the AppConfig
class and retrieved the admin
bean from it. We used the bean and finally, closed the Spring context.