5

How to deploy a Java and React webapp in one JAR/WAR

 2 years ago
source link: https://marco.dev/deploy-java-react-one
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to deploy a Java and React webapp in one JAR/WAR


This project is the same as the Angular project described in this post How to deploy a Java and Angular webapp in one JAR/WAR

In your project you can deploy your React and Java application in the same artifact (.jar or .war) or in separate artifacts.

Here you can find the sources of the project on GitHub: https://github.com/marco76/java-react-basic

There is no best solution. You should adopt the architecture chosen by your team.

If frontend and backend teams are working independently, and the frontend team is using a monorepo, separate artifacts could have some advantages.

A quick (2 minutes) video tutorial is here, the video is based on the Angular project, but it applies for the React code too.

If you would like the video for React, simply leave a message or a comment.

One JAR with Spring Boot

Your project contains 3 modules, the parent and 2 children (frontend and backend).

In this example we use Spring Boot but you can use the same structure with other Java frameworks.

We are building a Spring fat jar that contains the backend and the frontend.

Here you can see how the project is structured:

structure.gif

The backend project artifact will contain the Java compiled classes and the React application:

backend.gif

To build and start the project locally:

 
git clone https://github.com/marco76/java-react-basic.git 
 
cd ./java-react-basic.git 
 
mvn clean package 
 
cd ./backend/target 
 
java -jar backend-0.1-SNAPSHOT.jar 

You should have the following result on http://localhost:8080

react-answer.gif

parent pom.xml

The parent pom.xml declares the 2 modules to build. frontend for React and backend for Java.

The 2 modules can be started separately during the development. The React app will use the port 3000, the Java application will use the port 8080.

<?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>dev.marco</groupId> 
    <artifactId>java-react-example</artifactId> 
    <packaging>pom</packaging> 
    <version>0.1-SNAPSHOT</version> 
    <parent> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-parent</artifactId> 
        <version>2.4.3</version> 
    </parent> 
    <modules> 
        <module>frontend</module> 
        <module>backend</module> 
    </modules> 
 
    <dependencies> 
        <dependency> 
            <groupId>org.springframework</groupId> 
            <artifactId>spring-context-support</artifactId> 
            <version>5.3.4</version> 
        </dependency> 
        <dependency> 
            <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-web</artifactId> 
            <version>2.4.3</version> 
        </dependency> 
    </dependencies> 
</project> 

Frontend pom.xml

The frontend module contains a standard React application.

During the development you can start the application with a standard npm start

The heavy lifting is done by the plugin https://github.com/eirslett/frontend-maven-plugin. This plugin download node, install the libraries and build the project.

The result is a jar file that contains the Angular application compiled.

<?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"> 
    <parent> 
        <groupId>dev.marco</groupId> 
        <artifactId>java-react-example</artifactId> 
        <version>0.1-SNAPSHOT</version> 
    </parent> 
    <modelVersion>4.0.0</modelVersion> 
    <artifactId>frontend</artifactId> 
    <packaging>jar</packaging> 
    <build> 
        <plugins> 
            <!-- clean the dist directory used by Angular --> 
            <plugin> 
                <artifactId>maven-clean-plugin</artifactId> 
                <version>3.1.0</version> 
                <configuration> 
                    <filesets> 
                        <fileset> 
                            <directory>dist</directory> 
                        </fileset> 
                    </filesets> 
                </configuration> 
            </plugin> 
 
            <plugin> 
                <groupId>com.github.eirslett</groupId> 
                <artifactId>frontend-maven-plugin</artifactId> 
                <version>1.11.2</version> 
 
                <executions> 
                    <!-- Install node and npm --> 
                    <execution> 
                        <id>Install Node and NPM</id> 
                        <goals> 
                            <goal>install-node-and-npm</goal> 
                        </goals> 
                        <configuration> 
                            <nodeVersion>v14.16.0</nodeVersion> 
                        </configuration> 
                    </execution> 
 
                    <!-- clean install --> 
                    <execution> 
                        <id>npm install</id> 
                        <goals> 
                            <goal>npm</goal> 
                        </goals> 
                    </execution> 
 
                    <!-- build app --> 
                    <execution> 
                        <id>npm run build</id> 
                        <goals> 
                            <goal>npm</goal> 
                        </goals> 
                        <configuration> 
                            <arguments>run build</arguments> 
                        </configuration> 
                    </execution> 
                </executions> 
            </plugin> 
        </plugins> 
 
        <resources> 
            <resource> 
                <!-- we copy the content of the frontend directory in the final artifact --> 
                <directory>build</directory> 
            </resource> 
        </resources> 
    </build> 
</project> 

The Java Backend pom.xml

You have to import the frontend module, the frontend code will be included in your final package.

There a dependency with the frontend module. This solution is not ideal because the backend module is not completely independent.

We use the maven-dependency-plugin to unpack the content of the frontend and copy the content in our backend artifact.

The Angular application is copied in the folder /classes/static, this folder is used to serve static content in Spring Boot.

