SpringMVC中的异常处理(全局异常处理对自定义异常类进行统一处理)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38409944/article/details/82821336

前言:

WEB开发中,总会有一些不可预料的错误,对于一些课预测的异常,我们可以自定义一个异常类,然后再加载个全局异常处理器,对系统中出现的异常进行统一的处理。

注意:当你在Springmvc配置文件中配置全局异常处理器的时候,只要如下配置即可:

 <!--只要该bean继承了HandlerExceptionResolver接口,这个类就会被SpringMVC作为一个全局异常处理器-->
    <bean class="exception.UserExceptionResolver"></bean>
我已经把栗子放到git上了:感兴趣的朋友可以看看
https://github.com/jjc123/exception_handling_demo

这里就总结下我遇到的一些问题:

坑1:

通配符的匹配很全面, 但无法找到元素 'mvc:annotation-driven' 的声明

当我配置Springmvc的适配器和处理器的时候经常遇到这个问题:

<mvc:annotation-driven></mvc:annotation-driven>

原因是:
虽然在xml文件上方声明了mvc,但没有配置此声明对应的文件信息,正确配置如下:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd  ">

主要是结尾要添加这个内容:

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd

意思就是:
mvc声明用http://www.springframework.org/schema/mvc/spring-mvc.xsd这个文件来解析


坑2:EL表达式在JSP界面中取不到值问题。

这个也是很常用的问题,因为最新的web配置中el默认是关闭的,你可以选择手动开启,也可以选择采用最新的web属性值:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

坑3:引用外部资源文件properties时乱码问题

ctrl+alt+s进入Settings 然后设置File Encodings中全部编码格式为UTF-8
而且Transparent native-to-ascii conversion打勾在这里插入图片描述

坑4:如何引入外部资源文件:3个方法:

//拿不到资源
1 InputStream is = this.getClass().getResourceAsStream(fileName);  
// 拿到资源
2 InputStream is = this.getClass().getResourceAsStream("/" + fileName); 
//拿到资源  默认从classpathe中找文件,name不能带“/”,否则会抛空指针
3 InputStreamis=this.getClass().getClassLoader().getResourceAsStream(fileName); 

对于前两者:

path不以’/'开头时,默认是从此类所在的包下取资源;
path  以’/'开头时,则是从ClassPath根下获取;

对于第三者:

path不能以’/'开头时;
path是从ClassPath根下获取;在idea中是从target下的classes根下获取

猜你喜欢

转载自blog.csdn.net/qq_38409944/article/details/82821336