springmvc处理局部异常和全局异常

springmvc通过HandlerExceptionResolver(是一个接口,在spring-webmvc依赖下)处理程序异常,包括处理器异常、数据绑定异常以及处理器执行时发生的异常。HandlerExceptionResolver仅有一个接口方法,如下

当发生异常时,springmvc会调用resolverException()方法,并转到ModelAndView对应的视图中,作为一个异常处理报告页面反馈给用户。

局部异常处理

局部异常处理仅能处理指定controller中的异常,使用@ExceptionHandler注解(在spring-web依赖下)实现,@ExceptionHandler可以指定多个异常,代码如下

@RequestMapping(value = "exlogin.html", method = RequestMethod.GET)
public String exLogin(@RequestParam String userCode, @RequestParam String userPassword){
    User user = userService.selectUserByUserCodeAndUserPassword(userCode, userPassword);
    if (null == user){
        throw new RuntimeException("用户名或者密码不正确!");
    }
    return "redirect:/user/main.html";
}

@ExceptionHandler({RuntimeException.class})
public String handlerException(RuntimeException e, HttpServletRequest request){
    request.setAttribute("e", e);
    return "error";
}

在异常处理方法handlerException()中,把异常提示信息放入HttpServletRequest对象中

展示页面输出相应的异常信息${e.message},输出自定义的异常信息

全局异常处理

全局异常处理可使用SimpleMappingExceptionResolver来实现。它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常。然后在springmvc-servlet.xml中配置全局异常。

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="java.lang.RuntimeException">error</prop>
        </props>
    </property>
</bean>

指定当控制器发生RuntimeException异常时,使用error视图显示异常信息。当然也可以在<props>标签内自定义多个异常。

error.jsp页面中的message显示,需修改为${exception.message}来抛出异常信息。

原文地址:https://www.cnblogs.com/yanguobin/p/11666523.html