Spring MVC: how to handle incoming request to wrong context path

Viewed 812

How do we handle incoming request to a wrong contextpath in spring mvc?

I have deployed a spring mvc application having contextpath as

http://exampledomain.com/mycontext

But when I try accessing url http://exampledomain.com/wrongcontext I get error as HTTP Status 404 - /wrongcontext/

I have implemented error handling which works fine for all wrong url when correct context path is used but it does not work for wrong context path.

I am trying to understand how do we redirect all incoming request to specific page in production environment..

thanks in advance

3 Answers

Your application can only see requests to its context /mycontext There is nothing your application can do about requests to other contexts.

You can however deploy an application at the root context / and implement an error handler there.

Check out this answer: How to customize JBoss AS7 404 page

That answer relates to JBoss, but the same idea will apply on other servers.

We can use @ExceptionHandler inside a @Controller or @ControllerAdvice to handle such kind of exceptions and decide on the view page to be rendered.

@ExceptionHandler({ HttpRequestMethodNotSupportedException.class,
        HttpMediaTypeNotSupportedException.class, HttpMediaTypeNotAcceptableException.class,
        MissingPathVariableException.class, MissingServletRequestParameterException.class,
        ServletRequestBindingException.class,MethodArgumentNotValidException.class, MissingServletRequestPartException.class, 
        NoHandlerFoundException.class})
    public ModelAndView handleException(){
        return new ModelAndView("errorpage");
    }
Related