자바 JAVA/Spring | 스프링
[Spring Boot] @PathVariable ?
saml2l
2020. 8. 25. 13:29
- @PathVariable
- @PathVariable is a Spring annotation which indicates that a method parameter should be bound to a URI template variable.
- If the method parameter is Map<String, String> then the map is populated with all path variable names and values.
- @PathVariable 은 메소드의 파라미터가 URI 템플릿 변수에 bind 되어 있다는 것을 가리킨다.
- 메소드의 파리미터가 Map<String, String> 형태일 경우, map 은 경로 변수 이름과 값을 다 포함하게 된다.
- 쉽게 얘기해서 URI 경로에 변수를 집어 넣을수 있다는 점.
- http://localhost:8085/article/list?boardCode=free
- 이런식으로 하는 것보다 아래 처럼
- http://localhost:8085/article/free-list
- 이렇게
- http://localhost:8085/article/list?boardCode=free
@Controller
public class ArticleController {
@Autowired
private ArticleService articleService;
@RequestMapping("/article/{boardCode}-list")
public String showArticleList(Model model, @PathVariable("boardCode") String boardCode) {
List<Article> articles = articleService.getArticlesForList();
Board board = articleService.getBoardByCode(boardCode);
model.addAttribute("board", board);
model.addAttribute("articles", articles);
return "article/list";
}
- Controller 에서 boardCode 를 @PathVariable 를 붙여줘서 uri 에서 사용 가능하게 해줌
- @RequestMapping 에서 showArticleList()의 parameter 인 @PathVariable("boardCode") 를 받아서
@RequestMapping("article/{boardCode}-list} 이런식으로 URI에 변수를 추가해주면 http://localhost:8085/article/free-list 처럼 사용 가능함.
끝.