SpringMVC异常映射

异常映射

作用

统一管理项目中的异常

  抛出异常

  显示异常

    普通请求:在页面上显示异常信息

    Ajax请求:返回json数据

异常映射的工作机制

SpringMVC异常映射

 

服务器接收到用户请求过程中,如果有异常则抛出异常,SpringMVC的异常映射机制则会判断请求的类型从而响应不同的异常映射请求.

 

判断请求类型的工具方法

判断依据

SpringMVC异常映射

 

创建工具类

/**
 * @Description 判断请求是ajax还是普通请求
 */
public class CrowdUtil {
    /**
     * 判断请求是否是ajax请求
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");
        return ((accept!=null && accept.contains("application/json")) || (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest")));
    }
}

异常映射实现方式

基于xml

步骤:

  • 配置异常解析器
  • 新建自定义异常界面
<!--异常映射-->
    <bean id="simpleMappingExceptionResolver"
          class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
       <!--指定异常类型和逻辑视图名称的对应关系-->
        <property name="exceptionMappings">
            <props>
                <!--
                key表示异常类型
                value表示映射的视图界面
                -->
                <prop key="java.lang.Exception">system-error</prop>
            </props>
        </property>
        <!--使用exceptionAttribute可以修改异常对象存入请求域时使用的属性名-->
        <!--<property name="exceptionAttribute"></property>-->
    </bean>

然后指定映射的jsp页面即可.

 

基于注解

  • 加入gson依赖:处理json数据
  • 创建异常处理类
// @ControllerAdvice,表示这是一个基于注解的 异常处理类
@ControllerAdvice
public class ExceptionResolver {

    // @ExceptionHandler 建立异常和类的映射关系
    @ExceptionHandler(value = ArithmeticException.class)
    public ModelAndView resolverException(ArithmeticException e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 判断请求的类型
        boolean requestType = CrowdUtil.isAjaxRequest(request);

        // 如果是ajax请求
        if (requestType) {
            // 创建ResultEntity
            ResultEntity<Object> failed = ResultEntity.failed(e.getMessage());
            // 创建Gson
            Gson gson = new Gson();
            // 将ResultEntity转为json
            String json = gson.toJson(failed);
            // 将json数据返还给浏览器
            response.getWriter().write(json);
            // 因为使用了原生respones对象返回了响应,不提供ModelAndView对象
            return null;
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("exception", e);
            modelAndView.setViewName("system-error");
            return modelAndView;
        }
    }

    /**
     * 提取可复用部分
     *
     * @return
     */
    public ModelAndView common(String viewName, Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean requestType = CrowdUtil.isAjaxRequest(request);
        if (requestType) {
            ResultEntity<Object> failed = ResultEntity.failed(e.getMessage());

            String json = new Gson().toJson(failed);

            response.getWriter().write(json);
            return null;
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("exception", e);
            modelAndView.setViewName(viewName);
            return modelAndView;
        }
    }

    @ExceptionHandler(LoginFailedException.class)
    public ModelAndView resolverLoginFailedException(LoginFailedException e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String viewName = "/ad-login";
        ModelAndView modelAndView = common(viewName, e, request, response);
        return modelAndView;
    }

    @ExceptionHandler(AccessForbidenException.class)
    public ModelAndView resolverAccessForbiddenException(AccessForbidenException e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String viewName = "/ad-login";
        ModelAndView modelAndView = common(viewName, e, request, response);
        return modelAndView;
    }

    @ExceptionHandler(LoginAccountAlreadlyInUse.class)
    public ModelAndView resolverLoginAccountAlreadlyInUseException(LoginAccountAlreadlyInUse e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String viewName = "/add";
        ModelAndView modelAndView = common(viewName, e, request, response);
        return modelAndView;
    }

    @ExceptionHandler(LoginAccountAlreadlyInUseForUpdate.class)
    public ModelAndView resolverLoginAccountAlreadlyInUseForUpdateException(LoginAccountAlreadlyInUseForUpdate e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String viewName = "system-error";
        ModelAndView modelAndView = common(viewName, e, request, response);
        return modelAndView;
    }
}

 

  

 

上一篇:初探SpringMVC


下一篇:SpringBoot中处理的转发与重定向