UserAction.java(Action抛出异常):
package cn.xxx.web.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import cn.xxx.domain.User;
import cn.xxx.service.UserService;
import cn.xxx.service.impl.UserServiceImpl;
public class UserAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
private UserService us = new UserServiceImpl();
public String login() throws Exception { // 抛出异常。通过Struts.xml配置文件处理异常
if(XXX){
throw new RuntimeException("异常信息!");
}
return "toHome";
}
@Override
public User getModel() {
return user;
}
}
src/struts.xml(Struts2配置文件;配置全局异常处理):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 指定struts2是否以开发模式运行
1.热加载主配置.(不需要重启即可生效)
2.提供更多错误信息输出,方便开发时的调试
-->
<constant name="struts.devMode" value="true"></constant>
<package name="crm" namespace="/" extends="struts-default" >
<global-exception-mappings>
<!-- 如果出现java.lang.RuntimeException异常,就将跳转到名为"error"的结果 -->
<exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
</global-exception-mappings>
<action name="UserAction_*" class="cn.xxx.web.action.UserAction" method="{1}" >
<result name="toHome" type="redirect" >/index.htm</result>
<result name="error" >/login.jsp</result> <!-- 如果发生RuntimeException异常,跳到该结果中 -->
</action>
</package>
</struts>
login.jsp(通过OGNL表达式标签获取异常信息):
<%@ 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 Frameset//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/frameset.dtd">
<HTML xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
</HEAD>
<BODY>
<FORM id=form1 name=form1 action="${pageContext.request.contextPath}/UserAction_login" method=post>
<!-- .................. -->
<s:property value="exception.message" /> <!-- 通过OGNL表达式获取异常信息 -->
<input type="submit" value="提交" />
</FORM>
<s:debug></s:debug> <!-- 调试,查看ValueStack(OGNLContext)中的内容 -->
</BODY>
</HTML>