您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Spring控制器处理错误404

使用Spring控制器处理错误404

查找最简单的方法是使用以下命令:

@ExceptionHandler(Throwable.class)
  public String handleAnyException(Throwable ex, HttpServletRequest request) {
    return ClassUtils.getShortName(ex.getClass());
  }

如果URL在DispatcherServlet的范围内,则任何由于错误输入或其他原因引起的404都将被此方法捕获,但是如果键入的URL超出DispatcherServlet的URL映射,则你必须使用以下任一方法

<error-page>
   <exception-type>404</exception-type>
   <location>/404error.html</location>
</error-page>

要么

为你的DispatcherServlet映射URL提供“ /”映射,以便处理特定服务器实例的所有映射。

我使用spring 4.0和java配置。我的工作代码是:

@ControllerAdvice
public class MyExceptionController {
    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleError404(HttpServletRequest request, Exception e)   {
            ModelAndView mav = new ModelAndView("/404");
            mav.addObject("exception", e);  
            //mav.addObject("errorcode", "404");
            return mav;
    }
}

在JSP中:

    <div class="http-error-container">
        <h1>HTTP Status 404 - Page Not Found</h1>
        <p class="message-text">The page you requested is not available. You might try returning to the <a href="<c:url value="/"/>">home page</a>.</p>
    </div>

对于初始化参数配置:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    public void customizeRegistration(ServletRegistration.Dynamic registration) {
        registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
    }
}

或通过xml:

<servlet>
    <servlet-name>rest-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>
Java 2022/1/1 18:13:36 有658人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