簡體   English   中英

Spring Boot Rest - 如何配置 404 - 找不到資源

[英]Spring Boot Rest - How to configure 404 - resource not found

我有一個工作彈簧靴休息服務。 當路徑錯誤時,它不會返回任何內容。 完全沒有反應。 同時它也不會拋出錯誤。 理想情況下,我預計會出現 404 not found 錯誤。

我有一個 GlobalErrorHandler

@ControllerAdvice
public class GlobalErrorHandler extends ResponseEntityExceptionHandler {

}

ResponseEntityExceptionHandler中有這個方法

protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
                                                     HttpStatus status, WebRequest request) {

    return handleExceptionInternal(ex, null, headers, status, request);
}

我在我的屬性中標記error.whitelabel.enabled=false

我還必須做什么才能讓此服務向客戶端拋出 404 not found 響應

我參考了很多線程,沒有看到任何人面臨這個麻煩。

這是我的主要應用程序類

 @EnableAutoConfiguration // Sprint Boot Auto Configuration
@ComponentScan(basePackages = "com.xxxx")
@EnableJpaRepositories("com.xxxxxxxx") // To segregate MongoDB
                                                        // and JPA repositories.
                                                        // Otherwise not needed.
@EnableSwagger // auto generation of API docs
@SpringBootApplication
@EnableAspectJAutoProxy
@EnableConfigurationProperties

public class Application extends SpringBootServletInitializer {

    private static Class<Application> appClass = Application.class;

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(appClass).properties(getProperties());

    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public FilterRegistrationBean correlationHeaderFilter() {
        FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
        filterRegBean.setFilter(new CorrelationHeaderFilter());
        filterRegBean.setUrlPatterns(Arrays.asList("/*"));

        return filterRegBean;
    }

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    static Properties getProperties() {
        Properties props = new Properties();
        props.put("spring.config.location", "classpath:/");
        return props;
    }

    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
        WebMvcConfigurerAdapter webMvcConfigurerAdapter = new WebMvcConfigurerAdapter() {
            @Override
            public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
                configurer.favorPathExtension(false).favorParameter(true).parameterName("media-type")
                        .ignoreAcceptHeader(false).useJaf(false).defaultContentType(MediaType.APPLICATION_JSON)
                        .mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
            }
        };
        return webMvcConfigurerAdapter;
    }

    @Bean
    public RequestMappingHandlerMapping defaultAnnotationHandlerMapping() {
        RequestMappingHandlerMapping bean = new RequestMappingHandlerMapping();
        bean.setUseSuffixPatternMatch(false);
        return bean;
    }
}

解決方案非常簡單:

首先,您需要實現將處理所有錯誤情況的控制器。 此控制器必須具有@ControllerAdvice - 需要定義適用於所有@RequestMappings@ExceptionHandler

@ControllerAdvice
public class ExceptionHandlerController {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(value= HttpStatus.NOT_FOUND)
    @ResponseBody
    public ErrorResponse requestHandlingNoHandlerFound() {
        return new ErrorResponse("custom_404", "message for 404 error code");
    }
}

@ExceptionHandler中提供要覆蓋響應的異常。 NoHandlerFoundException是當 Spring 無法委托請求時將生成的異常(404 情況)。 您還可以指定Throwable來覆蓋任何異常。

其次,您需要告訴 Spring 在 404 的情況下拋出異常(無法解析處理程序):

@SpringBootApplication
@EnableWebMvc
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        DispatcherServlet dispatcherServlet = (DispatcherServlet)ctx.getBean("dispatcherServlet");
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    }
}

當我使用未定義的 URL 時的結果

{
    "errorCode": "custom_404",
    "errorMessage": "message for 404 error code"
}

更新:如果您使用application.properties配置 SpringBoot 應用程序,則需要添加以下屬性,而不是在 main 方法中配置DispatcherServlet (感謝@mengchengfeng):

spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false

我知道這是一個老問題,但這是另一種在代碼中而不是在主類中配置DispatcherServlet的方法。 您可以使用單獨的@Configuration類:

@EnableWebMvc
@Configuration
public class ExceptionHandlingConfig {

    @Autowired
    private DispatcherServlet dispatcherServlet;

    @PostConstruct
    private void configureDispatcherServlet() {
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    }
}

請注意,如果沒有@EnableWebMvc注釋,這將不起作用。

  1. 將此添加到您的屬性文件中。

     spring: mvc: throw-exception-if-no-handler-found: true web: resources: add-mappings: false
  2. 在您的@ControllerAdvice類中添加以下內容:

     @ExceptionHandler(NoHandlerFoundException.class) public ResponseEntity<Object> handleNoHandlerFound404() { return new ResponseEntity<>(HttpStatus.BAD_REQUEST);; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM