3

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

3 Answers3

1

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.

mad_fox
  • 3,030
  • 5
  • 31
  • 43
1

It is not possible to handle wrong context path requests in Spring since it only will handle the requests which goes to your context root. You have to take a look at server configuration parameters to redirect those kind of requests. If you are working on Tomcat, check path parameter of context.xml: https://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Defining_a_context

okante
  • 97
  • 2
  • 11
-1

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");
    }
Barath
  • 5,093
  • 1
  • 17
  • 42