# 01.2-SpringBoot basics-Lesson2: Java Application Servers ###### tags: `Udacity` # 01 Web Development in Java {%youtube t0Oj-CM31XE%} > This Lesson is Your Introduction to Java Web Development ![](https://i.imgur.com/SgiPtLE.png) **Lesson Outline** In this lesson, you'll be introduced to the following ideas and tools: * **Java Application Servers**: We introduce the basics of server-side web development and how a Java Application Server simplifies things. * **Java Servlets**: We discuss the central feature of the Application Server, the Servlet, and how it allows developers to access the conveniences provided by the Application Server. * **Spring Applications**: We introduce Spring Framework, a collection of Java libraries and tools that build on the Application Server and Servlet to provide a huge amount of utility to Java web developers. * **Spring Starter Packs**: We discuss the various "starter packs" available through Spring Boot's project generator, which can be used to quickly get up and running with a new Spring Boot project configured for specific features. * **Maven and the POM file**: We introduce Maven, a dependency management tool for Java that allows developers to easily use powerful open-source libraries in their projects. We discuss how dependencies are declared in Maven's pom.xml file. # 02 Big Picture {%youtube JI6cbTaOapQ%} > How a Java Application Server Connects Applications to the Web ![](https://i.imgur.com/PRoWC0D.png) A web server's primary role is listening for HTTP requests and handling them with application logic, sending an HTTP response to the client that indicates the result of the operation. Simple HTTP servers host directories of HTML files directly, sending files in response to requests for specific URLs. This is enough for static websites with no dynamic server operations, but modern web apps support users accounts, complex interactions, and persistent data. Java application servers make these features more accessible by hosting many individual applications, managing them over a common interface, the servlet. This allows developers to focus on application logic and features, with HTTP request handling and routing handled by the server. Spring provides additional sets of libraries that integrate with the servlet interface to provide applications with even more utilities that focus on database access, security, and HTML generation, and it's the tool we'll use to build our web applications. **Key Terms** * **HTTP Request/Response**: HTTP, or HyperTextTransferProtocol, is a binary data format for communication between programs over the web. It can be broken down into two basic message types: requests and responses. Clients send requests for resources to servers, which respond with the requested data. Read more about the protocol here. * **HTTP `GET` and `POST`**: Every HTTP request has an important header that determines its method. `GET` and `POST` are two of the most common; `GET` indicates a request for data from the server, and `POST` represents a request to "post" new data to the server - this usually represents some action on server data like submitting search terms, posting an update, or adding new data to the server. # 03 Intuition Developing Your Intuition about Web Development with Java {%youtube VYA8VzMDJ90%} When building a web application, there are a lot of helpful tools that can solve common problems for you. How do you decide what you need to implement a given feature? Since we're going to be building web apps with Java and Spring boot, the first step is to research what Spring supports and recommends for that feature. [Spring's website](https://spring.io/projects) includes documentation and examples for a wide range of features and libraries, and is a great place to start. Once you've decided on a library to use, the next step is finding its website and documentation. Most open-source libraries have extensive documentation that covers getting started, usage examples, and complete references. You can use these resources to implement your feature and debug issues along the way. Finally, if you encounter issues that documentation alone can't solve, you should search Google for to find similar issues and solutions others have encountered. # 04 Java Application Server {%youtube eggveTIXAx0%} A Java Application Server is a pluggable architecture that can host many deployed applications at once. It provides utilities like multi-threading, request filtering, and resource sharing to each application. Those applications must expose endpoints that handle the requests routed to them by the server. > The Structure of a Java Application Server ![](https://i.imgur.com/eOWZO8h.png) **Key Terms** * HTTP: Hypertext Transfer Protocol. A binary protocol that originally defined the mechanics of requesting and sending HTML over the internet. * Web Server: A program that listens for and responds to HTTP requests over the internet * Application Server: A program that hosts other applications, forwarding incoming requests to the appropriate application according to a filter. Provides shared access to resources and multi-threading. * Pluggable Architecture: A pluggable architecture refers to any piece of software that allows parts of it to be added, replaced, and removed. Usually, this is achieved through a common interface for every "pluggable" component. Sometimes the architecture can even replace components at runtime, as is the case with Servlets in an Application Server. * Threads/Threading: These terms come from concurrent programming - a thread is essentially one track of computation, and multi-threading is running multiple threads in parallel. This gets a little complicated because your CPU has a limited number of physical cores that can process instructions in parallel, while the number of threads you can have can be many more than your computer has cores, but that's a topic for another time! **Further Research** * Oracle documentation for [Java EE Containers/Servers](https://javaee.github.io/tutorial/overview005.html#BNABO). # 06 Java Servlets {%youtube DNZVE0NJlZ0%} The `Servlet` class is the main connection between the apps you develop and the application server they run on. By extending `Servlet`, you can create endpoints that handle incoming requests in a way specific to your application needs, and you can map specific request URLs to specialized servlets by adding entries to a `web.xml` file. The app server uses this configuration to instantiate and manage your servlets. It interacts with each through three standard methods, `init`, `service`, and `destroy`: * `service` is where requests are handled, and the server will call this method when a request is routed to the servlet it's called on. * `init` is where initialization of the servlet is handled, and the server will call this method directly after instantiating the servlet. * `destroy` is where servlet resource cleanup is handled, and is called directly before the server terminates the servlet instance. ![](https://i.imgur.com/3CTx5HP.png) **A quick note on Java Application Files:** When you compile a Java program and package it to be run, the Java compiler creates what is called a Java ARchive, or JAR file. This file contains a compressed file hierarchy, with folders that represent Java packages that contain Java `.class` files, which are the compiled versions of `.java` source code files. It can also contain arbitrary resource files, either at the root level or deeply nested in the package hierarchy. These files often contain metadata related to the app or library contained in the JAR file, which can be read by any program that interacts with the JAR. When you want to deploy an app to an app server, you have to package it as a Web application ARchive, or WAR file. A WAR file is almost identical to a JAR file, but includes configuration files specific to web applications. When we copy a WAR file into the deployment directory of an app server, the server unpackages it, looks for a `web.xml` file, and uses that file to find the classes and resources required by the application. This uses advanced Java features like reflection and class loading to programmatically load Java class definitions and instantiate them which is quite a nifty trick! It allows us to dynamically load, start, stop, and replace any number of applications in a web server at any time. **Key Terms** * Endpoints: An endpoint is the address at which a client can reach a specific part of a server's functionality. Usually, this is a URL path, the /words/and/slashes that follow the domain of a URL, like .com or .org. * Servlet: A class defined as a part of the Java: Enterprise Edition specification. Provides an implementable interface for web server request processing, defining a service method that the server invokes on an instantiated servlet to handle a ServletRequest and ServletResponse object for an incoming request. The servlet also defines lifecycle methods for the server to invoke when initializing or destroying a servlet. * JAR: A Java Archive file, which stores compiled .class files in a folder hierarchy that matches the code's package structure. Includes an optional manifest file. * WAR: A variation on the JAR for web applications, which optionally includes web resources like HTML files and configuration files like web.xml for servlet registration/mapping. **Further Research** * Official documentation of the `Servlet` [API](https://javaee.github.io/tutorial/servlets.html#BNAFD) * Official documentation for the [Java JAR API](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/jar/package-summary.html) * Official documentation for [packaging WAR files](https://javaee.github.io/tutorial/packaging003.html#BCGHAHGD) # 08 Spring Applications {%youtube Cla07Uh3Ctc%} Spring is an application framework, which means that instead of choosing when to invoke it from your application, you choose when it invokes your application code. This pattern of software development is called Inversion of Control (IoC), and it's powerful because it allows developers to develop specialized application components and use Spring to connect them with each other using dependency injection. This is good for clean, separated code and for code reuse. This is evident when looking at the vast number of Spring modules and Spring-integrated third-party tools that are available. This course focuses on a few of them: * Spring MVC, a generic web controller library for Spring that supports a wide variety of utilities to simplify the handling of HTTP requests * Thymeleaf, a third party template engine that can integrate with Spring MVC to simplify the generation of web pages as responses to HTTP requests * Spring Security, a generic authentication library for Spring that can integrate with many different credential sources and authentication protocols to automatically manage request authentication and security contexts * MyBatis, a third-party database access library that provides simple SQL/Java mapping tools that can be defined in Spring components **The End of Boilerplate: Spring Boot** So Spring adds a lot of features, but it still sounds like a lot of configuration. We still have to deploy it to an application server, right? And we still have to create a servlet for Spring to live in. It also sounds like getting all of these modules and utilities to work together might take some work. In the past, Spring did require a lot of configuration, but over time, the development world has moved towards a convention-over-configuration approach. Spring Boot is a project that provides an a-la-cart Spring experience, complete with a web page for generating and downloading starter projects based on the application needs. Most Spring Boot applications today also contain an embedded application server with a default, pre-configured servlet definition. All you have to do to run your Spring-enabled code as a server is to run a main method. With the rise of containerized architectures like Docker, this style of application development has become as popular as the pluggable application server, and in this course, we'll be exclusively using this mode. However, if you do want to deploy your Spring Boot application to a traditional application server, there are built-in tools that allow you to package the application as a standard WAR file. **Key Terms** * IoC: Inversion of Control, which is the practice of designing libraries as application runners. This allows developers to focus on application-specific logic and rely on IoC containers to connect application components with one another, eliminating a lot of boilerplate and encouraging a clean separation of development concerns. **Further Research** * Inversion of Control still seem a little hard to conceptualize? [Watch this video](https://www.youtube.com/watch?v=vFzP2SaMyA0) from Udacity for a dead-simple explanation of the basics. * Official Spring framework [website](https://spring.io/). * An [article](https://www.martinfowler.com/articles/injection.html) about Inversion of Control by Martin Fowler from the beginning of the pattern's popularity. # 10 Exercise: Spring Application For this exercise, we’ll download a Spring starter project and open it in our development environment. This project is quite small, but has some useful artifacts we’ll explore in the next lesson. To start, we’ll use a tool to generate our starter project. Visit the site: [start.spring.io](https://start.spring.io/) This site allows us to specify the dependencies and metadata for our Spring project and then generates the whole project as a downloadable zip. Follow the instructions in the task list below to download your starter project and open it IntelliJ IDEA. # 11 Solution: Spring Applications {%youtube UoiFv7915QQ%} **Spring Initializr** This is a helpful page for generating our starter projects. Here’s an example of the configuration for a simple starter project using Spring Web: >Example Spring Initializr Configuration ![](https://i.imgur.com/0ATudND.png) Once you’ve generated the starter project, open it in IntelliJ using the File menu and selecting Open. You can open a directory and IntelliJ will create a new project and import your dependencies. Navigate to the package `src/main/java/com.udacity.jdnd` and find the `Course1Application.java` class. This is the main class that launches the Spring Boot application. You can run it by simply right clicking on it and choosing “Run Course1Application.java”. # 12 Spring Starter Packs **{%youtube vhDtf0kxPU4%} Spring Starter Packs Setup** Spring is a collection of open-source libraries that solve common web development problems. But how do we get those libraries? In this course, we'll be using Maven, a dependency management tool that lets us define dependencies on open-source libraries based on their names and version numbers. We define those in a file in our projects called `pom.xml`, which Maven reads and uses to download the required libraries. We can also have our projects inherit dependencies from some base project, which is a feature that Spring Boot uses to make setting up a new Spring project easy as pie. We'll be using Spring Initializr, an online project generator, to choose specific Spring dependencies to add to new Spring projects. {%youtube aN6k4UV-qWw%} Spring Boot is best experienced with the help of Spring Initializr, an official project generator. You can use it to configure metadata and build properties of a project as well as what starter dependencies you want to include. These include: * Spring Dev Tools: utilities including hot reloading changed code into a running application * Spring MVC: web layer utilities that make developing server-side web apps easy * Spring Data: a common interface for many different types of database access * And many more Once you've selected your dependencies and chosen your language, build tool, and project identifiers, Spring Initializr will generate a zip file that includes a ready-to-run server with all of the choices you made reflected in its pom.xml file, as well as the package structure. **Key Terms** * Maven: A dependency management system and project build tool for Java. Provides a standardized way to define dependencies between projects and include them in the project build path. * POM: The Project Object Model that Maven uses to represent the dependency and build configuration of a project. Usually, this refers to the pom.xml configuration file found in a Maven project. * Dependency Management System: Any tool that automates the downloading and linking of external packages to a software development project. Most languages these days either provide one officially or have a community-accepted standard. **Additional Resources** * Official Spring project generator: Spring Initializr # 14 Exercise:Sring Starter Packs Exercise: Spring Starter Pack We created a new project with the Spring Web dependency, but after we’ve started using it we realized that we also need to add the dependency for Thymeleaf! Below, you’ll be shown a `pom.xml` file in a Udacity workspace. **Update the following file to include the Thymeleaf dependency so your project can import the libraries it needs.** ***If You Want to Do This Exercise On Your Machine*** Remember, when you're developing locally, you can generate sample projects with the Spring Initializr and then use the Explore button to view their `pom.xml`. This could also be helpful if you want to see how another dependency is added to your project. # 15 Solution: Spring Starter Packs {%youtube yevgULcdHmk%} You can look up the values for new dependencies by adding them to a new project in Spring Initializr and then clicking the ‘Explore’ button to browse the pom. You can also add dependency elements manually, and IntelliJ will try to find and suggest artifacts that match your entries. >IntelliJ Suggesting Artifacts When Adding a Dependency to `pom.xml` ![](https://i.imgur.com/1l0TSO5.png) Here’s an example `pom.xml` that includes our new dependency: ```xml <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.udacity.jdnd</groupId> <artifactId>course1</artifactId> <version>0.0.1-SNAPSHOT</version> <name>course1</name> <description>My Super Cool Project</description> <properties> <java.version>14</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` # 16 Edge Case: When You Can't Use Spring Boot Consider the following scenarios and decide if you can use Spring Boot in each of them. Mark each scenario where Spring Boot is a viable choice. [X] A project that already uses Spring [X] A project that uses Java EE Enterprise Java Beans and JNDI [O] A project that uses Oracle WebLogic as an Application Server. [O] A project that uses plain Servlets to handle request. {%youtube 274bwKHmqzI%} Spring Boot is great, but sometimes you’ll have to configure Spring manually or work in an environment where Spring is not available. Which of the following scenarios might result in a configuration that doesn’t use Spring Boot? [O] This project uses Java EE instead of Spring. [X] This project that needs to work with a legacy database. [O] This project utilizes many features specific to one application server in particular. Sometimes, it's not an option to use Spring Boot in a project. Usually, this is because some form of IoC has already been implemented, or it would take a lot of time to rewrite the code to use Spring Boot. Sometimes, though, it's worth adding Spring or Spring Boot to a project by refactoring the code and adding the Spring Servlet manually. More information on this can be found in the Further Research section, but this won't be a focus for the course - just remember that it takes a decision and some setup to use Spring in an application, and not all applications do! **Further Research** * [Official Spring Boot Documentation for deploying as a WAR file](https://docs.spring.io/spring-boot/docs/1.2.0.M2/reference/html/howto-traditional-deployment.html) # 17 Final Review Final Review Exercise Each lesson in this course, you will build on a single project, adding more features as we learn about them. For this lesson, you need to set that project up! Create a spring starter project with the dependencies used in this course, and verify the program runs successfully. * Go to Spring Initializr and add the following starter dependencies. * Spring Boot DevTools * Spring Web * Thymeleaf * Spring Security * H2 Database * MyBatis Framwork * Make sure the metadata is set coreectly. * It's configured as a Maven project * It's configured to use Java * The group id is set to `review` * The packaging is set to `JAR` * The packageing is set to `JAR` * The java version is 14. * Download the project somewhere you wont't forget it! * Open the project in Intellij * Run the main application class and verify that it runs without errors. # 18 Solution: Final Review **Solution: Final Review** If you're having trouble completing this, refer back to the screencasts for Spring Starter Packs and make sure you re-read the instructions carefully. When you generate the project, check the POM file and make sure that it has the correct dependencies and metadata listed in the instructions. [You can compare your solution against mine here.](https://github.com/udacity/nd035-c1-spring-boot-basics-examples/tree/master/udacity-jwdnd-c1-l1-final-review-solution-master) **Glossary** * HTTP Request/Response: HTTP, or HyperTextTransferProtocol, is a binary data format for communication between programs over the web. It can be broken down into two basic message types: requests and responses. Clients send requests for resources to servers, which respond with the requested data. [Read more about the protocol here.](https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages) * HTTP `GET` and `POST`: Every HTTP request has an important header that determines its method. `GET` and `POST` are two of the most common; `GET` indicates a request for data from the server, and `POST` represents a request to "post" new data to the server - this usually represents some action on server data like submitting search terms, posting an update, or adding new data to the server. * HTTP: Hypertext Transfer Protocol. A binary protocol that originally defined the mechanics of requesting and sending HTML over the internet. * Web Server: A program that listens for and responds to HTTP requests over the internet * Application Server: A program that hosts other applications, forwarding incoming requests to the appropriate application according to a filter. Provides shared access to resources and multi-threading. * Pluggable Architecture: A pluggable architecture refers to any piece of software that allows parts of it to be added, replaced, and removed. Usually, this is achieved through a common interface for every "pluggable" component. Sometimes the architecture can even replace components at runtime, as is the case with Servlets in an Application Server. * Threads/Threading: These terms come from concurrent programming - a thread is essentially one track of computation, and multi-threading is running multiple threads in parallel. This gets a little complicated because your CPU have a limited number of physical cores that can process instructions in parallel, while the number of thread you can have can be many more than your computer has cores, but that's a topic for another time! * Endpoints: An endpoint is the address at which a client can reach a specific part of a server's functionality. Usually, this is a URL path, the `/words/and/slashes` that follow the domain of a URL, like `.com` or `.org`. * `Servlet`: A class defined as a part of the Java: Enterprise Edition specification. Provides an implementable interface for web server request processing, defining a `service` method that the server invokes on an instantiated servlet to handle a `ServletRequest` and `ServletResponse` object for an incoming request. The servlet also defines lifecycle methods for the server to invoke when initializing or destroying a servlet. * JAR: A Java Archive file, which stores compiled .class files in a folder hierarchy that matches the code's package structure. Includes an optional manifest file. * WAR: A variation on the JAR for web applications, which optionally includes web resources like HTML files and configuration files like `web.xml` for servlet registration/mapping. * IoC: Inversion of Control, which is the practice of designing libraries as application runners. This allows developers to focus on application-specific logic and rely on IoC containers to connect application components with one another, eliminating a lot of boilerplate and encouraging a clean separation of development concerns. * Maven: A dependency management system and project build tool for Java. Provides a standardized way to define dependencies between projects and include them in the project build path. * POM: The Project Object Model that Maven uses to represent the dependency and build configuration of a project. Usually, this refers to the pom.xml configuration file found in a Maven project. * Dependency Management System: Any tool that automates the downloading and linking of external packages to a software development project. Most languages these days either provide one officially or have a community-accepted standard. # 19 Lesson Conclusion {%youtube 3fwD0T38Ja0%} In this lesson, we learned about: * Web servers and how early servers were single-function programs that could host files, serve web pages, and expose databases to external connections. * Java application servers, which provide a pluggable architecture for applications to interface with, granting access to shared resources and multi-threaded request processing. * Spring framework, a family of libraries that build on the abstractions of the application server to support many third-party integrations to provide easy abstractions for common web development tasks. * Spring Boot, a convention-over-configuration approach to Spring app development that provides defaults for many Spring configuration options in order to provide a smoother development experience. * Spring Initializr, the official project generator for Spring Boot, which allows developers to specify an application's metadata and dependencies and receive a fully-configured Spring Boot project, ready for development. Next lesson, we'll take a look how Spring operates and how we can build many small application components and configure Spring to connect them to one another.