SpringBoot 와 React의 역할
- Back-end : Spring boot
- Front-End : React.js
1.Spring에서 gradle 프로젝트 생성
2. Webapp에 react 폴더 생성
3. vs코드에서 오른쪽 버튼 클릭 -> 작업 영역에 폴더 추가 -> react 추가
4. 터미널에서 react 폴더로 이동하여 npm install
5. App.js 수정
import React, { useState, useEffect } from 'react';
import axios from 'axios'
import './App.css';
function App() {
const [ testStr, setTestStr ] = useState('');
const [ test2Str, setTest2Str ] = useState('');
function callback(str) {
setTestStr(str);
}
function callback2(str){
setTest2Str(str);
}
useEffect(
() => {
axios({
url: '/home',
method: 'GET'
}).then((res) => {
callback(res.data);
})
}, []
);
return (
<div className="App">
<header className="App-header">
{testStr}
{test2Str}
</header>
</div>
);
}
export default App;
axios를 이용하여 url: '/home' 값을 보낸다.
다음 Spring에서 TestController 생성
package com.sugang.san;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin("*")
@RestController
public class TestController {
@GetMapping("/home")
public String getHome(){
System.out.println("ㅎㅇ!");
return "안녕하새우";
}
}
@crossOrigin(*)을 이용하여 모든 매핑을 받는다.
@GetMapping을 이용하여 axios에서 url: "/home" 보낸 값을 testController에서 받는다. 그 후 "안녕하새우" 리return (
return (
<div className="App">
<header className="App-header">
{testStr}
</header>
</div>
);
}
export default App;
받은 값은 {testStr}값에 넣어서 화면에 출력한다.
최종화면
'Programming > Back-end Language' 카테고리의 다른 글
[Spring] @ResponseBody은 무엇일까? (0) | 2022.03.28 |
---|---|
[Spring]Failed to load resource: the server responded with a status of 404 () 오류 해결 방법 (0) | 2022.03.24 |
[Spring] The import org.springframework.boot.test cannot be resolved 해결 방법 (0) | 2022.02.21 |
[JAVA]Call by value와 Call by referenece (0) | 2022.02.13 |
[JAVA] Servlet 로그인 페이지 만들기 (2) 마지막 (1) | 2022.01.05 |