Struts2的异常处理:
1,定义自己的异常信息类:继承Exception类
/**
* 我自己的异常类
* @author 张明学
*
*/
public class MyException extends Exception {
private String message;
public MyException(String message) {
super(message);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2,在Action中产生异常
@Override
public String execute() throws Exception {
if (!"mengya".equals(username)) {
//模拟产生异常
throw new MyException("用户名不存在!");
} else if (!"xiaobo".equals(password)) {
//模拟产生异常
throw new MyException("密码错误!");
} else {
return SUCCESS;
}
}
3,在struts.xml中配置异常
<package name="mengya" extends="struts-default">
<!-- 全局的异常配置global-results要配置在global-exception-mappings上面 -->
<global-results>
<result name="myException">/myException.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="myException"
exception="com.mengya.exception.MyException">
</exception-mapping>
</global-exception-mappings>
<action name="login" class="com.mengya.action.LoginAction">
<!-- 局布的异常用配置 -->
<!--
<exception-mapping result="myException"
exception="com.mengya.exception.MyException">
</exception-mapping>
-->
<result name="success">/show.jsp</result>
<!--
<result name="myException">/myException.jsp</result>
-->
</action>