简体   繁体   中英

Is it possible to add a “404 page not found” to my Spring Boot Controller class?

I'm looking to add a 404 error page to my Spring Application but I'm having trouble finding documentation/advice on how to do so. I'm only running the application locally for the moment through Eclipse. From my understanding of Spring Applications there are possibly 2 ways of doing this.

  1. Enter a method in the controller class that accepts some sort of condition into it's @RequestMapping value that will open the 404 page if it cannot recognise the URL, for example, localhost/sdksdjhfkjsdkjfsdkj . I tried the method below with @ResponseStatus and it didn't work. An error is prompted when I try to include @RequestMapping but I'm just including it below to give you an idea of what I am trying to achieve.

     @RequestMapping(value = HttpStatus.NOT_FOUND) public String pageNotFound() { return "404"; } 
  2. Add some sort of HTTPSecurity method to my web config class that will load the 404 page if no URLs match the one entered by the user. I will include an example of my configure method below.

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

    }

However I cannot find any methods in the HTTPSecurity documentation for this.

Does anyone have any suggestions or documentation I could look at to complete this task?

The DispatcherServlet will throw a NoHandlerFoundException if there is no handler for the requested resource(URL). You can catch the exception in an ExceptionTranslator and return whatever response you want. For example:

@ControllerAdvice
public class ExceptionTranslator {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public ResponseEntity<ErrorVM> processNoHandlerFoundException(NoHandlerFoundException ex) {
        return new ResponseEntity();
    }
}

You can a add status and message to the response entity based on the springframework api: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM