[java] Spring-MVC 컨트롤러에서 트리거 404?

Spring 3.0 컨트롤러가 404를 트리거하도록하려면 어떻게해야 합니까?

컨트롤러가 있고 컨트롤러에 액세스하는 @RequestMapping(value = "/**", method = RequestMethod.GET)일부 URL의 경우 컨테이너에 404가 필요합니다.



답변

Spring 3.0부터 @ResponseStatus주석으로 선언 된 예외를 던질 수 있습니다 .

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    ...
}

@Controller
public class SomeController {
    @RequestMapping.....
    public void handleCall() {
        if (isFound()) {
            // whatever
        }
        else {
            throw new ResourceNotFoundException();
        }
    }
}


답변

Spring 5.0부터 추가 예외를 만들 필요는 없습니다.

throw new ResponseStatusException(NOT_FOUND, "Unable to find resource");

또한 하나의 기본 제공 예외로 여러 시나리오를 처리 할 수 ​​있으며 더 많은 제어가 가능합니다.

더보기:


답변

메소드 서명 HttpServletResponse이 매개 변수로 승인 되도록 호출 setStatus(int)하여 호출 할 수 있도록 다시 작성하십시오 .

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments


답변

Spring에서 제공하는 기본적으로 404에 대한 예외가 있음을 언급하고 싶습니다. 자세한 내용은 Spring 설명서 를 참조하십시오. 따라서 자신의 예외가 필요하지 않은 경우 간단히 다음을 수행 할 수 있습니다.

 @RequestMapping(value = "/**", method = RequestMethod.GET)
 public ModelAndView show() throws NoSuchRequestHandlingMethodException {
    if(something == null)
         throw new NoSuchRequestHandlingMethodException("show", YourClass.class);

    ...

  }


답변

Spring 3.0.2부터 컨트롤러 메소드의 결과로 ResponseEntity <T> 를 반환 할 수 있습니다 .

@RequestMapping.....
public ResponseEntity<Object> handleCall() {
    if (isFound()) {
        // do what you want
        return new ResponseEntity<>(HttpStatus.OK);
    }
    else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

(ResponseEntity <T>는 @ResponseBody 주석보다 더 유연합니다. 다른 질문을 참조하십시오 )


답변

@ControllerAdvice 를 사용하여 예외를 처리 할 수 있습니다. @ControllerAdvice 주석 클래스의 기본 동작은 알려진 모든 컨트롤러를 지원합니다.

따라서 404 오류가 발생하면 컨트롤러가 호출됩니다.

다음과 같이 :

@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.NOT_FOUND)  // 404
    @ExceptionHandler(Exception.class)
    public void handleNoTFound() {
        // Nothing to do
    }
}

web.xml에이 404 응답 오류를 다음과 같이 매핑하십시오.

<error-page>
        <error-code>404</error-code>
        <location>/Error404.html</location>
</error-page>

희망이 도움이됩니다.


답변

컨트롤러 방법이 파일 처리와 같은 것이면 ResponseEntity매우 편리합니다.

@Controller
public class SomeController {
    @RequestMapping.....
    public ResponseEntity handleCall() {
        if (isFound()) {
            return new ResponseEntity(...);
        }
        else {
            return new ResponseEntity(404);
        }
    }
}