1

I tried to implement a filter following this answer:

How do I minify dynamic HTML responses in Spring?

This works very good, however, this filter does not work when the error 404 is thrown. Why not? And how do I apply this filter also for my 404-error page?

Solution:

Using the following code:

@ControllerAdvice
@Order(HIGHEST_PRECEDENCE)
public class NotFoundException {

     @ExceptionHandler(NoHandlerFoundException.class)
     public String noHandlerFoundException() {
          // provide information to view
          return "error";
     }
}

with the application.properties:

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

allows the redirection to the error page and the filter is applied. However, the warning: "No mapping for GET /css/styles.css" (and all other static resources) is logged. Registering a ResourceHandler with:

 resourceHandlerRegistry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
 // register resource handler for other static content

solved this. See also issues: #7653 (spring-boot) and #29491 (spring-framework) in the spring-projects, which seem related. Thank you!

manu
  • 556
  • 2
  • 9
  • 29

1 Answers1

1

A 404 is not a “normal“ exception type error in Spring Boot.

To turn it into a handleable exception add the following to application.properties

spring.mvc.throw-exception-if-no-handler-found=true

This may be sufficient to cause the minify filter to be hit.

Otherwise add an exception handler for the not found to apply the CharResponseWrapper or other mechanism to provide minified response.

manu
  • 556
  • 2
  • 9
  • 29
John Williams
  • 4,252
  • 2
  • 9
  • 18
  • An example of implementing the exception handler is linked to from my answer. Also look at this question and answer https://stackoverflow.com/questions/49167033/custom-exception-handler-for-nohandlerfoundexception-is-not-working-without-ena – John Williams Mar 19 '23 at 09:07
  • Look at this question and answer https://stackoverflow.com/questions/49167033/custom-exception-handler-for-nohandlerfoundexception-is-not-working-without-ena – John Williams Mar 19 '23 at 09:12
  • Use the @ExceptionHandler handleError that has the http response as one of the params. Populate ‘text’ with the text contained in error.html. response.getWriter().write(htmlCompressor.compress(text)); – John Williams Mar 19 '23 at 15:28
  • The fact that static files are not serving is a separate (simpler) issue. Please ask another question and accept my answer - solved your issue with manipulating 404 response. – John Williams Mar 19 '23 at 20:28