Spring mvc - How to map all wrong request mapping to a single method

天大地大妈咪最大 提交于 2021-02-08 15:01:28

问题


I am using a spring(version 3.2.5) annotation driven mvc application, basically I need be able to catch any wrong url to a single method then display an error message. For instance, if my correct url www.url.valid/login maps to a controller, if the user mistakenly insert loginw or any invalid url it should map to a default controller.

I have tried the following way:

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 kept getting the following error:

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 it please?

Thanks in advance


回答1:


It look like, you want a global page not found handler.

@ControllerAdvice
public class GlobalExceptionContoller {

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

}



回答2:


You can set config at web.xml for invalid url. Note that invalid url usually throw the 404 error page.

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

If it's not enough, you can go your controller method from this error page. But I usually use this config for error page instead of server side code. There have many other alternatives ways depend on your technologies usage but this way can reduce your code.




回答3:


If you define a ExceptionHandler, keep in mind, that the wrong requests like /login/blabla will not throw an NoHandlerFoundException, because the suffix pattern math is activated by default.

Therefore just to define an ExceptionHandler is not enough to catch all wrong requests.

In this case follow these steps:

First step. configure your application to throw an exception for unmapped calls like /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);
    }

    [...]
}

Second step. define exception handler:

@ControllerAdvice
public class GlobalExceptionHandler {

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

}


来源:https://stackoverflow.com/questions/40504501/spring-mvc-how-to-map-all-wrong-request-mapping-to-a-single-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!