如何在 spring MVC 3.0 中包含错误页面?
how to include error page in spring MVC 3.0?
如何在 spring MVC 3.0 中包含错误页面?
如何在异常发生时显示错误页面。
<http auto-config="true">
<access-denied-handler ref="my403" />
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
</http>
<beans:bean id="my403" class="com.mkyong.web.exception.MyAccessDeniedHandler">
<beans:property name="errorPage" value="403" />
</beans:bean>
请参阅 Whosebug 上的 this thread 或使用 @ControllerAdvice
。
您可以很容易地构建自己的错误控制器:
@ControllerAdvice
public class ExceptionHandlingController {
public static final String DEFAULT_ERROR_VIEW = "generalError";
final String NEW_LINE = System.getProperty("line.separator");
StringBuilder stackTraceString = new StringBuilder("");
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception exception) {
//System.out.println("Request: " + req.getRequestURL() + " raised " + exception);
ModelAndView mav = new ModelAndView(DEFAULT_ERROR_VIEW);
mav.addObject("errorMessage", exception.getMessage());
for (StackTraceElement element : exception.getStackTrace() ){
stackTraceString.append( element );
stackTraceString.append( NEW_LINE );
}
mav.addObject("stackTrace", stackTraceString);
mav.addObject("url", req.getRequestURL());
return mav;
}
}
如何在 spring MVC 3.0 中包含错误页面? 如何在异常发生时显示错误页面。
<http auto-config="true">
<access-denied-handler ref="my403" />
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
</http>
<beans:bean id="my403" class="com.mkyong.web.exception.MyAccessDeniedHandler">
<beans:property name="errorPage" value="403" />
</beans:bean>
请参阅 Whosebug 上的 this thread 或使用 @ControllerAdvice
。
您可以很容易地构建自己的错误控制器:
@ControllerAdvice
public class ExceptionHandlingController {
public static final String DEFAULT_ERROR_VIEW = "generalError";
final String NEW_LINE = System.getProperty("line.separator");
StringBuilder stackTraceString = new StringBuilder("");
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception exception) {
//System.out.println("Request: " + req.getRequestURL() + " raised " + exception);
ModelAndView mav = new ModelAndView(DEFAULT_ERROR_VIEW);
mav.addObject("errorMessage", exception.getMessage());
for (StackTraceElement element : exception.getStackTrace() ){
stackTraceString.append( element );
stackTraceString.append( NEW_LINE );
}
mav.addObject("stackTrace", stackTraceString);
mav.addObject("url", req.getRequestURL());
return mav;
}
}