Backend/SpringBoot

[기본 구조1] 컨트롤러 (@controller) 및 각종 매핑

Dean83 2024. 10. 21. 12:04

Url 을 매핑할때 사용되는 어노테이션으로 반드시 필요하다. 스프링에서 요청이 왔을때 소스코드로 연결을 해주기 위한 어노테이션이다.  클래스 선언부 위쪽에 작성한다. 

 

**참고 @RestController 어노테이션 사용시 @ResponseBody를 쓸 필요가 없음. (자동으로 리턴형을 보고 처리해줌)

 

 

import org.springframework.stereotype.Controller
...

@Controller
public class 클래스명()
{
	...
}

 

 

간단하게 Get 요청이 왔을때 문자열을 리턴하는 함수를 작성해보면 다음과 같다

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ResponseBody

@Controller
public class 클래스명()
{
    @GetMapping("/서브url")
    @ResponseBody
    fun 함수명(): String
    {
        return "안녕하세요"
    }
}

 

  • GetMapping
    • Get 요청이 왔을때 매핑되는 어노테이션이다. 
    • PostMapping 등 각 RESTAPI 에 해당되는 매핑 어노테이션이 존재한다. 
    • 서브 url 주소를 매핑하며, 해당 요청이 들어왔을때 처리를 한다. 
    • import org.springframework.web.bind.annotation.GetMapping 추가 해야 한다.


  • postURL 항목 Mapping
    • static url 이 아닌, 뒤에 page 숫자가 있다든지, token값이 있다든지 하는 가변형 postURL을 매핑해야 하는경우 @pathVariable 어노테이션을 사용한다. 
    • import org.springframework.web.bind.annotation.PathVariable; 추가한다
    • pathVariable 에서 정의한 변수명과 실제 함수에서 받는 인자값의 변수명이 일치해야 한다.
import org.springframework.ui.Model
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class 클래스명()
{
    @GetMapping("/서브url/{변수명}")
    fun 함수명(model : Model, @PathVariable("변수명") 변수명 : Int) : String
    {
        model.addAttribute("키값",변수명)
        return "templates폴더의 html파일명(확장자제외)"
    }
}



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

@Controller
public class test()
{
    @GetMapping("/hello/{pagenum}")
    fun Hello(model : Model, @PathVariable("pagenum") pagenum : Int) : String
    {
        model.addAttribute("test",pagenum)
        return "hello"
    }
}



  • @RequestMapping
    • Url 의 prefix 매핑을 위한 어노테이션으로, 한 클래스에 중복되는 prefix url이 있을경우 사용한다
      • 예 : 1번 함수에서 /hello/hi 를 매핑하고, 2번함수 에서 /hello/hi2 를 매핑한다고 하면, /hello가 prefix url이 된다
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("/prefixurl주소")
@Controller
public class 클래스명()
{
	//  /prefixulr/서브url
    @GetMapping("/서브url")
    @ResponseBody
    fun 함수명() : String
    {
       ...
        return "hello"
    }
}
  •  @ResponseBody
    • 응답의 body로 내용을 전달하겠다는 어노테이션으로, url 요청이 왔을때 해당 리턴값이 응답값이 된다. 
    • import org.springframework.web.bind.annotation.ResponseBody 추가 해야 한다.

 

  • @RequestParam
    • url 호출시 인자값으로 받은 항목을 가져올때 사용한다. 
    • import org.springframework.web.bind.annotation.RequestParam 을 추가 해야한다.
    • PathVariable과 같이 RequestParam에서 정의한 이름과 함수의 인자값 이름이 일치해야 한다.
    • 아래는 예시이다
package com.example.test1.test1

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

@Controller
public class test(val serviceItem : ServiceClass)
{
    @GetMapping("/hello/{pagenum}")
    fun Hello(model : Model, @PathVariable("pagenum") pagenum : Int, @RequestParam("content") content : String) : String
    {
        serviceItem.ReadItem()
        model.addAttribute("test",pagenum)
        return "hello"
    }
}




  • GetMapping 이나 ResponseBody 등은 프로젝트 설정시 Spring Web 을 설정하였다면, gradle에 포함이 되어 있을 것이다.  없다면, gradle 에 추가 해주자. 기본적으로 build.gradle 의 dependency 에 아래것들이 없으면 추가해주자
...

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'com.fasterxml.jackson.module:jackson-module-kotlin'
	implementation 'org.jetbrains.kotlin:kotlin-reflect'
	compileOnly 'org.projectlombok:lombok'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.jetbrains.kotlin:kotlin-test-junit5'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

...