Example project showing how to build a Spring Boot App providing a GUI with Vue.js
1.9K
If you´re a JavaMagazin / blog.codecentric.de / Softwerker reader, consider switching to vue-cli-v2-webpack-v3

A live deployment is available on Heroku: https://spring-boot-vuejs.herokuapp.com
This project is used as example in a variety of articles & as eBook:
blog.codecentric.de/en/2018/04/spring-boot-vuejs | JavaMagazin 8.2018 | entwickler.press shortcuts 229 | softwerker Vol.12
Get newest node & npm:
brew upgrade node
npm install -g npm@latest
Update vue-cli
npm install -g @vue/cli
Update Vue components/plugins (see https://cli.vuejs.org/migrating-from-v3/#upgrade-all-plugins-at-once)
vue upgrade
Well, I’m not a Frontend developer. I’m more like playing around with Spring Boot, Web- & Microservices & Docker, automating things with Ansible and Docker, Scaling things with Spring Cloud, Docker Compose, and Traefik... And the only GUIs I’m building are the "new JS framework in town"-app every two years... :) So the last one was Angular 1 - and it felt, as it was a good choice! I loved the coding experience and after a day of training, I felt able to write awesome Frontends...
But now we’re 2 years later and I heard from afar, that there was a complete rewrite of Angular (2), a new kid in town from Facebook (React) and lots of ES201x stuff and dependency managers like bower and Co. So I’m now in the new 2-year-cycle of trying to cope up again - and so glad I found this article: https://medium.com/reverdev/why-we-moved-from-angular-2-to-vue-js-and-why-we-didnt-choose-react-ef807d9f4163
Key points are:

And the introduction phrase sounds really great:
Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only and is very easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.
So I think, it could be a good idea to invest a day or so into Vue.js. Let’s have a look here!
brew install node
npm install -g @vue/cli
sudo apt update
sudo apt install node
npm install -g @vue/cli
choco install npm
npm install -g @vue/cli
spring-boot-vuejs
├─┬ backend → backend module with Spring Boot code
│ ├── src
│ └── pom.xml
├─┬ frontend → frontend module with Vue.js code
│ ├── src
│ └── pom.xml
└── pom.xml → Maven parent pom managing both modules
Go to https://start.spring.io/ and initialize a Spring Boot app with Web and Actuator. Place the zip’s contents in the backend folder.
Customize pom to copy content from Frontend for serving it later with the embedded Tomcat:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy Vue.js frontend content</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources/public</outputDirectory>
<overwrite>true</overwrite>
<resources>
<resource>
<directory>${project.parent.basedir}/frontend/target/dist</directory>
<includes>
<include>static/</include>
<include>index.html</include>
<include>favicon.ico</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Creating our frontend project is done by the slightly changed (we use --no-git here, because our parent project is already a git repository and otherwise vue CLI 3 would initialize an new one):
vue create frontend --no-git
see https://cli.vuejs.org/guide/
This will initialize a project skeleton for Vue.js in /frontend directory - it, therefore, asks some questions in the cli:

Do not choose the default preset with default (babel, eslint), because we need some more plugins for our project here (choose the Plugins with the space bar):

You can now also use the new vue ui command/feature to configure your project:

If you want to learn more about installing Vue.js, head over to the docs: https://vuejs.org/v2/guide/installation.html
If you’re a backend dev like me, this Maven plugin here https://github.com/eirslett/frontend-maven-plugin is a great help for you - because, if you know Maven, that’s everything you need! Just add this plugin to the frontend’s pom.xml:
<build>
<plugins>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>${frontend-maven-plugin.version}</version>
<executions>
<!-- Install our node and npm version to run npm/node scripts-->
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<nodeVersion>v10.10.0</nodeVersion>
</configuration>
</execution>
<!-- Install all project dependencies -->
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<!-- optional: default phase is "generate-resources" -->
<phase>generate-resources</phase>
<!-- Optional configuration which provides for running any npm command -->
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<!-- Build and minify static files -->
<execution>
<id>npm run build</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>run build</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Commonly, node projects will create a dist/ directory for builds which contains the minified source code of the web app - but we want it all in /target. Therefore we need to create the optional vue.config.js and configure the outputDir and assetsDir correctly:
module.exports = {
...
// Change build paths to make them Maven compatible
// see https://cli.vuejs.org/config/
outputDir;: 'target/dist',
assetsDir;: 'static';
}
Inside the root directory, do a:
mvn clean install
Run our complete Spring Boot App:
mvn --projects backend spring-boot:run
Now go to http://localhost:8098/ and have a look at your first Vue.js Spring Boot App.
The webpack-dev-server, which will update and build every change through all the parts of the JavaScript build-chain, is pre-configured in Vue.js out-of-the-box! So the only thing needed to get fast feedback development-cycle is to cd into frontend and run:
npm run serve
That’s it!
Install vue-devtools Browser extension https://github.com/vuejs/vue-devtools and get better feedback, e.g. in Chrome:

