[Practice] 클라이언트 요청에 대한 주소 만들기 (2)

2021. 4. 12. 13:24Spring/Practice

1. 문제

 

  • 컨트롤러 인식을 위한 Controller 어노테이션 이용
  • 주소매핑은 RequestMapping을 이용
  • HTTP 메서드는 GET 방식
  • 리턴값은 "hello world" 문자열 리턴
  • 주소는 "/helloworld"

 

 

 

 

2. 풀이

기본적으로 @Controller 어노테이션은 리턴 타입이 String이 아닌 View 페이지를 리턴한다. 따라서 문자열을 리턴하기 위해 @ResponseBody 어노테이션을 사용한다.

package com.example.jpa.sample;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class FirstController {

    // 문제 1
    @RequestMapping(value = "/first-url", method = RequestMethod.GET)
    public void first() {

    }

    // 문제 2
    @ResponseBody
    @RequestMapping("/helloworld")
    public String helloworld() {
        return "hello world";
    }
}
728x90