[英]Is it possible to add a “404 page not found” to my Spring Boot Controller class?
我想在我的Spring應用程序中添加404錯誤頁面,但是我找不到有關如何執行操作的文檔/建議。 目前,我僅通過Eclipse在本地運行該應用程序。 根據我對Spring Applications的理解,可能有兩種方法可以做到這一點。
在控制器類中的方法中輸入一個接受某種條件的方法,該方法的@RequestMapping
值將在無法識別URL的情況下打開404頁面,例如localhost/sdksdjhfkjsdkjfsdkj
。 我用@ResponseStatus
嘗試了下面的方法, @ResponseStatus
它不起作用。 當我嘗試包含@RequestMapping
時會提示錯誤,但我僅在下面包含它,以使您了解我要實現的目標。
@RequestMapping(value = HttpStatus.NOT_FOUND) public String pageNotFound() { return "404"; }
向我的Web配置類中添加某種HTTPSecurity
方法,如果沒有URL與用戶輸入的URL相匹配,該方法將加載404頁面。 我將在下面提供我的configure方法的示例。
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/resources/**", "/registration").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); //Disable csrf token as it is not needed for now and is preventing the applciation from running properly http.csrf().disable();
}
但是,我在HTTPSecurity
文檔中找不到此方法。
有沒有人建議我完成此任務?
如果沒有用於請求的資源(URL)的處理程序,則DispatcherServlet將引發NoHandlerFoundException。 您可以在ExceptionTranslator中捕獲異常,並返回所需的任何響應。 例如:
@ControllerAdvice
public class ExceptionTranslator {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseBody
public ResponseEntity<ErrorVM> processNoHandlerFoundException(NoHandlerFoundException ex) {
return new ResponseEntity();
}
}
您可以基於springframework api向響應實體添加狀態和消息: https : //docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.