(스프링부트, 앵귤러5 연동)Spring Boot MVC, Data JPA, REST 방식 CRUD, Angular5를 이용한…

http://www.devglan.com/spring-boot/spring-boot-angular-example 

 

 

위 주소의 예제를 따라하면 아래와 같은 결과창이 나옵니다

 

소스 답안은 

 

https://github.com/only2dhir/spring-boot-angular5 

 

에서 확인하실수 있습니다

 

 

 

 

 

820f52f8a81f7fa55d4ae783df0d7c6a_1523967
820f52f8a81f7fa55d4ae783df0d7c6a_1523967
 

 

 

 

위 예제를 하기위한 Angular 따라하기

 

 

먼저 CMD 창을 엽니다

 

아래처럼 npm -version 을 입력해봅니다

 

안나올 경우 node.js가 설치안되있는겁니다

 

 

1e08a595fa91cac2831c0ee8ec1df278_1524010
 

 

 

 

아래 주소로가서 안정적 버전으로 설치 해줍니다 

https://nodejs.org/ko/



설치 되있다면


앵귤러 프로젝트를 만들 workspace가 될 폴더로 갑니다

탐색기안에서 폴더 내에 Shift+우클릭
1e08a595fa91cac2831c0ee8ec1df278_1524011

을 하면 여기에 powershell창 열기가 나옵니다 

npm install -g @angular/cli
입력
1e08a595fa91cac2831c0ee8ec1df278_1524011

아래 명령문 입력 
ng new portal-app
1e08a595fa91cac2831c0ee8ec1df278_1524011

하면 해당 경로에 portal-app 이라는 폴더를 자동으로 생성해주고 
안에 기본적인 Angular 프로젝트 소스들을 넣어줍니다

즉 
npm install -g angular/cli 

를 입력하고

ng new 홍길동  

라고 하면
"홍길동"이라는 기본 Anuglar 프로젝트가 생성되는 겁니다

1e08a595fa91cac2831c0ee8ec1df278_1524011
위 처럼 successfully created가 나오면 성공입니다

이제 위예제를 위해서 portal-app 폴더내에서 

CMD를 통해 뭔가(컴포넌트)를 더 추가해야 합니다

cd portal-app 을 입력 합니다 (해당 폴더로 가기)

cd portal-app (해당 폴더로 가는 명령문)

ng generate component user

입력해줍니다

1e08a595fa91cac2831c0ee8ec1df278_1524012
위와같이 나온뒤 아톰이나 기타 IDE로 portal-app 폴더를 열어보면
아래처럼 나오는데 왼쪽이 우리가 방금 만든거고 
오른쪽은 예제 폴더구조입니다
빨간색 으로 표시된 파일들은 new file 로 해서 임의로 만들어줘야됩니다


1e08a595fa91cac2831c0ee8ec1df278_1524013

user.model.ts
export class User {

id: string;
firstName: string;
lastName: string;
email: string;
}






add-user.component.html
<div class="col-md-6">
<h2 class="text-center">Add User</h2>
<form>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" [(ngModel)]="user.email" placeholder="Email" name="email" class="form-control" id="email">
</div>

<div class="form-group">
<label for="firstName">First Name:</label>
<input [(ngModel)]="user.firstName" placeholder="First Name" name="firstName" class="form-control" id="firstName">
</div>

<div class="form-group">
<label for="lastName">Last Name:</label>
<input [(ngModel)]="user.lastName" placeholder="Last name" name="lastName" class="form-control" id="lastName">
</div>

<button class="btn btn-success" (click)="createUser()">Create</button>
</form>
</div>





add-user.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { User } from '../models/user.model';
import { UserService } from './user.service';

@Component({
templateUrl: './add-user.component.html'
})
export class AddUserComponent {

user: User = new User();

constructor(private router: Router, private userService: UserService) {

}

createUser(): void {
this.userService.createUser(this.user)
.subscribe( data => {
alert("User created successfully.");
});

};

}





user.component.html
<div class="col-md-6">
<h2> User Details</h2>

<table class="table table-striped">
<thead>
<tr>
<th class="hidden">Id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users">
<td class="hidden">{{user.id}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.email}}</td>
<td><button class="btn btn-danger" (click)="deleteUser(user)"> Delete User</button></td>
</tr>
</tbody>
</table>
</div>





user.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { User } from '../models/user.model';
import { UserService } from './user.service';

@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styles: []
})
export class UserComponent implements OnInit {

users: User[];

constructor(private router: Router, private userService: UserService) {

}

ngOnInit() {
this.userService.getUsers()
.subscribe( data => {
this.users = data;
});
};

deleteUser(user: User): void {
this.userService.deleteUser(user)
.subscribe( data => {
this.users = this.users.filter(u => u !== user);
})
};

}







user.service.ts
import {Injectable} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { User } from '../models/user.model';


