SpringMVC中的异常处理

简介

对于简单的全局异常处理,可以使用SpringMVC的异常处理机制,方法非常的简单;例如:使用异常处理来处理用户登录的情景,如下提供了一段伪代码

("/login")
public String login(String userName, String password, HttpSession session) {
    User tempUser = userService.getUserByUserName(userName);
    if(null == tempUser) {
        throw new UserException("用户不存在");
    }
    if(!tempUser.getPassword().equals(password)) {
        throw new UserException("密码不正确");
    }
    session.setAttribute("user", tempUser);
    return "success";
}

实现步骤

  1. 首先先创建一个异常处理的类,UserException.class,这个类要继承 RuntimeException

  2. 在 UserException.class 中右键点击 Source --> Generate Constructors from Supperclass,重写构造方法

public class UserException extends RuntimeException {    
    private String message;
    
    public UserException(String message) {
        this.message = message;
    }
    ... ...
}
  1. 在 spring-servlet.xml 文件中添加如下配置,prop 的 key 定义的是映射到哪个异常,error 是显示异常的页面;这里我们将异常统一跳转到 common/error.jsp 页面显示
<bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="com.ibm.reskill.exception.UserException">common/error</prop>
            <prop key="java.sql.QSLException">common/error</prop>
        </props>
    </property>
</bean>
  1. 在 error.jsp 页面显示异常信息应使用如下方式,${exception.message}
<html>
    <head>
        <title>全局异常处理</title>
    </head>
    <body>
        <h1>系统错误</h1>
        <h2 style="color:red;">${exception.message}</h2>
    </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值