스프링 부트와 앵귤러의 통합 :

Spring Boot and AngularJS Integration Tutorial

This tutorial helps you to build a simple spring boot application. Also, you might like to implement a simple UI such as an administrator tool or control panel to work with the backend. This is when I start learning about Angularjs to develop a simple UI for a monitoring project at work. I’ve found Spring boot and Angularjs very easy to work with, especially when there is a tight deadline for the project. Let’s see what are these frameworks and how we can integrate them.

1. Why Spring Boot?

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications. Most Spring Boot applications need very little Spring configuration. Spring Boot provides an easy way to quickly and simply run a java application, through an embedded server – by default it uses an embedded version of tomcat – thus eliminating the need of any Java EE containers. With Spring Boot, we can expose components such as REST services independently, exactly as proposed in microservices architecture, so that in any maintenance of the components, we no longer make the redeploy of all the system.

angularjs_small

 

AngularJS Programming Cookbook

In this ebook, we provide a compilation of AngularJS based examples that will help you kick-start your own web projects. We cover a wide range of topics, from Single Page Apps and Routing, to Data Binding and JSON Fetching. With our straightforward tutorials, you will be able to get your own projects up and running in minimum time. Download the cookbook by joining the Web Code Geeks Newsletter.

2. Why Angularjs?

AngularJS is a JavaScript framework. It is a library written in JavaScript. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application’s components clearly and succinctly. Angular’s data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.

3. Create a Spring Boot Application

Now, let’s create a spring boot application and go through more details. The following application is created in IntellijIDEA 15 CE. The project is developed based on JDK 1.8 and uses maven 4.

First of all, create a Maven project in your IDEA and configure the pom.xml file to include all required dependencies in the project. In this tutorial, we use spring-boot-1.3.3-RELEASE to configure the spring boot application. Also, we use webjars libraries to include all necessary js files for Angularjs.

pom.xml

01 <?xml version="1.0" encoding="UTF-8"?>
02 <project xmlns="http://maven.apache.org/POM/4.0.0"
03          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05     <modelVersion>4.0.0</modelVersion>
06  
07     <groupId>springboot-angularjs</groupId>
08     <artifactId>springboot-angularjs</artifactId>
09     <version>1.0-SNAPSHOT</version>
10  
11     <parent>
12         <groupId>org.springframework.boot</groupId>
13         <artifactId>spring-boot-starter-parent</artifactId>
14         <version>1.3.3.RELEASE</version>
15     </parent>
16     <dependencies>
17         <dependency>
18             <groupId>org.springframework.boot</groupId>
19             <artifactId>spring-boot-starter-web</artifactId>
20         </dependency>
21         <dependency>
22             <groupId>org.webjars</groupId>
23             <artifactId>angularjs</artifactId>
24             <version>1.4.9</version>
25             <scope>runtime</scope>
26         </dependency>
27         <dependency>
28             <groupId>org.webjars</groupId>
29             <artifactId>bootstrap</artifactId>
30             <version>3.3.6</version>
31             <scope>runtime</scope>
32         </dependency>
33     </dependencies>
34 </project>

WebJars is simply taking the concept of a JAR and applying it to client-side libraries or resources. For example, the Angularjs library may be packaged as a JAR and made available to your Spring Boot application. Many WebJars are available through Maven Central with a GroupID for org.webjars. A complete list is available at webjars.org.

JavaScript package management is not a new concept. In fact, npm and bower are two of the more popular tools, and currently offer solutions to managing JavaScript dependencies. Spring’s Understanding JavaScript Package Managers guide has more information on these. Most JavaScript developers are likely familiar with npm and bower and make use of those in their projects. However, WebJars utilizes Maven’s dependency management model to include JavaScript libraries in a project, making it more accessible to Java developers.

4. Spring boot application configuration

The SpringApplication class provides a convenient way to bootstrap a Spring boot application that will be started from a main() method. In many situations you can just delegate to the static SpringApplication.run method similar to the following class:

WebAppInitializer.java

