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
호출하고 싶습니다 .
한 가지 확실한 해결 방법 type
은 요청 매개 변수로 선언합니다 .
@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
작동합니다
선택적 경로 변수를 가질 수는 없지만 동일한 서비스 코드를 호출하는 두 가지 컨트롤러 메소드를 가질 수 있습니다.
@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();
}
당신은 봄 4.1 및 Java 8을 사용하는 경우 사용할 수 java.util.Optional
있는 지원되는 @RequestParam
, @PathVariable
, @RequestHeader
및 @MatrixVariable
스프링 MVC에서 -
@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"
}
}
@PathVariable 주석을 사용하여 경로 변수의 맵을 삽입 할 수도 있다는 것은 잘 알려져 있지 않습니다. 이 기능을 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();
}
}
You could use a :
@RequestParam(value="somvalue",required=false)
for optional params rather than a pathVariable
Spring 5 / Spring Boot 2 examples:
blocking
@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));
}
reactive
@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));
}
Check this Spring 3 WebMVC - Optional Path Variables. It shows an article of making an extension to AntPathMatcher to enable optional path variables and might be of help. All credits to Sebastian Herold for posting the article.
Simplified example of Nicolai Ehmann's comment and wildloop's answer (Spring 4.3.3+), you can use required = false
now:
@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
if (type != null) {
// ...
}
return new TestBean();
}
$.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 ) {}
참고URL : https://stackoverflow.com/questions/4904092/with-spring-can-i-make-an-optional-path-variable
'IT story' 카테고리의 다른 글
모범 사례 : PHP에서 길고 여러 줄로 된 문자열로 작업합니까? (0) | 2020.05.25 |
---|---|
Mac에서 ssh-copy-id를 어떻게 설치합니까? (0) | 2020.05.25 |
Laravel 4 : Eloquent ORM을 사용하여 "주문"하는 방법 (0) | 2020.05.25 |
오류 : Postgres를 사용하여 city_id_seq 시퀀스에 대한 권한이 거부되었습니다. (0) | 2020.05.25 |
ImeOptions의 완료 버튼 클릭을 어떻게 처리합니까? (0) | 2020.05.25 |