Reputation: 224
I have been learning Spring for just 7 months. While I used spring MVC only, i want to configure custom 404 page by throwing NoHandlerFoundException or enabling it in the dispatcher servlet. Now, i am learning spring boot, can anyone explain to me?
Upvotes: 1
Views: 3354
Reputation: 3543
I had the same issue, got it resolved. Below given steps to solve the same.
GlobalExceptionHandler
annotated with @ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler
{
@ExceptionHandler(NoHandlerFoundException.class)
public String handleNotFoundError(Exception ex)
{
return "redirect:/yourCustom404page";
}
}
DispatcherServlet
to throw the exception if no handler is found. We can do this by setting the throwExceptionIfNoHandlerFound
servlet initialization parameter to true
to achieve this
a. In spring-boot
spring.resources.add-mappings=false
in your application.properties or yaml file.
b. If spring-mvc java based configuration is
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
...
@Override
protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext)
{
final DispatcherServlet servlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
servlet.setThrowExceptionIfNoHandlerFound(true);
return servlet;
}
}
c. if spring-mvc xml based configuration, initialize your dispatcher servlet like this
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
Upvotes: 1