controller层异常,获取异常,并在视图显示
第一步:在controller层类里新建带异常的方法
//有带异常的方法,实现登录功能,登录不成功,抛出异常
@RequestMapping("/exlogin")
public String exLogin(@RequestParam String bbsName,@RequestParam String password,@RequestParam Integer userType,HttpServletRequest request){
ApplicationContext context=getApplicatIonContext(request);
UserService usi=(UserService)context.getBean("userServiceImpl");
int count=usi.getUserQuery(bbsName, password, userType);
if(count==0){
throw new RuntimeException("用户或者密码错误");
}else {
return "redirect:/user/hello"; //重定向
//return "hello"; //转发
}
}
第二步:获取异常
1.局部异常,只在当前类里有效,在controller层 “有带异常的方法” 类里新建获取异常的方法
//局部异常处理,获取异常的方法
@ExceptionHandler(value={RuntimeException.class}) //局部异常注解,获取当前 controller的RuntimeException异常。可以给多个别的类型异常。
public String handlerException(RuntimeException e,HttpServletRequest request){
request.setAttribute("e",e); //在页面用 ${e.message}获取异常提示信息
return "exception"; //异常信息显示视图
}
2.全局异常,在mvc配置文件里配置(springmvc-servlet.xml),应用于controller层 的所有类,设了局部异常后,全局异常不起作用
<!--全局异常的配置-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--RuntimeException:运行异常,exception:视图名,用exception.jsp页面显示异常信息,在页面用${exception.message}获取异常信息-->
<prop key="java.lang.RuntimeException">exception</prop>
</props>
</property>
</bean>
自定义异常:
1:新建类,继承Exception
public class MyException extends Exception {
public MyException(String message){
super(message);
}
}
2:配置文件配置
<!--全局异常的配置-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--定义默认的异常处理页面为error.jsp-->
<property name="defaultErrorView" value="jsp/error"/>
<!--定义异常处理页面用来获取异常信息用 ex. 变量名获取, 默认名为:exception-->
<property name="exceptionAttribute" value="ex"/>
<!--定义需要特殊处理的异常-->
<property name="exceptionMappings">
<props>
<!--RuntimeException:运行异常,myerror:视图名,用hello.jsp页面显示异常信息,在页面用${ex.message}获取异常信息-->
<prop key="java.lang.RuntimeException">jsp/myerror</prop>
<!--自定义类异常-->
<prop key="cn.kgc.exception.MyException">jsp/myerror</prop>
</props>
</property>
</bean>