//局部异常处理
//仅能处理指定Controller中的异常
//测试步骤:在地址栏中输入localhost:8080/user/exlogin.html?userCode=zhangsan&userPassword=123,如果数据库中不存在
// ,则出现自定的异常 throw new RuntimeException("用户名或者密码不对")
@RequestMapping(value="/exlogin.html",method=RequestMethod.GET)
public String exlogin(@RequestParam String userCode,@RequestParam String userPassword){
User user=userService.login(userCode, userPassword);
System.out.println(user);
if(null==user){//登陆失败
throw new RuntimeException("用户名或者密码不对");
}
return "redirect:/user/main.html";
}
//对这个异常进行相应的处理 ,加入一个捕获异常的方法:上述自定义的异常,在error.jsp页面中呈现
@ExceptionHandler(value={RuntimeException.class})
public String handlerException(RuntimeException e,HttpServletRequest req){
req.setAttribute("e", e);
return "error";
}
全局异常
现在springmvc文件中配置
<!--全局异常的处理 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.RuntimeException">error</prop> 此处的error是error.jsp页面
</props>
</property>
</bean>