01 package com.javacodegeeks.examples;
02  
03 import org.springframework.boot.SpringApplication;
04 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
05 import org.springframework.context.annotation.ComponentScan;
06 import org.springframework.context.annotation.Configuration;
07  
08 @Configuration
09 @EnableAutoConfiguration
10 @ComponentScan("com.javacodegeeks.examples")
11 public class WebAppInitializer{
12  
13     public static void main(String[] args) throws Exception{
14         SpringApplication.run(WebAppInitializer.class, args);
15     }
16 }

@Configuration tags the class as a source of bean definitions for the application context.
@EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans and various property settings.

@ComponentScan tells Spring to look for other components, configurations and services in the specified package which allows the application to find the MainController.

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. Here, the static content is under the /resources directory.

5. A simple Controller

The following class is only a simple controller which is implemented to handle the request to '/' and render the request to index.html.

MainController.java

01 package com.javacodegeeks.examples.controller;
02  
03 import org.springframework.stereotype.Controller;
04 import org.springframework.web.bind.annotation.RequestMapping;
05 import org.springframework.web.bind.annotation.RequestMethod;
06  
07 @Controller
08 public class MainController {
09  
10     @RequestMapping(value="/",method = RequestMethod.GET)
11     public String homepage(){
12         return "index";
13     }
14 }

6. Angularjs controllers and js, html files

In the index.html, there is some front-end code to display links in the page which are handled by Angularjs. Also, there are some script tags that included all necessary Angularjs js files.

index.html

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

01 <!DOCTYPE html>
02 <!--[if lt IE 7]>      <html lang="en" ng-app="app" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
03 <!--[if IE 7]>         <html lang="en" ng-app="app" class="no-js lt-ie9 lt-ie8"> <![endif]-->
04 <!--[if IE 8]>         <html lang="en" ng-app="app" class="no-js lt-ie9"> <![endif]-->
05 <!--[if gt IE 8]><!--> <html lang="en" ng-app="app" class="no-js"> <!--<![endif]-->
06 <head>
07     <meta charset="utf-8">
08     <meta http-equiv="X-UA-Compatible" content="IE=edge">
09     <title>Spring boot and Angularjs Tutorial</title>
10     <meta name="description" content="">
11     <meta name="viewport" content="width=device-width, initial-scale=1">
12     <link rel="stylesheet" href="/css/app.css">
13 </head>
14 <body>
15 <h2>Administrator Panel</h2>
16 <div class="home-section">
17     <ul class="menu-list">
18         <li><a href="#/users">Users</a></li>
19         <li><a href="#/roles">Roles</a></li>
20     </ul>
21 </div>
22 <div ng-view></div>
23 <script src="/webjars/angularjs/1.4.9/angular.js"></script>
24 <script src="/webjars/angularjs/1.4.9/angular-resource.js"></script>
25 <script src="/webjars/angularjs/1.4.9/angular-route.js"></script>
26 <script src="/js/app.js"></script>
27 <script src="/js/controller.js"></script>
28 <link rel="stylesheet" href="/webjars/bootstrap/3.3.6/css/bootstrap.css">
29 </body>
30 </html>

ng-view is a directive that complements the $route service by including the rendered template of the current route into the main layout. Every time the current route changes, the included view changes with it according to the configuration of the $routeProvider.

app.js file defines the application module configuration and routes. To handle a request to e.g. '/', it needs an Angularjs module, called ngRoute. To use ngRoute and inject it into our application. We use angular.module to add the ngRoute module to our app as shown below.

app.js

01 var app = angular.module('app', ['ngRoute','ngResource']);
02 app.config(function($routeProvider){
03     $routeProvider
04         .when('/users',{
05             templateUrl: '/views/users.html',
06             controller: 'usersController'
07         })
08         .when('/roles',{
09             templateUrl: '/views/roles.html',
10             controller: 'rolesController'
11         })
12         .otherwise(
13             { redirectTo: '/'}
14         );
15 });

Then, in the app.config, each route is mapped to a template and controller. Controller.js contains the implementation of controllers. The controller is simply a constructor function that takes a $scope parameter. You might notice that we are injecting the $scope service into our controller. Actually, AngularJS comes with a dependency injection container built into it.

