itsource

스프링-MVC 컨트롤러에서 404를 트리거합니까?

mycopycode 2022. 8. 19. 21:03
반응형

스프링-MVC 컨트롤러에서 404를 트리거합니까?

Spring 3.0 컨트롤러로 404를 트리거하려면 어떻게 해야 하나요?

컨트롤러가 있습니다.@RequestMapping(value = "/**", method = RequestMethod.GET)그리고 컨트롤러에 접속하는 URL에 대해서는 컨테이너에 404를 준비해 주셨으면 합니다.

Spring 3.0 이후 주석으로 선언된 예외도 던질 수 있습니다.

@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");

또, 1개의 빌트인 예외로 복수의 시나리오를 커버할 수 있기 때문에, 보다 많은 컨트롤이 가능합니다.

더:

메서드 시그니처를 고쳐 쓰고,HttpServletResponse파라미터로서 호출할 수 있습니다.setStatus(int)그 위에 올려놔요.

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

Spring이 제공하는 디폴트로는 404에 대한 예외가 있다는 것을 언급하고 싶습니다.자세한 내용은 스프링 설명서를 참조하십시오.따라서 자신의 예외가 필요하지 않은 경우 다음과 같이 간단히 수행할 수 있습니다.

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

    ...

  }

Spring 3.0.2 이후 Response Entity를 반환할 수 있습니다.<T> 컨트롤러 방식의 결과:

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

(Response Entity<T>는 @ResponseBody 주석보다 유연합니다.다른 질문을 참조해 주세요.

@ControllerAdvice를 사용하여 예외를 처리할 수 있습니다.@ControllerAdvice 주석이 달린 클래스는 이미 알려진 모든 컨트롤러를 지원합니다.

따라서 가지고 있는 컨트롤러 중 하나가 404 오류를 발생시키면 호출됩니다.

다음과 같습니다.

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

이 404 응답 오류를 web.xml에 매핑합니다.다음은 예를 제시하겠습니다.

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

도움이 되길 바랍니다.

표시된 답변은 맞지만 예외 없이 이를 달성할 수 있는 방법이 있습니다.서비스가 되돌아오고 있습니다.Optional<T>검색된 오브젝트 중 하나이며, 이는 에 매핑됩니다.HttpStatus.OK발견된 경우 404로, 비어 있는 경우 404로 이동합니다.

@Controller
public class SomeController {

    @RequestMapping.....
    public ResponseEntity<Object> handleCall(@PathVariable String param) {
        return  service.find(param)
                .map(result -> new ResponseEntity<>(result, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
}

@Service
public class Service{
  
    public Optional<Object> find(String param){
        if(!found()){
            return Optional.empty();
        }
        ...
        return Optional.of(data); 
    }
    
}

컨트롤러 방식이 파일 처리와 같은 용도로 사용되는 경우ResponseEntity매우 편리합니다.

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

HttpClientErrorException을 다음과 같이 던질 것을 권장합니다.

@RequestMapping(value = "/sample/")
public void sample() {
    if (somethingIsWrong()) {
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
    }
}

이 작업은 서블릿 출력 스트림에 쓰기 전에만 수행할 수 있습니다.

좀 늦은 감이 있지만 Spring Data REST를 사용하는 경우 이미org.springframework.data.rest.webmvc.ResourceNotFoundException, 「」를 사용합니다.@ResponseStatus예외를 .더 이상 사용자 지정 런타임 예외를 만들 필요가 없습니다.

또한 컨트롤러에서 404 상태를 반환하려면 이 작업만 수행하면 됩니다.

@RequestMapping(value = "/something", method = RequestMethod.POST)
@ResponseBody
public HttpStatus doSomething(@RequestBody String employeeId) {
    try {
        return HttpStatus.OK;
    } 
    catch (Exception ex) { 
         return HttpStatus.NOT_FOUND;
    }
}

이렇게 하면 컨트롤러에서 404를 반환할 경우 404 오류가 발생합니다.

설정을 사용하여 web.xml을 구성합니다.

<error-page>
    <error-code>500</error-code>
    <location>/error/500</location>
</error-page>

<error-page>
    <error-code>404</error-code>
    <location>/error/404</location>
</error-page>

새 컨트롤러 생성

   /**
     * Error Controller. handles the calls for 404, 500 and 401 HTTP Status codes.
     */
    @Controller
    @RequestMapping(value = ErrorController.ERROR_URL, produces = MediaType.APPLICATION_XHTML_XML_VALUE)
    public class ErrorController {


        /**
         * The constant ERROR_URL.
         */
        public static final String ERROR_URL = "/error";


        /**
         * The constant TILE_ERROR.
         */
        public static final String TILE_ERROR = "error.page";


        /**
         * Page Not Found.
         *
         * @return Home Page
         */
        @RequestMapping(value = "/404", produces = MediaType.APPLICATION_XHTML_XML_VALUE)
        public ModelAndView notFound() {

            ModelAndView model = new ModelAndView(TILE_ERROR);
            model.addObject("message", "The page you requested could not be found. This location may not be current.");

            return model;
        }

        /**
         * Error page.
         *
         * @return the model and view
         */
        @RequestMapping(value = "/500", produces = MediaType.APPLICATION_XHTML_XML_VALUE)
        public ModelAndView errorPage() {
            ModelAndView model = new ModelAndView(TILE_ERROR);
            model.addObject("message", "The page you requested could not be found. This location may not be current, due to the recent site redesign.");

            return model;
        }
}

같은 일을 적어도 10가지 방법은 항상 가지고 있는 것이 좋기 때문입니다.

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class Something {
    @RequestMapping("/path")
    public ModelAndView somethingPath() {
        return new ModelAndView("/", HttpStatus.NOT_FOUND);
    }
}

단순히 web.xml을 사용하여 오류 코드와 404 오류 페이지를 추가할 수 있습니다.단, 404 에러 페이지가 WEB-INF 아래에 표시되지 않도록 해 주세요.

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

이것이 가장 간단한 방법이지만 약간의 제한이 있다.다른 페이지를 추가한 페이지와 동일한 유형을 이 페이지에 추가하려고 합니다.이 방법으로는 당신은 그것을 할 수 없다. 하다를 요.@ResponseStatus(value = HttpStatus.NOT_FOUND)

언급URL : https://stackoverflow.com/questions/2066946/trigger-404-in-spring-mvc-controller

반응형