const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class UserService {

constructor(private http:HttpClient) {}

private userUrl = 'http://localhost:8080/';


public getUsers() {
return this.http.get<User[]>(this.userUrl);
}

public deleteUser(user) {
return this.http.delete(this.userUrl + "/"+ user.id);
}

public createUser(user) {
return this.http.post<User>(this.userUrl, user);
}

}





app.component.html
<div class="container-fluid">
<div class="col-md-offset-1">
<h1>
Welcome to {{title}}!
</h1>
</div>

<a routerLink="/users">List Users</a>
<a style="margin-left:10px" routerLink="/add">Add User</a>
<br/>
<router-outlet></router-outlet>
</div>





app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'User App';
}


app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { UserComponent } from './user/user.component';
import { AppRoutingModule } from './app.routing.module';
import {UserService} from './user/user.service';
import {HttpClientModule} from "@angular/common/http";
import {AddUserComponent} from './user/add-user.component';

@NgModule({
declarations: [
AppComponent,
UserComponent,
AddUserComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [UserService],
bootstrap: [AppComponent]
})
export class AppModule { }



app.routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { UserComponent } from './user/user.component';
import {AddUserComponent} from './user/add-user.component';

const routes: Routes = [
{ path: 'users', component: UserComponent },
{ path: 'add', component: AddUserComponent }
];

@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
],
declarations: []
})
export class AppRoutingModule { }


 

마지막으로 PORTAL-APP/proxy.config.json (PORTAL-APP 디렉토리 안에 생성)

 

proxy.config.json

{
"/api/*": {
"secure": false
}
}

 

 

 

 

 

앵귤러 서버를 키는 방법은

 

portal-app경로에서 cmd 창에

 

ng serve

 

를 치면

 

localhost:4200

으로 확인할수 있습니다

 

대신 CMD창을 끄면 서버도 꺼집니다

 

 

 

 

 

 

앵귤러 첨부된 소스를 받아서 할경우(중요) 

 

 

첨부된 소스를 받아서 할경우 Angular는 node 패키지 설치작업(자바로 치면 jar파일들 추가하는거)을 해줘야됩니다

 

소스를 받은뒤

 

portal-app 경로로 가서 

 

shirt+마우스 우클릭

 

npm install 를 해주면 됩니다 

 

1e08a595fa91cac2831c0ee8ec1df278_1524014
 

 

 

 

 

 

 

 

 

스프링 부트

 

 

spring starter project

 

type:maven

java-version:8

 

group:com.devglan 

artifactId:user-portal

 

Spring boot version:2.0.1

Web -> Web 체크

 

 

User.java 

package com.devglan.userportal;
import javax.persistence.*;
@Entity
@Table(name = "user")
public class User {
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column
private String firstName;
@Column
private String lastName;
@Column
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

 

 

 

 

UserController.java

package com.devglan.userportal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping({"/api"})
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public User create(@RequestBody User user){
return userService.create(user);
}
@GetMapping(path = {"/{id}"})
public User findOne(@PathVariable("id") int id){
return userService.findById(id);
}
@PutMapping
public User update(@RequestBody User user){
return userService.update(user);
}
@DeleteMapping(path ={"/{id}"})
public User delete(@PathVariable("id") int id) {
return userService.delete(id);
}
@GetMapping
public List<User> findAll(){
return userService.findAll();
}
}

 

 

 

UserPortalApplication.java

package com.devglan.userportal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserPortalApplication {
public static void main(String[] args) {
SpringApplication.run(UserPortalApplication.class, args);
}
}

 

 

UserRepository.java

 (9 sloc)  293 Bytes

package com.devglan.userportal;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface UserRepository extends JpaRepository<User, Integer> {

}

 

 

UserService.java

package com.devglan.userportal;
import java.util.List;
public interface UserService {
User create(User user);
User delete(int id);
List<User> findAll();
User findById(int id);
User update(User user);
}

 

 

UserServiceImpl.java

 

package com.devglan.userportal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository repository;
@Override
public User create(User user) {
return repository.save(user);
}
@Override
public User delete(int id) {
User user = findById(id);
if(user != null){
repository.delete(user);
}
return user;
}
@Override
public List<User> findAll() {
return repository.findAll();
}
@Override
public User findById(int id) {
return repository.findOne(id);
}
@Override
public User update(User user) {
return null;
}
}

 

 

src/main/resources/application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=1234

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.show-sql=true

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl

spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

 

 

 

 

 

 

 

스프링 부트는 프로젝트를 하면서 pom.xml에서 많이 걸렸습니다 주의하세요

 

 

 

 

 

 

 

 

<?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>com.devglan</groupId>

<artifactId>user-portal</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>

 

<name>user-portal</name>

<description>Demo project for Spring Boot</description>

 

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.12.RELEASE</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

 

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

</properties>

 

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.6</version>

</dependency>

</dependencies>

 

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>




테이블
CREATE TABLE user(id INT NOT NULL AUTO_INCREMENT,email VARCHAR(255),first_name  VARCHAR(255),last_name VARCHAR(255),PRIMARY KEY (id))ENGINE=InnoDB;



Comments