Here, a headingtitle is set in scope to display in the view, either gallery or contactInfo.

controller.js

1 app.controller('usersController', function($scope) {
2     $scope.headingTitle = "User List";
3 });
4  
5 app.controller('rolesController', function($scope) {
6     $scope.headingTitle = "Roles List";
7 });

The concept of a $scope in Angular is crucial. A $scope can be seen as the glue which allows the template, model and controller to work together. Angular uses scopes, along with the information contained in the template, data model, and controller, to keep models and views separate, but in sync. Any changes made to the model are reflected in the view; any changes that occur in the view are reflected in the model.

users.html

01 <div class="section">
02     <h3>{{headingTitle}}</h3>
03     <div>
04         <ul type="square">
05             <li>Luke</li>
06             <li>Darth</li>
07             <li>Anakin</li>
08             <li>Leia</li>
09         </ul>
10     </div>
11 </div>

In this two html files, you can see the {{headingTitle}} which will be filled later by the value that is set in scope.

roles.html

01 <div class="section">
02     <h3>{{headingTitle}}</h3>
03     <div>
04         <ul type="square">
05             <li>Administrator</li>
06             <li>Super Admin</li>
07             <li>User</li>
08             <li>View-Only</li>
09         </ul>
10     </div>
11 </div>

The source directory of the project is as below at the end.

Spring boot and Angularjs project directory

7. Build and run the application

Now, it is time to deploy and run the project in action. To do so, go to the project directory and run:

1 mvn clean install

Then, run the application on tomcat.

1 mvn spring-boot:run

And you can now navigate the project as below.

Spring boot and Angularjs project on web

Spring boot and Angularjs project on web

8. Download the Source Code

Download
You can download the full source code of this example here: Integration Spring Boot and AngularJS Tutorial.
 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
106 Spring MVC Dropdown Box Example file 졸리운_곰 2018.03.26 214
105 SpringBoot JPA 예제 졸리운_곰 2018.03.13 344
104 스프링 CKEditor 적용 - 에디터 졸리운_곰 2018.03.07 2594
103 spring ckeditor 파일업로드 예제 (file upload) file 졸리운_곰 2018.03.07 2036
102 CKEditor 사용 및 파일 업로드 적용 졸리운_곰 2018.03.07 164
101 Spring MVC Checkbox And Checkboxes Example 자바 스프링 mvc 체크박스 샘플 file 졸리운_곰 2018.03.07 80
100 SPRING MVC - CHECKBOXES EXAMPLE 자바 스프링 mvc 체크박스 예제 file 졸리운_곰 2018.03.07 184
99 Spring MVC Dropdown Box Example 스프링 웹 개발 [콤보 선택 박스] file 졸리운_곰 2018.03.07 238
98 SPRING과 ANGULAR2 연동해서 실행하기 file 졸리운_곰 2018.02.12 198
97 두번째, 스프링 배치보다 간편한 스프링 Quartz 졸리운_곰 2018.02.08 118
96 첫번째, 스프링 배치보다 간편한 스프링 Quartz 졸리운_곰 2018.02.08 104
95 JAVA] Quartz (쿼츠)를 사용하여 자바 스케줄링(scheduling) 하기 졸리운_곰 2018.02.08 628
94 Spring Batch를 이용한 기본적인 Batch Application 졸리운_곰 2018.02.08 81
93 Quartz + Spring Batch 조합하기 file 졸리운_곰 2018.02.08 2061
92 스프링 web MVC와 앵귤러의 통합 How to configure AngularJs with Spring MVC | SpringBoot file 졸리운_곰 2018.01.28 204
» 스프링 부트와 앵귤러의 통합 : Spring Boot and AngularJS Integration Tutorial file 졸리운_곰 2018.01.28 492
90 mybatis에서 selectKey 사용법 졸리운_곰 2018.01.24 391
89 Spring form:form 태그 설명 졸리운_곰 2018.01.24 180
88 java spring form 태그 졸리운_곰 2018.01.24 147
87 Spring MVC - 값 전달 file 졸리운_곰 2018.01.24 94
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED