Vue 와 RestController 연동하는 방법

HUGO·2022년 10월 14일
0

VUE 연동

목록 보기
1/1

Controller와 RestController의 차이

✔ controller는 templates에 html과 연동 하기 위해쓰는 것
✔ restcontroller는 프론트엔드(EX : Vue)와 연동 하기 위해 쓰는 것

BoardRestController.java 예제

package com.example.restcontroller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.entity.Board;
import com.example.repository.BoardRepository;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping(value = "/api/board")
@RequiredArgsConstructor
public class BoardRestController {
    
    final BoardRepository boardRepository;

    @GetMapping(value = "/select.do")
    public Map<String, Object> selectGET(){
        Map<String , Object> map = new HashMap<>();
        try {
            List<Board> list = boardRepository.findAll();
            map.put("status", 200);
            map.put("result", list);
        } catch (Exception e) {
            map.put("status", -1);
        }
        return map;
    }
}

Vue 설정하기

vue.config.js
-- 필요한 라이브러리 다운로드

-- 라우트
CMD> npm i vue-router@next --save

-- 벡엔드 연동
CMD> npm i axios --save

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,

  // 벡엔드 연동설정
  devServer: {
    proxy: {
      "/ROOT": {
        target: 'http://127.0.0.1:8080',
        changeOrigin: true,
        logLevel: 'debug'
      }
    },
    port: 9090
  },

  // resources/static/vue 폴더에 위치
  publicPath:'/ROOT/vue'
})

VUE 코드 작성

<template>
  <div>
    <h3>홈화면</h3>
    {{state.rows}}
  </div>
</template>

<script>
import axios from 'axios';
import { reactive } from '@vue/reactivity';
import { onMounted } from '@vue/runtime-core';

export default {
  setup () {
    const state = reactive({
      rows:null
    });   

    const handleData = async() => {
      const url = `/ROOT/api/board/select.json`;
      const headers = {"Content-Type":"application/json"};
      const { data } = await axios.get(url, {headers});
      if(data.status === 200) {
        state.rows = data.result;
      }
    };

    onMounted(()=>{
      handleData();
    });

    return {state}
  }
}
</script>

<style lang="scss" scoped>

</style>

HomeController.java에 소스 추가

 // 127.0.0.1:8080/ROOT/vue.do
    @GetMapping(value="/vue.do")
    public String aaa() {
        return "vue/index";
    }
    

vue를 연동 하기위해 java 파일에 vue 폴더 만들기

resources/static/vue

이 파일안에 vue 폴더에 dist 에 있던 파일을 들고옴

✔ 이때 index.html 은 java/templates 폴더에 vue파일을 만들고 그안에 집어넣음(사실 index.html은 굳이 vue 파일을 안 만들고 넣어도 됌.)

profile
갓 신생아 개발자 이야기

0개의 댓글