springmvc异常处理

一、步骤

1.编写自定义异常处理类(做提示信息的)

2.编写异常处理器

3.配置异常处理器(跳转到友好的提示页面)

二、案例

1、

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/testException")
    public String testException() throws Exception{
        System.out.println("/testException..........");

        try{
            //模拟异常
            int a = 10 / 0;
        }catch (Exception e){
            e.printStackTrace();
            throw new SysException("被零除了。。。。。");
        }
        return "success";
    }
}

2、

public class SysException extends Exception{
    //存储提示信息
    private String message;

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public SysException(String message) {
        this.message = message;
    }
}

3、

//异常处理器类,需要实现特定的接口
public class SysExceptionResolver implements HandlerExceptionResolver {

    /**
     * 处理异常业务逻辑
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        //获取异常对象,ex
        SysException e = null;

        if(ex instanceof  SysException){
            e = (SysException)ex;
        }else {
            e = new SysException("系统在维护。。。");
        }
        //创建ModelAndView对象,可以跳转到要去的页面
        ModelAndView mv = new ModelAndView();
        //加入错误信息
        mv.addObject("errorMsg",e.getMessage());
        //配置调到哪里error.jsp页面等
        mv.setViewName("error");

        return mv;
    }
}

4、

<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="cn.rzpt.exception.SysExceptionResolver"/>

5、

error.jsp

${errorMsg}

6、springmvc.xml配置

<!-- 开启注解扫描 -->
<context:component-scan base-package="cn.rzpt"/>

<!-- 视图解析器对象 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<!--前端控制器,哪些静态资源不拦截-->
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值