Servlet technology

Introduction and installation

Installing Apache Maven
Download from https://maven.apache.org/install.html
Add the bin directory of the created directory apache-maven-3.6.3 to the PATH environment variable

Maven’s Objectives

  1. Making the build process easy
  2. Providing a uniform build system
  3. Providing quality project information
  4. Providing guidelines for best practices development
  5. Allowing transparent migration to new features


web project from Maven Template

syntax mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId={maven-template} -DinteractiveMode=false
mvn archetype:generate -DgroupId=am.egs -DartifactId=java-web-project -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false


Maven POM.xml example

pom.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>am.developer.lesson.maven</groupId>
  <artifactId>MavenServletGetPost</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <finalName>${project.name}-byHayk</finalName>
  </build>

</project>


 


Our exampe from gitlab

 git clone https://gitlab.com/developer.armenia/mavenservlet_getpost

How to run

mvn package
mvn jetty:run


Maven defines 4 items of a build process

  • Lifecycle Three built-in lifecycles (aka build lifecycles): default, clean, site
  • Phase Each lifecycle is made up of phases, e.g. for the default lifecycle: compile, test, package, install, etc.
  • Plugin An artifact that provides one or more goals
  • Goal The task (action) that is executed. A plugin can have one or more goals.


Maven Phases / Lifecycle

most common default lifecycle phases.

  • validate validate the project is correct and all necessary information is available
  • compile compile the source code of the project
  • test test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package take the compiled code and package it in its distributable format, such as a JAR.
  • verify run any checks to verify the package is valid and meets quality criteria
  • install install the package into the local repository, for use as a dependency in other projects locally
  • deploy done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects

example
mvn package -DskipTests

There are two other Maven lifecycles of note beyond the default list above. They are

  • clean cleans up artifacts created by prior builds
  • site generates site documentation for this project


Goal

Plugins are artifacts that provide goals to Maven. Furthermore, a plugin may have one or more goals wherein each goal represents a capability of that plugin. For example, the Compiler plugin has two goals: compile and testCompile


  • compiler:compile the compile goal from the compiler plugin is bound to the compile phase
  • compiler:testCompile is bound to the test-compile phase
  • surefire:testis bound to test phase
  • install:install is bound to install phase

example
mvn help:describe -Dcmd=compile

Maven Plugin

Maven is actually a plugin execution framework where every task is actually done by plugins. Maven Plugins are generally used to

  • create jar file
  • create war file
  • compile code files
  • unit testing of code
  • create project documentation
  • create project reports


example

 
<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>
 
  


Maven Plugin examples

Always add maven-help-plugin to display the active profile during the compile or package phase, it will save you a lot of debugging time.


 
<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-help-plugin</artifactId>
        <version>3.1.0</version>
        <executions>
			<execution>
				<id>show_profiles</id>
				<phase>compile</phase>
				<goals>
					<goal>active-profiles</goal>
				</goals>
			</execution>
        </executions>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>
 
  

Maven Project Structure

Introduction to the Standard Directory Layout
https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

src/main/javaApplication/Library sources
src/main/resourcesApplication/Library resources
src/main/filtersResource filter files
src/main/webappWeb application sources
src/test/javaTest sources
src/test/resourcesTest resources
src/test/filtersTest resource filter files


Introduction to the POM

A Project Object Model or POM is the fundamental unit of work in Maven

  • It is an XML file that contains information about the project and configuration details used by Maven to build the project.
  • It contains default values for most projects. Examples for this is the build directory, which is target; the source directory
  • which is src/main/java; the test source directory
  • which is src/test/java; and so on
  • When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal.
  • Some of the configuration that can be specified in the POM are the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. Other information such as the project version, description, developers, mailing lists and such can also be specified

Dependency Management

The second core feature of Maven is dependency management. A dependency is an artifact that a software application requires — either at compile-time or at run-time. For simple applications, we can manually manage dependencies, such as by adding a JAR to the classpath during compilation. As the scale of an application grows, though, manual management becomes unruly.

Not only are we responsible for managing the direct dependencies that our project has, but we are also responsible for handling the transitive dependencies — i.e., the dependencies of our dependencies. Adding a single dependency to our project can mean that we have to manage ten more dependencies that our dependency requires, and possibly dozens more that each of these transitive dependencies in-turn require.


Declaring Dependencies

Instead of managing this dependency tree manually, we can use Maven to automatically resolve and download our dependencies for us, ensuring that they are compiled and linked correctly so that our application can execute at run-time. To do this, we must declare our dependencies in our POM under the dependencies element:


 <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>am.developer.lesson.maven</groupId>
  <artifactId>MavenServletGetPost</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <finalName>${project.name}-byHayk</finalName>
  </build>

<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
      </dependency>
</dependencyManagement>

</project>
  

Scope

defines when the dependency should be used (i.e., included on the classpath)

  • compile This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
  • provided This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.
  • runtime This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath. .
  • test This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases. This scope is not transitive
  • system This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.
  • import (only available in Maven 2.0.9 or later) This scope is only supported on a dependency of type pom in the section. It indicates the dependency to be replaced with the effective list of dependencies in the specified POM’s section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

 <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>am.developer.lesson.maven</groupId>
  <artifactId>MavenServletGetPost</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <finalName>${project.name}-byHayk</finalName>
  </build>

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.20</version>
        <scope>provided</scope>
      </dependency>


</project>
  

Repositories

With our dependencies declared, Maven can now resolve each dependency into a suitable binary and using this binary to compile and link the necessary bytecode to our application. To do this, Maven looks at a repository or set of repositories for an appropriate binary and downloads the binary.

  • Local It's in your local machine folder , by default .m2 folder in user folder
  • Central for example http://repo.maven.apache.org/maven2/
  • Remote Repository accessed by a variety of protocols such as file:// and https:// . These repositories might be a truly remote repository set up by a third party to provide their artifacts for downloading

Maven Dependency Search Sequence

When we execute Maven build commands, Maven starts looking for dependency libraries in the following sequence

  • Step 1 Search dependency in local repository, if not found, move to step 2 else perform the further processing.
  • Step 2 Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4. Else it is downloaded to local repository for future reference.
  • Step 3 If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency).
  • Step 4 Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference. Otherwise, Maven stops processing and throws error (Unable to find dependency).

  • Build Profile

    A Build profile is a set of configuration values, which can be used to set or override default values of Maven build. Using a build profile, you can customize build for different environments such as Production v/s Development environments.

    
     <profiles>
            <profile>
    			<id>skiptest</id>
    			<properties>
    				<maven.test.skip>true</maven.test.skip>
    			</properties>
    		</profile>
        </profiles>
       

    Run
    $ mvn package -Pskiptest