@PathVariable

CODEDRAGON Development/Spring

반응형



 

 

@PathVariable

·         @PathVariable 어노테이션을 이용하면 경로(path) 변수를 넣어주면 해당 변수를 요청메소드의 파라미터로 이용 있습니다.

·         HTTP 요청에 대한 요청 URL 파라미터(경로변수;구분자)형태로 사용할 있습니다.

·         요청시 마다 변하는 부분을 경로 변수로 처리할 있습니다.

·         REST API에서 값을 호출할 uri에서 구분자에 들어오는 값을 처리해야 주로 많이 사용합니다.

 

 

요청 URL

/bbs/{경로변수}

파라미터 처리

@PostMapping("/bbs/{경로변수}")

@PathVariable("경로변수") int 매개변수

 

@PostMapping("/bbs/{경로변수}")

@PathVariable int 매개변수(경로변수명과 동일)

 

 

 

// 경로에 변수를 넣어서 요청 처리

// 해당 변수는 요청 메소드의 파라미터로 이용되어 집니다.

@RequestMapping("/student/{studentId}")

public String getStudent(@PathVariable String studentId, Model model) {

// @PathVariable 어노테이션을 통해 경에 설정한 변수를 요청메소드의 파라미터로 사용하고 있습니다.

model.addAttribute("studentId", studentId);

return "student/studentView";

}

@RequestMapping("/student/{studentId}")

// 경로변수명의 값을 저장할 변수명이 경로변수명과 다를 경우 @PathVariable 경로 변수경을 꼭어준 원하는 변수명을 사용해 주면 됩니다.습니다.

public String getStudent(@PathVariable("index") String studentNumberId, Model model) {

 

model.addAttribute("studentId", studentNumberId);

return "student/studentView";

}

 

 

 

 

 

 

요청 URL

http://localhost:8080/bbs/13

파라미터 처리

@PostMapping("/bbs/{index}")

@PathVariable("index") int articleId

 

POST방식의 /bbs/{index} 같이 uri 요청이 들어오면  /bbs/13 URL 경로에서 경로변수에 해당하는 (13) 가져와서 articleId 매개변수에 저장하여 사용합니다.

@PostMapping("/bbs/{index}")

@ResponseBody

public boolean deletePost(@PathVariable("index") int articleId) {

//...

return true;

}

 

 

 

@Controller

@RequestMapping("/bbs")

public class BbsController{

@Autowired

private BbsService bbsService;

 

@RequestMapping(value = "/{index}", method = RequestMethod.POST)

public boolean deletePost(@PathVariable("index") int articleId) {

        //...

        return true;

}

}

 

 

 

 


반응형

'Development > Spring' 카테고리의 다른 글

Static Web Resource 처리  (0) 2019.08.09
"Spring Explorer" 뷰 오픈 하기  (0) 2019.07.27
STS4에서 Spring Legacy Project 생성하기  (0) 2019.06.15
eclipse/STS - Spring 환경구성  (0) 2019.06.06
Jackson Library 검색 및 설치  (0) 2019.05.18