Spring mvc - How to map all incorrect query mappings to a single method

I am using mvc application with spring annotation support (version 3.2.5), basically I need to catch any wrong url for one method and then display an error message. For example, if my correct one url www.url.valid/loginmaps to the controller, if the user mistakenly inserts loginw or any invalid URL, it should map to the default controller.

I tried as follows:

package com.controller;

import static com.mns.utils.Constants.REGISTER_FAIL;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class DefaultSpringController {

      @RequestMapping
      public String forwardRequest(final HttpServletRequest request) {
         return "redirect:/" + REGISTER_FAIL;
      }

}

My application context is as follows:

    <!-- Default to DefaultSpringController -->
     <bean id="defaultSpringController"  class="com.controller.DefaultSpringController">
     </bean>

  <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="defaultHandler" ref="defaultSpringController"/>
  </bean

But the following error persisted:

nested exception is java.lang.ClassNotFoundException: com.controller.DefaultSpringController

I am not sure what I am missing here and the controller is in the correct package.

Any idea how I can achieve this, please?

Thanks in advance

+4
3

, , .

@ControllerAdvice
public class GlobalExceptionContoller {

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handleError404(HttpServletRequest request, Exception e) {
        return "pageNotFoundViewNameGoesHere";
    }

}
+5

web.xml url. , url 404.

<error-page>
        <error-code>404</error-code>
        <location>/error/error.jsp</location>
    </error-page>

, . . , , .

+2

ExceptionHandler, , , /login/blabla, NoHandlerFoundException, .

ExceptionHandler , .

:

. /login/blabla (SuffixPattern + TrailingSlashMatch):

@Configuration
public class WebAppMainConfiguration extends WebMvcConfigurerAdapter {  

    @Override 
    public void configurePathMatch(PathMatchConfigurer configurer) {
        // will throw NoHandlerFoundException
        configurer.setUseSuffixPatternMatch(false);
        configurer.setUseTrailingSlashMatch(false);
    }

    [...]
}

. define :

@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public Object handleException(NoHandlerFoundException ex, HttpServletRequest request) {
        [...]
        ex.printStackTrace();
        return "error";
    }

}
+1

Source: https://habr.com/ru/post/1660275/


All Articles