xyb*_*rek 13 java spring spring-mvc
我@ExceptionHandler
用来处理我的网络应用程序抛出的异常,在我的情况下,我的应用程序返回JSON
响应,HTTP status
以便对客户端进行错误响应.
但是,我试图弄清楚如何处理error 404
以返回类似的JSON响应,就像处理的那样@ExceptionHandler
更新:
我的意思是,当访问不存在的URL时
Md.*_*man 42
我使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
在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>
Run Code Online (Sandbox Code Playgroud)
对于Init param配置:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
}
Run Code Online (Sandbox Code Playgroud)
或者通过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>
Run Code Online (Sandbox Code Playgroud)
另请参见: Spring MVC Spring安全性和错误处理
使用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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
最简单的查找方法是使用以下内容:
@ExceptionHandler(Throwable.class)
public String handleAnyException(Throwable ex, HttpServletRequest request) {
return ClassUtils.getShortName(ex.getClass());
}
Run Code Online (Sandbox Code Playgroud)
如果 URL 在 DispatcherServlet 的范围内,则此方法将捕获由错误输入或其他任何原因引起的任何 404,但如果输入的 URL 超出 DispatcherServlet 的 URL 映射,则必须使用:
<error-page>
<exception-type>404</exception-type>
<location>/404error.html</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)
或者
提供到 DispatcherServlet 映射 URL 的“/”映射,以便处理特定服务器实例的所有映射。
归档时间: |
|
查看次数: |
42940 次 |
最近记录: |