SpringMVC框架学习---SpringMVC之异常的处理机制@ControllerAdvice及@ExceptionHandler以及重定向参数传递flash属性

SpringMVC框架学习—SpringMVC之异常的处理机制@ControllerAdvice及@ExceptionHandler以及重定向参数传递flash属性

1. 异常的处理机制

  1. 局部controller有效
// SpringMVC的异常处理机制(异常处理器)
// 注意:写在这里只会对当前controller类生效
@ExceptionHandler(ArithmeticException.class)
public void handleException(ArithmeticException exception, HttpServletResponse response) {
    // 异常处理逻辑
    try {
        response.getWriter().write(exception.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1. 全局有效
/**
 * 可以让我们优雅的捕获所有Controller对象handler方法抛出的异常
 * @author apple
 */
@ControllerAdvice
public class GlobalExceptionResolver {

	//这个是只针对ArithmeticException异常的处理方法
    @ExceptionHandler(ArithmeticException.class)
    public ModelAndView handleException(ArithmeticException exception, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg",exception.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

2. 转发和重定向

SpringMVC 重定向时参数传递的问题
  1. 转发:A 找 B 借钱400,B没有钱但是悄悄的找到C借了400块钱给A,url不会变,参数也不会丢失,一个请求
  2. 重定向:A 找 B 借钱400,B 说我没有钱,你找别人借去,那么A 又带着400块的借钱需求找到C,url会变,参数会丢失需要重新携带参数,两个请求
@RequestMapping("/handleRedirect")
    public String handleRedirect(String name, RedirectAttributes redirectAttributes) {

        // 拼接参数安全性、参数长度都有局限
        //return "redirect:handle01?name=" + name;  
        
        // addFlashAttribute方法设置了一个flash类型属性,该属性会被暂存到session中,在跳转到页面之后该属性销毁
        redirectAttributes.addFlashAttribute("name", name);
        
        return "redirect:handle01";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值