简体   繁体   English

使用Spring控制器处理错误404

[英]Handle error 404 with Spring controller

I use @ExceptionHandler to handle exceptions thrown by my web app, in my case my app returns JSON response with HTTP status for error responses to the client. 我使用@ExceptionHandler来处理Web应用程序引发的异常,在这种情况下,我的应用程序将返回HTTP status JSON响应以返回给客户端。

However, I am trying to figure out how to handle error 404 to return a similar JSON response like with the one handled by @ExceptionHandler 但是,我试图弄清楚如何处理error 404以返回类似的JSON响应,就像@ExceptionHandler处理的@ExceptionHandler

Update: 更新:

I mean, when a URL that does not exist is accessed 我的意思是,当访问不存在的URL时

I use spring 4.0 and java configuration. 我使用spring 4.0和java配置。 My working code is: 我的工作代码是:

@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;
    }
}

In JSP: 在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>

For Init param config: 对于初始化参数配置:

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

Or via xml: 或通过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>

See Also: Spring MVC Spring Security and Error Handling 另请参阅: Spring MVC Spring安全性和错误处理

With spring > 3.0 use @ResponseStatus 对于spring> 3.0,请使用@ResponseStatus

  @ResponseStatus(value = HttpStatus.NOT_FOUND)
  public class ResourceNotFoundException extends RuntimeException {
    ...
}

    @Controller
    public class MyController {
    @RequestMapping.....
    public void handleCall() {
        if (isFound()) {
        // do some stuff
        }
        else {
              throw new ResourceNotFoundException(); 
        }
    }
}

Simplest way to find out is use the following: 查找最简单的方法是使用以下命令:

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

If the URL is within the scope of DispatcherServlet then any 404 caused by mistyping or anything else will be caught by this method but if the URL typed is beyond the URL mapping of the DispatcherServlet then you have to either use: 如果该URL在DispatcherServlet的范围内,则该方法将捕获由错误或其他任何原因引起的404,但是如果键入的URL超出DispatcherServlet的URL映射,则您必须使用以下任一方法:

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

or 要么

Provide "/" mapping to your DispatcherServlet mapping URL so as to handle all the mappings for the particular server instance. 为您的DispatcherServlet映射URL提供“ /”映射,以便处理特定服务器实例的所有映射。

public final class ResourceNotFoundException extends RuntimeException {

}


@ControllerAdvice
public class AppExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleNotFound() {
        return "404";
    }
}

Just define an Exception, an ExceptionHandler, throw the Exception from your business code controller. 只需定义一个Exception,一个ExceptionHandler,从您的业务代码控制器中抛出该Exception。

You can use servlet standard way to handle 404 error. 您可以使用servlet标准方式来处理404错误。 Add following code in web.xml web.xml添加以下代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM