![](/img/trans.png)
[英]How to handle 404 error in spring MVC using Controller Advice
[英]Handle error 404 with Spring controller
我使用@ExceptionHandler
來處理Web應用程序引發的異常,在這種情況下,我的應用程序將返回HTTP status
JSON
響應以返回給客戶端。
但是,我試圖弄清楚如何處理error 404
以返回類似的JSON響應,就像@ExceptionHandler
處理的@ExceptionHandler
更新:
我的意思是,當訪問不存在的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>
對於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();
}
}
}
查找最簡單的方法是使用以下命令:
@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提供“ /”映射,以便處理特定服務器實例的所有映射。
public final class ResourceNotFoundException extends RuntimeException {
}
@ControllerAdvice
public class AppExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleNotFound() {
return "404";
}
}
只需定義一個Exception,一個ExceptionHandler,從您的業務代碼控制器中拋出該Exception。
您可以使用servlet標准方式來處理404錯誤。 在web.xml
添加以下代碼
<error-page>
<exception-type>404</exception-type>
<location>/404error.html</location>
</error-page>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.