1.异常处理:exception-mapping元素
struts.xml中配置 exception-mapping标签,可以捕捉在Action中出现的异常,
exception:需要捕捉的异常名称
result:出现异常后,跳转到哪个result
<struts>
<!-- 修改当前 Struts 应用的主题 -->
<constant name="struts.ui.theme" value="simple"></constant>
<package name="default" namespace="/" extends="struts-default">
<action name="product-save" class="com.atguigu.struts.valuestack.Product"
method="save">
<exception-mapping result="input" exception="ArithmeticException"></exception-mapping>
<result name="input">/input.jsp</result>
<result>/details.jsp</result>
</action>
<action name="emp-*"
class="com.atguigu.struts.valuestack.app.Employee"
method="{1}">
<result name="{1}">/emp-{1}.jsp</result>
</action>
</package>
</struts>
Struts2框架的ExceptionMappingInterceptor拦截器会将Exception放入值栈。
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String result;
try {
result = invocation.invoke();
} catch (Exception e) {
if (isLogEnabled()) {
handleLogging(e);
}
List<ExceptionMappingConfig> exceptionMappings = invocation.getProxy().getConfig().getExceptionMappings();
ExceptionMappingConfig mappingConfig = this.findMappingFromExceptions(exceptionMappings, e);
if (mappingConfig != null && mappingConfig.getResult()!=null) {
Map parameterMap = mappingConfig.getParams();
// create a mutable HashMap since some interceptors will remove parameters, and parameterMap is immutable
invocation.getInvocationContext().setParameters(new HashMap<String, Object>(parameterMap));
result = mappingConfig.getResult();
publishException(invocation, new ExceptionHolder(e));
} else {
throw e;
}
}
return result;
}
源码中的publishException
protected void publishException(ActionInvocation invocation, ExceptionHolder exceptionHolder) {
invocation.getStack().push(exceptionHolder);
}
对应页面可以打印出错误信息 input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:debug></s:debug>
<s:property value="exceptionStack"/>
<br>
异常对象:
<s:property value="exception.message"/>
<br><br><br>
<form action="product-save.action" method="post">
ProductName: <input type="text" name="productName"/>
<br><br>
ProductDesc: <input type="text" name="productDesc"/>
<br><br>
ProductPrice: <input type="text" name="productPrice" />
<br><br>
<input type="submit" value="Submit"/>
<br><br>
</form>
</body>
</html>