<?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"> 
    <parent> 
        <groupId>dev.marco</groupId> 
        <artifactId>java-react-example</artifactId> 
        <version>0.1-SNAPSHOT</version> 
        <relativePath>../pom.xml</relativePath> 
    </parent> 
 
    <modelVersion>4.0.0</modelVersion> 
 
    <properties> 
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
        <project.build.outputEncoding>UTF-8</project.build.outputEncoding> 
    </properties> 
 
    <artifactId>backend</artifactId> 
 
    <dependencies> 
        <dependency> 
            <groupId>dev.marco</groupId> 
            <artifactId>frontend</artifactId> 
            <version>0.1-SNAPSHOT</version> 
            <type>jar</type> 
        </dependency> 
    </dependencies> 
 
    <build> 
        <plugins> 
            <plugin> 
                <groupId>org.springframework.boot</groupId> 
                <artifactId>spring-boot-maven-plugin</artifactId> 
                <version>2.4.3</version> 
                <configuration> 
                    <mainClass>dev.marco.example.springboot.Application</mainClass> 
                </configuration> 
                <executions> 
                    <execution> 
                        <goals> 
                            <goal>repackage</goal> 
                        </goals> 
                    </execution> 
                </executions> 
            </plugin> 
 
            <plugin> 
                <groupId>org.apache.maven.plugins</groupId> 
                <artifactId>maven-dependency-plugin</artifactId> 
                <version>3.1.2</version> 
                <executions> 
                    <execution> 
                        <id>merge</id> 
                        <phase>initialize</phase> 
                        <goals> 
                            <goal>unpack</goal> 
                        </goals> 
                        <configuration> 
                            <artifactItems> 
                                <artifactItem> 
                                    <groupId>dev.marco</groupId> 
                                    <artifactId>frontend</artifactId> 
                                    <type>jar</type> 
                                    <overWrite>true</overWrite> 
                                    <outputDirectory>${project.build.directory}/classes/static</outputDirectory> 
                                </artifactItem> 
                            </artifactItems> 
                        </configuration> 
                    </execution> 
                </executions> 
            </plugin> 
        </plugins> 
    </build> 
</project> 

Spring

In our example we added a REST controller to deploy and execute the basic application.

During the development phase we are starting the Spring backend application and the Angular application in separated instances.

To allow the communication between the HttpClient of Angular and the RestController of Spring we have to enable a Cross Origin Resource Sharing in Spring Boot or our requests will be refused.

@RestController 
// we allow localhost:3000 for testing purposes 
@CrossOrigin(origins = "http://localhost:3000") 
public class HelloController { 
 
    @RequestMapping(value = "/message", produces = MediaType.APPLICATION_JSON_VALUE) 
    public Map<String, String> index() { 
        return Collections.singletonMap("message", "Greetings from Spring Boot!"); 
    } 
 
} 

React

Our React application doesn't do anything special, we simply call the backend service, and we show the message received.

In this project we use TypeScript.

import React from 'react'; 
 
type MyProps = { }; 
type MyState = { data: string }; 
class HelloSpring extends React.Component<MyProps, MyState> { 
 
    constructor(props: any) { 
        super(props); 
 
        this.state = { data: ""} 
    } 
    componentDidMount() { 
        const apiURL = 'http://localhost:8080/message'; 
        fetch(apiURL) 
            .then((response) => response.json()) 
            .then((json) => { 
                this.setState({ 
                    data: json.message 
                }) 
            }) 
    } 
    render() { 
        return ( 
            <p> 
                <div> 
                    It worked, this is the message from the backend: <br/> 
        {this.state.data} 
        </div> 
        </p> 
    ) 
    } 
} 
 
export default HelloSpring; 

Deploy a WAR with Tomcat (still Angular version)

If you need to deploy a WAR using Tomcat you can use the following branch of the Angular project.

I didn't implement the solution for React yet but you can update the previous project following the instructions.

https://github.com/marco76/java-angular-basic/tree/feature/war-for-tomcat

You need to

  1. mvn clean package

  2. In backend there will be a file: angular-spring-example.war

  3. Deploy the file, it should be visible under: localhost:8080/angular-spring-example, if you want to run it as / you have to rename it in ROOT before the deployment.

Major changes in relation to the JAR version:

backend/pom.xml

We change the type of packaging and we add a dependency to spring-boot-starter-tomcat

<packaging>war</packaging> 
 
<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-tomcat</artifactId> 
<scope>provided</scope> 
</dependency> 

backend/src/main/java/dev/marco/example/springboot/Application.java

@SpringBootApplication 
// we extend SpringBootServletInitializer 
    public class Application extends SpringBootServletInitializer { 

Bonus: features showcase

To the original minimalistic example I started to add some features. I think the example project is more interesting as showcase than as 'bootstrap'.

I added OpenAPI with SpringDocs, when you start the project is available here: http://localhost:8080/swagger-ui

I added some tests to show the difference between RestTemplateTest and MockMvc.

I planned to add other features like WebSockets, Spring Data and Spring Security.

If you are interested to see how some features are implemented you can leave a comment or send me a message.

Request a feature

You can contact me or fill a feature request if you would like to see a feature included in this showcase.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK