springmvc中的异常处理(跳转到异常页面)

it2023-10-09  72

springmvc中的异常处理

在springmvc中页面经常会出现一些异常,如404、403、500,这些错误不应展现给使用者,所以要处理这些错误信息,每一个错误代码都应该对应一个错误页面。处理方式1: 用springmvc自己的处理机制,即是在web.xml文件中指定错误代码应该跳转的页面: <error-page> <error-code>403</error-code> <location>/403.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/404.jsp</location> </error-page> 处理方式2: 写一个处理异常的类,去实现HandlerExceptionResolver这个接口,重写方法resolveException,具体代码如下(注意if-else可用多分支,根据自己的需求) public class ControllerExceptionAdvice implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView mv = new ModelAndView(); if (e instanceof AccessDeniedException) { mv.setViewName("forward:/403.jsp"); }else { mv.setViewName("forward:/505.jsp"); } return mv; } }

这种方法还可以用注解的方法简化:(建议使用)

import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ExceptionAdvice { @ExceptionHandler(AccessDeniedException.class) public String advice1(){ // return "redirect:/403.jsp"; return "forward:/403.jsp"; } } 处理方式3:在spring security中配置 <security:access-denied-handler error-page="/403.jsp"/>
最新回复(0)