首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

spring mvc3中错误处理

2012-09-07 
spring mvc3中异常处理在spring mvc3中,处理异常可以这样做,首先定义一个自定义的异常类:1 public class G

spring mvc3中异常处理
在spring mvc3中,处理异常可以这样做,
首先定义一个自定义的异常类:
1 public class GenericException extends RuntimeException{

private String customMsg;

//getter and setter methods

public GenericException(String customMsg) {
this.customMsg = customMsg;
}

}

2 web.xml
  <web-app ...>

  <error-page>
<error-code>404</error-code>
<location>/WEB-INF/pages/404.jsp</location>
  </error-page>

  <error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/WEB-INF/pages/404.jsp</location>
  </error-page>

</web-app>


3 控制器
   CustomerController.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import com.mkyong.common.exception.GenericException;

public class CustomerController extends AbstractController{

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {

throw new GenericException("Oppss...System error, please visit it later");

}

}


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

  <bean
  />

<!-- Register the bean -->
<bean />

<bean >
          <property name="prefix">
              <value>/WEB-INF/pages/</value>
           </property>
          <property name="suffix">
             <value>.jsp</value>
          </property>
    </bean>

</beans>

5 要注意的是,这里用了SimpleMappingExceptionResolver,
当抛出com.mkyong.common.exception.GenericException时,会先于web.xml抛出异常,这时就去到
/WEB-INF/pages/GenericExceptionPage.jsp这个页面处理你的自定义异常了

热点排行