본문 바로가기
Dev/Spring

URI 템플릿 사용 - @PathVariable, @RequestMapping

by vellahw 2022. 10. 20.

 

 

RESTful 서비스의 영향으로 URI를 다음과 같이 REST 방식으로 구성하는 경우가 대부분이다.

  • http://somehost/users/codingco
  • http://somehost/games
  • http://somehost/forum/board1/10

이전에는 http://somehost/users/userinfo?id=codingco와 같이 파라미터를 이용해서 아이디나 이름을 전달받았다면, 이제는 URI에 아이디나 이름 등이 포함되도록 URL을 구성하고 있다.

SPRING 3버전에 추가된 기능 중 하나인 URI 템플릿을 이용하면 REST 방식의 URL 매칭을 쉽게 처리할 수 있다. 

 

🎈. URI 템플릿을 사용하는 방법

  • @RequestMapping Annotation의 값으로 {템플릿변수}를 사용한다.
  • @PathVariable Annotation을 이용해서 {템플릿변수}와 동일한 이름을 갖는 파라미터를 추가한다.

 

 

💡. @PathVariable Annotation을 이용한 URI 템플릿

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
            
@Controller            
public class CharacterInfoController {
 
    @RequestMapping("/game/users/{userId}/characters/{characterId}")
    public String characterInfo(@PathVariable String userId,    
                @PathVariable int characterId, ModelMap model) {
 
        model.addAttribute("userId", userId);
        model.addAttribute("characterId", characterId);
            return "game/character/info";
    }
}
cs

위 코드를 보면 @RequestMapping Annotation은 이름이 userId와 characterId인 변수를 포함하고 있다.

이들 변수는 @PathVariable Annotation이 적용된 동일한 이름을 갖는 파라미터에 매칭된다. 

따라서 요청 URI가 " /game/users/codingco/character/1 "이면, characterInfo() 메서드의 userId 파라미터와 characterId 파라미터의 값은 각각 " codingco "와 " 1 "이 된다.
        

 

💡. @RequestMapping Annotation의 추가 설정 방법

@RequestMapping Annotation을 Class와 메서드에 함께 적용할 경우, 메서드에 적용한 @RequestMapping Annotation의 값은 Class에 적용한 @RequestMapping Annotation의 값을 기본 경로로 사용하게 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Controller
@RequestMapping("/game/users/{userId}")
public class CharacterInfoController {
            
    @RequestMapping("/characters/{characterId}")
    public String characterInfo(@PathVariable String userId,
                            @PathVariable int characterId, ModelMap model) {
 
        model.addAttribute("userId", userId);
        model.addAttribute("characterId", characterId);
 
        return "game/character/info";
    }
}
cs

위 코드에서 characterInfo() 메서드에 적용된 @RequestMapping Annotation의 값은 " /characters/{characterId} "인데,

실제로 매칭되는 값은 Class에 적용된 @RequestMapping Annotation의 값을 포함한 "/game/users/{userId}/characters/{chracterId} " 가 된다.

 

@RequestMapping Annotation은 Ant 스타일의 패턴을 지원하기 때문에 경로명에 " * "나 " ** "를 값으로 사용할 수 있다.

예) @RequestMapping("/members/*.do")  || @RequestMapping("/game/*/items/{itemId}")

 

 

🎈. URI 템플릿 사용 예제 

1) 컨트롤러

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package springMVC.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
@RequestMapping("/game/users/{userId}")
public class CharacterInfoController {
    @RequestMapping("/characters/{characterId}")
    public String characterInfo(@PathVariable String userId, 
                            @PathVariable int characterId, ModelMap model) {
        
        model.addAttribute("userId", userId);
        model.addAttribute("characterId", characterId);
        
        return "game/character/info";
    }
}
cs

 

2) 스프링 설정 파일에 bean 설정 추가

1
<bean class="springMVC.controller.CharacterInfoController" />
cs

 

3) 뷰 파일 작성

1
2
3
4
5
6
7
8
9
10
<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>캐릭터 정보</title>
</head>
<body>
${userId} 회원의 ${characterId} 캐릭터 정보 출력
</body>
</html>
cs

 

실행 결과

 

 

댓글