Spring-mvc的拦截器和异常通知

Interceptor(拦截器)

springmvc.xml的配置

<!-- 包扫描-->

<context:component-scan base-package="com"/>

<!-- 配置拦截器 -->
<mvc:interceptors>
<!-- 配置其中一个拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<mvc:mapping path="/hello1"/>

<!-- 自定义拦截器 -->
<bean class="com.interceptor.MyInterceptor"></bean>


</mvc:interceptor>
</mvc:interceptors>

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

 

MyInterceptor.java

//在执行目标代码之前执行的拦截功能
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("这是Controller执行前的拦截器,顺序:1");

//return true 不拦截 ,reture false或者抛出异常时之后的都不执行
return true;
}

//在执行目标代码之后执行的拦截功能
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("这是Controller执行后 页面渲染前的拦截器,顺序:3");
}


//在目标代码执行完毕后 跳转了指定页面

//只要preHandle return true时,必定会执行
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("这是页面渲染完成后的拦截器,顺序:5");
}

 

ExceptionAdvice(异常统一处理)

springmvc.xml的配置

<!-- 配置异常映射处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- key代表异常 要求添加全类名 跳转到的页面 要卸载双标签的中间 -->
<prop key="java.lang.Exception">forward:/error.jsp</prop>
<prop key="java.lang.RuntimeException">forward:/error.jsp</prop>
<prop key="java.lang.ArithmeticException">forward:/error.jsp</prop>
<prop key="java.lang.NullPointerException">forward:/error.jsp</prop>
</props>
</property>
</bean>
<!-- 放行静态资源 -->
<mvc:default-servlet-handler/>

 

ExceptionAdvice.java

@ExceptionHandler
public ModelAndView exceptionHandler(Exception e) {
System.out.println("Exception异常信息:"+e);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("forward:/error.jsp");
modelAndView.addObject("exception",e);
return modelAndView;
}

@ExceptionHandler
public ModelAndView exceptionHandler(RuntimeException e) {
System.out.println("Exception异常信息:"+e);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("forward:/error.jsp");
modelAndView.addObject("exception",e);
return modelAndView;
}

@ExceptionHandler
public ModelAndView exceptionHandler(ArithmeticException e) {
System.out.println("Exception异常信息:"+e);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("forward:/error.jsp");
modelAndView.addObject("exception",e);
return modelAndView;
}

 

posted @ 2019-10-15 19:43  m_ming  阅读(295)  评论(0编辑  收藏  举报