어느 비전공자의 개발일지

Spring MVC 와 Rest API 본문

백엔드 개발자/Java[Spring]

Spring MVC 와 Rest API

vndn629 2025. 3. 26. 16:12

 

Spring MVC

 

● Spring MVC 웹 Jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Greeting</title>
</head>
<body>
    <h1>Hello, ${name}!</h1>
    <p>Your ID is: ${userId}</p>
</body>
</html>

 

● Spring MVC 웹 Controller.java

 

package com.example.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

    @GetMapping("/greeting")
    public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        model.addAttribute("userId", 123); // 예시 데이터
        return "greeting"; // View 이름 (greeting.jsp) 반환
    }
}

 

 

 

 

 

 


Rest API

 

 

● Rest API (jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>API Consumer</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#fetchData").click(function() {
                $.ajax({
                    url: "/api/users/1", // REST API 엔드포인트
                    type: "GET",
                    dataType: "json",
                    success: function(data) {
                        $("#userName").text(data.name);
                        $("#userEmail").text(data.email);
                    },
                    error: function(error) {
                        console.error("Error fetching data:", error);
                        $("#result").text("데이터를 가져오는 데 실패했습니다.");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h1>API Consumer</h1>
    <button id="fetchData">Get User Data</button>
    <div id="result">
        <p>User Name: <span id="userName"></span></p>
        <p>User Email: <span id="userEmail"></span></p>
    </div>
</body>
</html>

 

 

● Rest API Controller.java

package com.example.rest;

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

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

@RestController
@RequestMapping("/api/users")
public class UserRestController {

    @GetMapping("/{id}")
    public Map<String, String> getUser(@PathVariable Long id) {
        // 실제로는 DB에서 사용자 정보를 조회하는 로직이 들어갑니다.
        Map<String, String> user = new HashMap<>();
        if (id == 1) {
            user.put("name", "John Doe");
            user.put("email", "john.doe@example.com");
        } else {
            user.put("name", "User Not Found");
            user.put("email", "");
        }
        return user; // JSON 형태로 자동 변환되어 응답
    }
}

 

 

 

 

 

반응형