ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring Boot] Controller vs RestController
    공부/etc 2024. 3. 2. 17:30
    package wordle.wordle.controller;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.node.ObjectNode;
    import com.fasterxml.jackson.databind.node.ArrayNode;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    import wordle.wordle.utils.JsonConverter;
    
    @RestController
    @RequestMapping("/wordle")
    public class WordleController {
    
        @RequestMapping(method=RequestMethod.GET, path="/")
        public String home(Model model){
            System.out.println("GET HOME");
            model.addAttribute("data", "hello wordle!");
            return "wordle";
        }
    
        @RequestMapping(method=RequestMethod.GET, path="/lookup")
        public static ArrayNode word(@RequestParam String word) throws Exception{
            String dictionaryUrl = String.format("https://api.dictionaryapi.dev/api/v2/entries/en/%s", word);
            URL url = new URL(dictionaryUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
    
            ObjectMapper objectMapper = new ObjectMapper();
            ArrayNode jsonResponse = objectMapper.createArrayNode();
    
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
    
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
    
                String responseBody = response.toString();
                JsonConverter jsonConverter = new JsonConverter();
                jsonResponse = jsonConverter.convertStringToJsonArray(responseBody);
    //            System.out.println("Response Body: " + jsonResponse);
                connection.disconnect();
            }
            else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
                ObjectNode objectNode = objectMapper.createObjectNode();
                objectNode.put("msg", "It does not exist!");
                jsonResponse.add(objectNode);
            }
            return jsonResponse;
        }
    }

     

     

    위 Class에서 

    • /wordle 로 GET Request를 전송했을 때는, resources/templates/wordle.html이 반환되고
    • /wordle/lookup?word=[검색할 단어] 로 GET Request를 전송했을 때는, JSON 데이터가 반환되길 기대했다.

    하지만 /wordle로 GET Request를 전송했을때는 아래와 같은 오류가 발생함

     

     

    /wordle/ 로 GET Request 전송시에는 오류는 나지 않지만, 기대했던 html 파일이 아닌 String이 반환됨

     

     

    왜 이러는거야~!~!~!

     

    찾아보니 RestController를 사용했기 때문에 html이 반환되지 않은 것 같았다.

     

    간략하게 정리하면

    @RestController은 @Controller와 @ResponseBody의 조합
    RESTful 웹 서비스 개발을 용이하게 하기 위해 Spring 4.0에서 추가된 어노테이션임

    @Controller은 Model 객체를 매개변수로 전달받아 주로 View를 반환하기 위해 사용함

     

    참고

    https://dncjf64.tistory.com/288

     

    @Controller와 @RestController의 차이점

    1.개요 Spring MVC의 @RestController은 @Controller와 @ResponseBody의 조합입니다. Spring 프레임 워크에서 RESTful 웹 서비스를 보다 쉽게 개발할 수 있도록 Spring 4.0에서 추가되었습니다. 근본적인 차이점은 @Contr

    dncjf64.tistory.com

     

     


    아래와 같이 코드를 수정하여 해결~!

     

    package wordle.wordle.controller;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.node.ObjectNode;
    import com.fasterxml.jackson.databind.node.ArrayNode;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    import wordle.wordle.utils.JsonConverter;
    
    @Controller
    @RequestMapping("/wordle")
    public class WordleController {
    
        @RequestMapping(method=RequestMethod.GET, path="")
        public String home(Model model){
            System.out.println("GET HOME");
            model.addAttribute("data", "wordle!");
            return "wordle";
        }
    
        @RequestMapping(method=RequestMethod.GET, path="/lookup")
        public static @ResponseBody ArrayNode word(@RequestParam String word) throws Exception{
            String dictionaryUrl = String.format("https://api.dictionaryapi.dev/api/v2/entries/en/%s", word);
            URL url = new URL(dictionaryUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
    
            ObjectMapper objectMapper = new ObjectMapper();
            ArrayNode jsonResponse = objectMapper.createArrayNode();
    
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
    
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
    
                String responseBody = response.toString();
                JsonConverter jsonConverter = new JsonConverter();
                jsonResponse = jsonConverter.convertStringToJsonArray(responseBody);
    //            System.out.println("Response Body: " + jsonResponse);
                connection.disconnect();
            }
            else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
                ObjectNode objectNode = objectMapper.createObjectNode();
                objectNode.put("msg", "It does not exist!");
                jsonResponse.add(objectNode);
            }
            return jsonResponse;
        }
    }

     

     

    • GET /wordle

     

    • GET /wordle/lookup?word=love

     

     

     

    • (참고) wordle.html
    <!DOCTYPE HTML>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Hello</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    <p th:text="'Welcome to ' + ${data}" ></p>
    </body>
    </html>
Designed by Tistory.