SpringMVC处理自定义异常,通过读取配置文件把错误信息显示在前台页面

首先引入jar包,用于读取配置资源文件:

<!-- commons组件读取配置文件相关依赖 -->
    <dependency>
        <groupId>commons-configuration</groupId>
        <artifactId>commons-configuration</artifactId>
        <version>1.8</version>
    </dependency>

自定义异常:

public class DuplicateException extends RuntimeException{
    private static final long serialVersionUID = 1L;
    public DuplicateException() {
    }
    public DuplicateException(String message){
        super(message);
    }
}

利用控制器通知注解@ControllerAdvice将自定义异常集中在同一个地方处理:

/**
 * 带有@ControllerAdvice的类中,所有带有@ExceptionHandler的方法会应用到
 * 整个应用程序所有控制器中带有@RequestMapping注解的方法上
 * 注解@ControllerAdvice本身已经使用了@Component注解
 * @author dai
 *
 */
@ControllerAdvice
public class AppWideExceptionHandler {
    @ExceptionHandler(DuplicateException.class)
    public String duplicateHandler(HttpServletRequest request,DuplicateException ex){
        request.setAttribute("error", ex.getMessage());
        return "error/duplicate";
    }
}

控制器方法抛出自定义异常:

@RequestMapping(value="/register",method=POST)
    public String processRegistration(Spitter spitter) throws IOException{
        if("test".equals(spitter.getUsername())){
            throw new DuplicateException(getProperty("username.duplicate"));
        }
        return "redirect:/spitter/"+spitter.getUsername();
    }

此处用到的自定义错误提示,是通过读取property配置文件来获得。

getProperty()方法是自己封装好的,如下:

public class PropertiesUtil {
    private static PropertiesConfiguration configuration = null;
    public static String getProperty(String key){
        try {
            configuration = new PropertiesConfiguration("/spittr/props/errors.properties");
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        return configuration.getString(key);
        
    }
    
}

该工具类利用了Commons组件包,/spittr/props/errors.properties为资源文件的项目类加载路径,注意:

commons-configuration组件抛出的ConfigurationException异常引用了commons-lang-2.6.jar包,所以commons-lang jar包的版本不能太高,这里用的是2.6版本,测试可以通过。

errors.properties定义如下:

username.duplicate=用户名重复!

前台JSP相关代码:

This is an error page! <br />
error:<c:out value="${error}"></c:out>

项目运行后,在前台表单输入用户名"test",提交后跳转到错误提示页面,并显示用户名重复!

参考资料:《Spring实战(第4版)》

转载于:https://my.oschina.net/daigd/blog/759126

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值