development

스프링 MVC @ PathVariable

big-blog 2020. 7. 22. 07:34
반응형

스프링 MVC @ PathVariable


@PathVariablespring mvc 에서 사용하는 간단한 설명과 샘플을 제공해 주 시겠습니까? URL을 입력하는 방법을 포함 시키십시오?
jsp 페이지를 표시하기 위해 올바른 URL을 얻는 데 어려움을 겪고 있습니다. 감사.


주문을 가져 오기 위해 URL을 작성한다고 가정하면 말할 수 있습니다.

www.mydomain.com/order/123

여기서 123은 orderId입니다.

이제 스프링 mvc 컨트롤러에서 사용할 URL은 다음과 같습니다.

/order/{orderId}

이제 주문 ID를 경로 변수로 선언 할 수 있습니다

@RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public String getOrder(@PathVariable String orderId){
//fetch order
}

url www.mydomain.com/order/123을 사용하는 경우 orderId 변수는 봄에 의해 123 값으로 채워집니다.

또한 pathVariable은 URL의 일부이므로 PathVariable은 requestParam과 다릅니다. 요청 매개 변수를 사용하는 동일한 URL은 다음과 같습니다.www.mydomain.com/order?orderId=123

API DOC
Spring 공식 참조


아래 코드 스 니펫을 살펴보십시오.

@RequestMapping(value="/Add/{type}")
public ModelAndView addForm(@PathVariable String type ){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("addContent");
    modelAndView.addObject("typelist",contentPropertyDAO.getType() );
    modelAndView.addObject("property",contentPropertyDAO.get(type,0) );
    return modelAndView;
}

코드 작성에 도움이되기를 바랍니다.


경로 변수가 포함 된 URL이있는 경우 (예 : www.myexampl.com/item/12/update) 여기서 12는 id이고 create는 단일 양식을 사용하여 업데이트를 수행 할 때 intance 실행을 지정하는 데 사용하려는 변수입니다. 컨트롤러 에서이 작업을 수행하십시오.

   @RequestMapping(value = "/item/{id}/{method}" , RequestMethod.GET)
    public String getForm(@PathVariable("id") String itemId ,  @PathVariable("method") String methodCall , Model model){
  if(methodCall.equals("create")){
    //logic
}
 if(methodCall.equals("update")){
//logic
}

return "path to your form";
}

@PathVariable URL에서 값을 가져 오는 데 사용

예를 들어 : 질문을 받으려면

www.stackoverflow.com/questions/19803731

여기에 몇 가지 질문 id이 URL의 매개 변수로 전달됩니다.

이제이 값을 가져 오려면 controller메소드 매개 변수에서 @PathVariable을 전달하면됩니다.

@RequestMapping(value = " /questions/{questionId}", method=RequestMethod.GET)
    public String getQuestion(@PathVariable String questionId){
    //return question details
}

메소드 매개 변수가 URI 템플리트 변수에 바인드되어야 함을 표시하는 주석. RequestMapping 어노테이션이있는 핸들러 메소드에 지원됩니다.

@RequestMapping(value = "/download/{documentId}", method = RequestMethod.GET)
public ModelAndView download(@PathVariable int documentId) {
    ModelAndView mav = new ModelAndView();
    Document document =  documentService.fileDownload(documentId);

    mav.addObject("downloadDocument", document);
    mav.setViewName("download");

    return mav;
}

Let us assume you hit a url as www.example.com/test/111 . Now you have to retrieve value 111 (which is dynamic) to your controller method .At time you ll be using @PathVariable as follows :

@RequestMapping(value = " /test/{testvalue}", method=RequestMethod.GET)
public void test(@PathVariable String testvalue){
//you can use test value here
}

SO the variable value is retrieved from the url


It is one of the annotation used to map/handle dynamic URIs. You can even specify a regular expression for URI dynamic parameter to accept only specific type of input.

For example, if the URL to retrieve a book using a unique number would be:

URL:http://localhost:8080/book/9783827319333

The number denoted at the last of the URL can be fetched using @PathVariable as shown:

@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)

public String showBookDetails(@PathVariable("ISBN") String id,

Model model){

model.addAttribute("ISBN", id);

return "bookDetails";

}

In short it is just another was to extract data from HTTP requests in Spring.


have a look at the below code snippet.

@RequestMapping(value = "edit.htm", method = RequestMethod.GET) 
    public ModelAndView edit(@RequestParam("id") String id) throws Exception {
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("user", userinfoDao.findById(id));
        return new ModelAndView("edit", modelMap);      
    }

If you want the complete project to see how it works then download it from below link:-

UserInfo Project on GitLab

참고URL : https://stackoverflow.com/questions/19803731/spring-mvc-pathvariable

반응형