How to develop a Single Page Application (SPA) with Micronaut.

Single Page application is the frontend concept and there are supported frameworks for this such as react and angular. In this article, we will try to develop SPA with micronaut. Micronaut surely helps us develop the REST layer and the REST endpoints consumed by our frontend application.

micronaut
micronaut framework

Tech Stack:

  • Micronaut
  • Java1.8 and higher version.
  • Maven/ gradle
  • Tomcat embed 9.0.14
  • Visual studio code
  • TypeScript
  • Angular

Let us jump and start code. First we will create some controller which is handling the incoming request. If you are new to micronaut then please use below link to get started.

https://www.techwasti.com/dockerise-micronaut-application/

Server:

Before that create one folder with SPADemoEx and inside that create the micronaut application using the micronaut launch option similar like spring start website.

https://micronaut.io/launch/

Let us create simple HelloWorldController.

import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;


@Controller
public class HelloController {
    @Produces(MediaType.TEXT_PLAIN)
    @Get("/{name}")
    HttpResponse<String> hello(String name) {
        return HttpResponse.ok("Hello, " + name + "!");
    }
}

This controller takes name as input and greet that use with hello message.

Now if you go and check the Application.java code which is like this:

import io.micronaut.runtime.Micronaut;

public class Application {

    public static void main(String[] args) {
        Micronaut.run(Application.class, args);
    }
}

This is our server code, now let us validate by running the code.

$ cd server

$ ./gradlew run

Then visit the url http://localhost:8080/Maheshwar and you will get below output on your browser.

Hello, Maheshwar!

Client:

Now let us create first react application by using following command.

$ npx create-react-app client

This is creating the client as react application.

After creating the project your directory structure would be look like below:

When we create the react application the application js file is App.js.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import {SERVER_URL} from "./config";

class App extends Component {

  //<1>
  state = {
    name: 'World',
    message: null
  };

  //<2>
  setName = e => this.setState({name: e.target.value});

  //<3>
  getMessage = e => {
    e.preventDefault();
    fetch(`${SERVER_URL}/${this.state.name}`)
        .then(r => r.text())
        .then(message => this.setState({message}))
        .catch(e => console.error(e))
  };

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          {/* <4> */}
          <form onSubmit={this.getMessage}>
            <label>Enter your name: </label>
            <input type="text" value={this.state.name} onChange={this.setName} />
            <input type="submit" value="Submit" />
          </form>

          {/* <5> */}
          <p>
            { this.state.message ?
                <strong>{this.state.message}</strong> :
                <span>Edit <code>src/App.js</code> and save to reload.</span>
            }
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

The above code snippet where in the 1st section we have to defining the initial state and then method code snippet to make API call and get result and then bind that result to UI. When binding to the UI means update the state of that component.

Note:- Java application will be on 8080 port and react client application is on 3000 port.

When you run the client application using below command

$ npm start

and visit localhost:3000

Conclusion:

In this article we just created the HelloWorldController and it is taking name as input and returning the greet message as a JSON output and we are UI layer as react app which is consumer of this REST API and showcasing the result on UI. Here I don’t know much about react so haven’t discussed much just now to create app and so some cosmetic changes. For this example I took complete help from micronaut documentation. Please if you tried something new feel free to share with me.