시작이 반

[Spring] @RequestParam, @PathVariable 본문

Programming/Spring

[Spring] @RequestParam, @PathVariable

G_Gi 2021. 1. 25. 18:08
SMALL

 

 

Spring에서 Controller의 전달 인자

1. localhost:8080/hello-mvc?name=spring

    RequestParam의 경우 url 뒤에 붙는 파라메터의 값을 가져올 때 사용

    RequestParam 여러 인자 받을수 있음

 

2. localhost:8080/hello-path/spring

    PathVariable의 경우 url에서 각 구분자에 들어오는 값을 처리해야 할 때 사용

    하나만 설정 가능

    @GetMapping("hello-mvc")//외부에서 파라미터를 받음
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template";
    }

    @GetMapping("hello-path/{name}")//외부에서 파라미터를 받음
    public String helloPath(@PathVariable("name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template";
    }

hello-template.html

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

html속성중 name 이 있는곳에 함수에서 받은 name 값이 들어감

 

 

 

 

 

 

 

@RequestParam 또는 @PathVariable 하나만 사용하는 것이 아닌 복합적으로 사용도 가능

    @GetMapping("hello-pahtparma/{name}")//외부에서 파라미터를 받음
    public String helloPathPram(@PathVariable("name") String name, @RequestParam("id") String id, Model model){
        model.addAttribute("name", name);
        model.addAttribute("id", id);
        return "hello-PathParam";
    }

hello-PathParam.html

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'name: ' + ${name}">hello! empty</p>
<p th:text="'id: ' + ${id}">hello! empty</p>
</body>
</html>

LIST