female software engineer coding on computer

Full-Stack Web Application, JavaScript and Spring Boot

Introduction

The full-stack web application is a website that is divided into two types of applications, such as front-end and back-end applications. these applications interact and working together to run the whole full-stack web application.

And also if you want more information about full-stack application, click the link below:

http://lgeratech.com/2019/11/what-is-a-full-stack-developer/

In this tutorial, we are going to build a full-stack web application with JavaScript And Spring Boot. Additionally, the creation of front-end and back-end application are separated in other posts. In order to work the full-stack application properly, we should follow the tutorials and configuration setup.

Application walk-through

The application is base on the online shopping app, which will do the basic operations for products like Create-Read-Update-Delete(CRUD) operations.

See the video below for the full-stack web application demo:

Back-end tutorial

To skip this tutorial, proceed to the next section Back-end Setup.

Back-end application is the core part of the full-stack web or mobile application.

It contains the logical and functional algorithm of the application. However, you can only access this application using client-side or front-end applications or through client APIs, including postman or curl.

Click the link below for the back-end tutorial:

Back-end Setup

The challenging part of this tutorial is the back-end application. In order to run the back-end successfully, you should install and setup the environment for back-end application.

The back-end was written in Java and Spring Boot framework, therefore, we need to install JDK and Maven to build and run the application.

JDK and Maven Setup

Skip this section if you already have JDK and Maven.

First and most important is the JDK, to download the JDK navigate to this link: https://www.oracle.com/ph/java/technologies/javase-downloads.html

And for the Maven, visit its official site to download and install it: https://maven.apache.org/

And also, here are the other tips for JDK and Maven environment set-up: https://maven.apache.org/install.html#windows-tips

Downloading Back-end application

Once you’ve done the environment setup, you can now download the back-end application in github repository.

You can choose whether to download or clone the project directly to your local.

In order to download the source code, click the link below to navigate to the github repository: https://github.com/LeoBernabe/product-service-v1

Or, on the other hand, clone the repository to using this link: https://github.com/LeoBernabe/product-service-v1.git

Once you’ve done the downloading the back-end application, you can now try to run the it.

First, CD to the project folder:

cd product-service-v1

Then run the application using this command:

mvn spring-boot:run.

Back-end configuration (Enabling CORS)

In this section, we are going to modify the security access of the back-end application. In other words, the purpose of this modification is to allow front-end or other anonymous apps to access the back-end application. And also, to run the back-end functions, including HTTP requests for CRUD operations.

Here is the step to modify the back-end application:

Open the project or source code on any editors or IDEs like Eclipse, IntelliJ, VS Code, etc..

Once the project is opened, go to src/main/java/com/lgeratech/productservice or com.lgeratech.productservice package and add new java file, CorsConfiguration.java, then copy-paste the code below:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class CorsConfiguration implements WebMvcConfigurer
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("POST", "GET", "DELETE", "PUT");
    }
}

As you can see, we’ve overridden the implementation for the addCorsMappings method to enable cross-origin resource sharing (CORS). Therefore, it enables the front-end application to access resources, such as HTTP requests which are defined on allowedMethods.

Alright, we’ve done the back-end application setup. Before we test the application, make sure you’ve restarted it, to reflect the changes we’ve done for CORS.

Test the back-end HTTP request

As of now to ensure if the back-end is working, we can use any client APIs. I recommend postman or curl.

Find the list of URLs below for the following HTTP requests:

GET Request:

localhost:8080/retrieveProducts

POST Request:

localhost:8080/createProduct

PUT Request:

localhost:8080/updateProduct

DELETE Request:

localhost:8080/deleteProduct/1

Front-end tutorial

The Front-end or also known as client-side is referring to operations where an end-user can perform software transactions. Front-end developer focuses on User Interface (UI) and User Experience (UX) design creation to meet the user’s requirements. Click the link below for more info:

You can also find the resources and source code, here at Github repository: https://github.com/LeoBernabe/shopping-app-frontend-js

Modify the request URLs

Once you have the source code, you will notice in the productService.js file that the URLs used in the last tutorial are different compared to the URLs we defined in the back-end application.

In this section, we will integrate and change the URLs to back-end HTTP request URLs in the front-end application.

GET all products request

Change the GET request from localhost:3000/products to localhost:8080/retrieveProducts:

async function loadProduct(){
    let response = await fetch('http://localhost:3000/products');
    if (response.ok) { 
        let products = await response.json();
        productContainer.innerHTML = '';
        products.forEach(product => 
            productContainer.appendChild(parseProduct(product)));
    } else {
        alert("HTTP GET Request Error: " + response.status);
    }
};
Add product request

Change the POST request from localhost:3000/products to localhost:8080/createProduct:

async function saveProduct(productForm){
    let response = await fetch('http://localhost:8080/createProduct', {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json'
        },
        body: JSON.stringify(Object.fromEntries(new FormData(productForm)))
      });
      if(response.ok){
          loadProduct();
          alert('Product has been added successfully!');
          openModal(false);
      } else {
          alert("HTTP-Error: " + response.status);
      }
}
Update product request

Change the PUT request from localhost:3000/products/{id} to localhost:8080/updateProduct:

async function updateProduct(id, productForm){
    let response = await fetch(`http://localhost:8080/updateProduct`, {
        method: 'PUT',
        headers: {
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            ...Object.fromEntries(new FormData(productForm)),
            productId: id
        })
      });
      if(response.ok){
          alert('Product has been updated successfully!');
          loadProduct();
          window.location.href = window.location.href.split('?')[0];
      } else {
          alert("HTTP-Error: " + response.status);
      }
}
Delete product request

Change the PUT request from localhost:3000/products/{id} to http://localhost:8080/deleteProduct/${id}:

async function deleteProduct(id){
    let response = await fetch(`http://localhost:8080/deleteProduct/${id}`, {
        method: 'DELETE'
      });
      if(response.ok){
          loadProduct();
          alert('Product has been deleted successfully!');
      } else {
          alert("HTTP-Error: " + response.status);
      }
}
Get product request

Change the GET request from localhost:3000/products/{id} to http://localhost:8080/product/${id}:

async function getProduct(id){
    let response = await fetch( `http://localhost:3000/product/${id}`);
    if (response.ok) { 
       return await response.json();
    } else {
        alert("HTTP-Error: " + response.status);
        return null;
    }
};

Test the full-stack application

Once you’ve completed the front-end modification, we can now proceed in testing.

Make sure the back-end is running, then open the front-end application in the browser. I recommend google chrome to ensure it will work properly.

If you encountered a CORS error when you check the devTools, go back to the previous section Back-end configuration (Enabling CORS) to enable the CORS in back-end application.

Conclusion

Congratulations! we have done creating a Full-Stack Web Application with JavaScript And Spring Boot.

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

BCF Theme By aThemeArt - Proudly powered by WordPress.
BACK TO TOP