日期:2014-05-16  浏览次数:20425 次

struts2之json请求的异常处理方案

大家都知道,使用struts2的异常处理机制,只要几行配置,就可以在发生异常时,跳转到我们指定的页面,并显示出相应的异常信息,具体的使用操作过程如下:

1)struts.xml

<struts>
<include file="struts-default.xml"></include>
    <constant name="struts.devMode" value="true" /><!-- 实现国际化资源文件和struts配置文件自动重新加载,不需要重启服务器 -->
    <constant name="struts.ui.theme" value="simple" />
    <constant name="struts.action.extension" value="," /><!-- 不要后缀 -->
    <constant name="struts.enable.SlashesInActionNames" value="true" /><!-- 使用"/"的方式 -->
    <package name="hatch" namespace="" extends="json-default"><!-- json支持  -->
...

<!-- 定义全局视图 -->
    <global-results>
	<result name="login" type="redirectAction">login</result>
	<result name="404">/WEB-INF/view/404.jsp</result>
	<result name="500">/WEB-INF/view/500.jsp</result>
    </global-results>
    <!-- 定义全局异常-->
    <global-exception-mappings>
	<exception-mapping result="500" exception="java.lang.Exception"/><!-- 出现异常时,将页面转到500这个错误页面 -->
    </global-exception-mappings>
...

</struts>




2)500.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>程序异常</title>
<%@include file="/WEB-INF/view/common/common.jspf" %>
<style type="text/css">
*{margin:0;padding:0;}
.errTitle{min-width:300px;width:90%;height:50px;line-height:50px;border:1px solid #999999;border-radius:5px;background:#0169B2;text-align:center;word-spacing:10px;font-family:'黑体';font-size:24px;margin:10px 70px;padding: 4px 4px 4px 6px;position:relative;}
.showErrWrap{font-size:10px;position:absolute;right:10px;bottom:-5px;}
.showErrWrap a:link,.showErrWrap a:visited{text-decoration:none;color:black;}
.showErrWrap a:hover{text-decoration:underline;color:yellow;}
.showErrWrap span{margin:0 4px;color:black;}
.errStack{min-width:300px;width:90%;font-family:"Courier New", Courier, monospace;border:0 none;margin:10px 70px;overflow:auto;padding:4px;}
</style>
<script type="text/javascript">
$(function(){
	$('#showErrBtn').toggle(function(){
		$('#showErrBtn').text('关闭详情');
		$('.errStack').slideDown('normal');
	},function(){
		$('.errStack').slideUp('normal');
		$('#showErrBtn').text('查看详情');
	});
});
if (window.parent != window) {
	window.parent.location.href = window.location.href;
}
</script>

</head>
<body>
<div class="errTitle">程 序 出 现 异 常!<span class="showErrWrap"><a href="javascript:void(0);" id="showErrBtn">查看详情</a><span>|</span><a href="javascript:void(0);" onclick="javascript:history.go(-1);">返回上一页</a></span></div>
<div class="errStack" style="display:none;"><pre>
<s:property value="exceptionStack"/><!-- 异常信息 -->
</pre>
</div>
</body>
</html>

假设在UserAction.java中有一个跳转到列表页面的方法,如下:

/* 用户列表视图 */
public String list() {
	int i = 10/0;
	return "list