복붙노트

[SPRING] Spring에서는 선택적 경로 변수를 만들 수 있습니까?

SPRING

Spring에서는 선택적 경로 변수를 만들 수 있습니까?

Spring 3.0에서는 선택적 경로 변수를 사용할 수 있습니까?

예를 들어

@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(
        HttpServletRequest req,
        @PathVariable String type,
        @RequestParam("track") String track) {
    return new TestBean();
}

여기에 / json / abc 또는 / json에서 같은 메서드를 호출하고 싶습니다. 한 가지 확실한 해결 방법은 형식을 요청 매개 변수로 선언하는 것입니다.

@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(
        HttpServletRequest req,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam("track") String track) {
    return new TestBean();
}

그런 다음 / json? type = abc & track = aa 또는 / json? track = rr이 작동합니다.

해결법

  1. ==============================

    1.선택적 경로 변수는 사용할 수 없지만 동일한 서비스 코드를 호출하는 두 개의 컨트롤러 메소드를 가질 수 있습니다.

    선택적 경로 변수는 사용할 수 없지만 동일한 서비스 코드를 호출하는 두 개의 컨트롤러 메소드를 가질 수 있습니다.

    @RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
    public @ResponseBody TestBean typedTestBean(
            HttpServletRequest req,
            @PathVariable String type,
            @RequestParam("track") String track) {
        return getTestBean(type);
    }
    
    @RequestMapping(value = "/json", method = RequestMethod.GET)
    public @ResponseBody TestBean testBean(
            HttpServletRequest req,
            @RequestParam("track") String track) {
        return getTestBean();
    }
    
  2. ==============================

    2.Spring 4.1과 Java 8을 사용하고 있다면 Spring MVC에서 @RequestParam, @PathVariable, @RequestHeader, @MatrixVariable에서 지원되는 java.util.Optional을 사용할 수 있습니다 -

    Spring 4.1과 Java 8을 사용하고 있다면 Spring MVC에서 @RequestParam, @PathVariable, @RequestHeader, @MatrixVariable에서 지원되는 java.util.Optional을 사용할 수 있습니다 -

    @RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
    public @ResponseBody TestBean typedTestBean(
        @PathVariable Optional<String> type,
        @RequestParam("track") String track) {      
        if (type.isPresent()) {
            //type.get() will return type value
            //corresponds to path "/json/{type}"
        } else {
            //corresponds to path "/json"
        }       
    }
    
  3. ==============================

    3.@PathVariable 어노테이션을 사용하여 경로 변수의 Map을 삽입 할 수 있다는 것은 잘 알려져 있지 않습니다. 이 기능을 Spring 3.0에서 사용할 수 있는지 또는 나중에 추가했는지는 확실하지 않지만 예제를 해결할 수있는 또 다른 방법이 있습니다.

    @PathVariable 어노테이션을 사용하여 경로 변수의 Map을 삽입 할 수 있다는 것은 잘 알려져 있지 않습니다. 이 기능을 Spring 3.0에서 사용할 수 있는지 또는 나중에 추가했는지는 확실하지 않지만 예제를 해결할 수있는 또 다른 방법이 있습니다.

    @RequestMapping(value={ "/json/{type}", "/json" }, method=RequestMethod.GET)
    public @ResponseBody TestBean typedTestBean(
        @PathVariable Map<String, String> pathVariables,
        @RequestParam("track") String track) {
    
        if (pathVariables.containsKey("type")) {
            return new TestBean(pathVariables.get("type"));
        } else {
            return new TestBean();
        }
    }
    
  4. ==============================

    4.다음을 사용할 수 있습니다 :

    다음을 사용할 수 있습니다 :

    @RequestParam(value="somvalue",required=false)
    

    pathVariable이 아닌 선택적 매개 변수의 경우

  5. ==============================

    5.

    @GetMapping({"/dto-blocking/{type}", "/dto-blocking"})
    public ResponseEntity<Dto> getDtoBlocking(
            @PathVariable(name = "type", required = false) String type) {
        if (StringUtils.isEmpty(type)) {
            type = "default";
        }
        return ResponseEntity.ok().body(dtoBlockingRepo.findByType(type));
    }
    
    @GetMapping({"/dto-reactive/{type}", "/dto-reactive"})
    public Mono<ResponseEntity<Dto>> getDtoReactive(
            @PathVariable(name = "type", required = false) String type) {
        if (StringUtils.isEmpty(type)) {
            type = "default";
        }
        return dtoReactiveRepo.findByType(type).map(dto -> ResponseEntity.ok().body(dto));
    }
    
  6. ==============================

    6.이 Spring 3 WebMVC - 선택적 경로 변수를 확인하십시오. AntPathMatcher를 확장하여 선택적 경로 변수를 활성화하고 도움이 될 수있는 기사를 보여줍니다. 모든 기사는 Sebastian Herold에게 게시됩니다.

    이 Spring 3 WebMVC - 선택적 경로 변수를 확인하십시오. AntPathMatcher를 확장하여 선택적 경로 변수를 활성화하고 도움이 될 수있는 기사를 보여줍니다. 모든 기사는 Sebastian Herold에게 게시됩니다.

  7. ==============================

    7.Nicolai Ehmann의 주석과 wildloop의 답변 (Spring 4.3.3 이상)의 간단한 예제에서 required = false를 사용할 수 있습니다.

    Nicolai Ehmann의 주석과 wildloop의 답변 (Spring 4.3.3 이상)의 간단한 예제에서 required = false를 사용할 수 있습니다.

      @RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
      public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
        if (type != null) {
          // ...
        }
        return new TestBean();
      }
    
  8. ==============================

    8.

    $.ajax({
                type : 'GET',
                url : '${pageContext.request.contextPath}/order/lastOrder',
                data : {partyId : partyId, orderId :orderId},
                success : function(data, textStatus, jqXHR) });
    
    @RequestMapping(value = "/lastOrder", method=RequestMethod.GET)
    public @ResponseBody OrderBean lastOrderDetail(@RequestParam(value="partyId") Long partyId,@RequestParam(value="orderId",required=false) Long orderId,Model m ) {}
    
  9. from https://stackoverflow.com/questions/4904092/with-spring-can-i-make-an-optional-path-variable by cc-by-sa and MIT license