There's a blog post: https://blog.jetbrains.com/webstorm/2018/01/working-with-vue-js-in-webstorm/
Especially the New... Vue Component looks quite cool :)
Prior to Vue 2.0, there was a build in solution (vue-resource). But from 2.0 on, 3rd party libraries are necessary. One of them is Axios - also see blog post https://alligator.io/vuejs/rest-api-axios/
npm install axios --save
Calling a REST service with Axios is simple. Go into the script area of your component, e.g. Hello.vue and add:
import axios from 'axios'
data ();{
return {
response: [],
errors: []
}
},
callRestService ();{
axios.get(`api/hello`)
.then(response => {
// JSON responses are automatically parsed.
this.response = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
In your template area you can now request a service call via calling callRestService() method and access response data:
<button class=”Search__button” @click="callRestService()">CALL Spring Boot REST backend service</button>
<h3>{{ response }}</h3>
Single-Origin Policy (SOP) could be a problem if we want to develop our app. Because the webpack-dev-server runs on http://localhost:8080 and our Spring Boot REST backend on http://localhost:8098.
We need to use Cross-Origin Resource Sharing Protocol (CORS) to handle that (read more background info about CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
Create a central Axios configuration file called http-commons.js:
import axios from 'axios'
export const AXIOS = axios.create({
baseURL: `http://localhost:8098`,
headers: {
'Access-Control-Allow-Origin': 'http://localhost:8080'
}
})
Here we allow requests to the base URL of our Spring Boot App on port 8098 to be accessible from 8080.
Now we could use this configuration inside our Components, e.g. in Hello.vue:
import {AXIOS} from './http-common'
export default {
name: 'hello',
data () {
return {
posts: [],
errors: []
}
},
methods: {
// Fetches posts when the component is created.
callRestService () {
AXIOS.get(`hello`)
.then(response => {
// JSON responses are automatically parsed.
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
Additionally, we need to configure our Spring Boot backend to answer with the appropriate CORS HTTP Headers in its responses (there's a good tutorial here: https://spring.io/guides/gs/rest-service-cors/). Therefore we add the annotation @CrossOrigin to our BackendController:
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(path = "/hello")
public @ResponseBody String sayHello() {
LOG.info("GET called on /hello resource");
return HELLO_TEXT;
}
Now our Backend will respond CORS-enabled and will accept requests from 8080. But as this only enables CORS on one method, we have to repeatedly add this annotation to all of our REST endpoints, which isn’t a nice style. We should use a global solution to allow access with CORS enabled to all of our REST resources. This could be done in the SpringBootVuejsApplication.class:
// Enable CORS globally
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/*").allowedOrigins("http://localhost:8080");
}
};
}
Now all calls to resources behind api/ will return the correct CORS headers.
Thanks to my colleague Daniel who pointed me to the nice proxying feature of Webpack dev-server, we don't need to configure all the complex CORS stuff anymore!
According to the Vue CLI 3 docs the only thing we need to configure is a devserver-proxy for our webpack devserver requests. This could be done easily in the optional vue.config.js inside devServer.proxy:
module.exports = {
// proxy all webpack dev-server requests starting with /api
// to our Spring Boot backend (localhost:8098) using http-proxy-middleware
// see https://cli.vuejs.org/config/#devserver-proxy
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8098',
ws: true,
changeOrigin: true
}
}
},
...
}
With this configuration in place, the webpack dev-server uses the http-proxy-middleware, which is a really handy component, to proxy all frontend-requests from http://localhost:8080 --> http://localhost:8098 - incl. Changing the Origin accordingly.
This is used in the webpack build process to configure the proxyMiddleware (you don't need to change something here!):
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context];
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(options.filter || context, options))
})
If we use the default configuration of the generated Vue.js template, we see URLs with a # inside them - like this:
http://localhost:8098/#/bootstrap
or
http://localhost:8098/#/user
With the usage of HTML5 history mode, we can achieve much nicer URLs without the # in them. Only thing to do in the Vue.js frontend is to configure our router accordingly inside the router.js:
...
Vue.use(Router);
const router = new Router({
mode: 'history', // uris without hashes #, see https://router.vuejs.org/guide/essentials/history-mode.html#html5-history-mode
routes: [
{ path: '/', component: Hello },
{ path: '/callservice', component: Service },
...
That's nearly everything. BUT only nearly! If one clicks on a link inside our frontend, the user is correctly send to the wished component.
But if the user enters the URL directly into the Browser, we get a Whitelabel Error Page because our Spring Boot backend gives us a HTTP 404 - since this URL isn't present in the backend:

The solution is to redirect or better forward the user to the frontend (router) again. The Vue.js docs don't provide an example configuration for Spring Boot, but luckily there are other resources. In essence we have to implement a forwarding controller in our BackendController:
// Forwards all routes to FrontEnd except: '/', '/index.html', '/api', '/api/**'
// Required because of 'mode: history' usage in frontend routing, see README for further details
@RequestMapping(value = "{_:^(?!index\\.html|api).$}")
public String redirectApi() {
LOG.info("URL entered directly into the Browser, so we need to redirect...");
return "forward:/";
}
This controller will forward every request other then '/', '/index.html', '/api', '/api/**' to our Vue.js frontend.
There’s a nice integration of Bootstrap in Vue.js: https://bootstrap-vue.js.org/
npm install bootstrap-vue
Now you can use all the pretty Bootstrap stuff with ease like:
<b-btn @click="callRestService()">CALL Spring Boot REST backend service</b-btn>
instead of
<button type="button" class=”btn” @click="callRestService()">CALL Spring Boot REST backend service</button>
The docs contain all the possible components: https://bootstrap-vue.js.org/docs/components/alert/
See some elements, when you go to http://localhost:8080/#/bootstrap/ - this should look like this:

A good discussion about various UI component frameworks: http://vuetips.com/bootstrap
As you may already read, the app is automatically deployed to Heroku on https://spring-boot-vuejs.herokuapp.com/.
The project makes use of the nice Heroku Pipelines feature, where we do get a full Continuous Delivery pipeline with nearly no effort:

And with the help of super cool Automatic deploys, we have our GitHub Actions build our app after every push to master - and with the checkbox set to Wait for CI to pass before deploy - the app gets also automatically deployed to Heroku - but only, if the GitHub Actions (and Codegov...) build succeeded:

You only have to connect your Heroku app to GitHub, activate Automatic deploys and set the named checkbox. That's everything!
Frontend needs to know the Port of our Spring Boot backend API, which is automatically set by Heroku every time, we (re-)start our App.
You can try out your Heroku app locally! Just create a .env-File with all your Environment variables and run
heroku local!
To access the Heroku set port, we need to use relative paths inside our Vue.js application instead of hard-coded hosts and ports!
All we need to do is to configure Axios in such a way inside our frontend/src/components/http-common.js:
export const AXIOS = axios.create({
baseURL: `/api`
})
First, add Heroku Postgres database for your Heroku app.
Then follow these instructions on Stackoverflow to configure all needed Environment variables in Heroku: https://stackoverflow.com/a/49978310/4964553
Mind the addition to the backend's pom.xml described here: https://stackoverflow.com/a/49970142/4964553
Now you're able to use Spring Data's magic - all you need is an Interface like UserRepository.java:
package de.jonashackt.springbootvuejs.repository;
import de.jonashackt.springbootvuejs.domain.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface UserRepository extends CrudRepos
Content type
Image
Digest
Size
276.9 MB
Last updated
about 5 years ago
docker pull jonashackt/spring-boot-vuejs