struts2,Spring,hibernate框架组合是struts2有声明式异常处理,再来看看SpringMvc,Spring Ioc,hibernate的声明式异常处理,首先在dao层和service层不需要处理的异常可以直接往外抛异常, 到Controller层同样抛出异常,在spring-servlet.xml中把异常映射起来统一处理:
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView">
<value>failure</value>
</property>
<property name="exceptionMappings">
<props>
<prop key="java.sql.SQLException">showDBError</prop>
<prop key="java.lang.RuntimeException">showError</prop>
</props>
</property>
</bean>
对应的异常路径可以灵活配置了。
关于log4j:
web.xml中加入listener
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView">
<value>failure</value>
</property>
<property name="exceptionMappings">
<props>
<prop key="java.sql.SQLException">showDBError</prop>
<prop key="java.lang.RuntimeException">showError</prop>
</props>
</property>
<property name="warnLogCategory" value="WARN"></property>
<property name="defaultStatusCode" value="500"></property>
</bean>