@ControllerAdvice的使用

这是一个增强的 Controller。使用这个 Controller ,可以实现三个方面的功能:

  • 全局异常处理
  • 全局数据绑定
  • 全局数据预处理

标题全局异常处理

package com.czr.crowd.mvc.config;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.czr.crowd.util.CrowdUtil;
import com.czr.crowd.util.ResultEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;


import com.google.gson.Gson;

// @ControllerAdvice表示当前类是一个基于注解的异常处理器类
@ControllerAdvice
public class CrowdExceptionResolver {
	
	@ExceptionHandler(value = ArithmeticException.class)
	public ModelAndView resolveMathException(
				ArithmeticException exception,
				HttpServletRequest request,
				HttpServletResponse response
			) throws IOException {

		String viewName = "error";

		return commonResolve(viewName, exception, request, response);
	}
	@ExceptionHandler(value = NullPointerException.class)
	public ModelAndView resolveNullPointerException(
			NullPointerException exception, 
			HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		String viewName = "error";

		return commonResolve(viewName, exception, request, response);
	}

	
	// @ExceptionHandler将一个具体的异常类型和一个方法关联起来
	private ModelAndView commonResolve(
			
			// 异常处理完成后要去的页面
			String viewName, 
			
			// 实际捕获到的异常类型
			Exception exception, 
			
			// 当前请求对象
			HttpServletRequest request, 
			
			// 当前响应对象
			HttpServletResponse response) throws IOException {
		
		// 1.判断当前请求类型
		boolean judgeResult = CrowdUtil.judgeRequestType(request);
		
		// 2.如果是Ajax请求
		if(judgeResult) {
			
			// 3.创建ResultEntity对象
			ResultEntity<Object> resultEntity = ResultEntity.failed(exception.getMessage());
			
			// 4.创建Gson对象
			Gson gson = new Gson();
			
			// 5.将ResultEntity对象转换为JSON字符串
			String json = gson.toJson(resultEntity);
			
			// 6.将JSON字符串作为响应体返回给浏览器
			response.getWriter().write(json);
			
			// 7.由于上面已经通过原生的response对象返回了响应,所以不提供ModelAndView对象
			return null;
		}
		
		// 8.如果不是Ajax请求则创建ModelAndView对象
		ModelAndView modelAndView = new ModelAndView();
		
		// 9.将Exception对象存入模型
		modelAndView.addObject("exception", exception);
		
		// 10.设置对应的视图名称
		modelAndView.setViewName(viewName);
		
		// 11.返回modelAndView对象
		return modelAndView;
	}

}

判断当前请求是否为Ajax请求

public class CrowdUtil {

    /**
     * 判断当前请求是否为Ajax请求
     * @param request 请求对象
     * @return
     * 		true:当前请求是Ajax请求
     * 		false:当前请求不是Ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {

        // 1.获取请求消息头
        String acceptHeader = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");

        // 2.判断
        return (acceptHeader != null && acceptHeader.contains("application/json"))
                ||
                (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest"));
    }

}

json统一返回

/**
 * json统一返回
 * @param <T>
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResultEntity<T> {

    public static final Integer SUCCESS = 2000;
    public static final Integer FAILED = 5000;

    // 返回状态码成功还是失败
    private Integer code;
    // 请求处理失败时返回错误消息
    private String message;
    // 要返回的数据
    private T data;

    /**
     * 请求处理成功且需要返回数据
     * @param data 要返回的数据
     * @param <Type>
     * @return
     */
    public static <Type> ResultEntity<Type> successWithData(Type data){
        return new ResultEntity<Type>(SUCCESS, "成功", data);
    }

    /**
     * 请求成功不返回数据
     * @param <Type>
     * @return
     */
    public static <Type> ResultEntity<Type> successWith(){
        return new ResultEntity<Type>(SUCCESS, "成功", null);
    }

    /**
     * 请求失败
     * @param message 失败的错误信息
     * @param <Type>
     * @return
     */
    public static <Type> ResultEntity<Type> failed(String message){
        return new ResultEntity<Type>(SUCCESS, message, null);
    }



}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值