Struts2官方文档中的异常处理是返回jsp页面,但是,如果我们在前端用的是Ajax方法请求,服务器统一返回Json处理,我们就不能直接返回jsp了。
先看看返回jsp的方法,如下(可跳过,进入主题):
全局配置:
0 1 2 3 4 5 6 7 8 9 10 11 |
<global-results> <result name="securityerror">/securityerror.jsp</result> <result name="error">/error.jsp</result> </global-results> <global-exception-mappings> <exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreachException" result="securityerror" /> <exception-mapping exception="java.lang.Exception" result="error" /> </global-exception-mappings> |
单个Action中配置:
0 1 2 3 4 5 6 7 8 |
<action name="actionspecificexception" class="org.apache.struts.register.action.Register" method="throwSecurityException"> <exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreachException" result="login" /> <result>/register.jsp</result> <result name="login">/login.jsp</result> </action> |
jsp页面:
0 1 2 3 4 5 6 7 8 9 |
<h4>The application has malfunctioned.</h4> <p> Please contact technical support with the following information:</p> <h4>Exception Name: <s:property value="exception" /> </h4> <h4>Exception Details: <s:property value="exceptionStack" /></h4> |
我们可以在jsp中输出exception和exceptionStatck查看错误。(当然,直接输出异常信息给用户是一个不良的做法)
一、jsp返回Json
你可以把jsp页面改成以下形式:
0 1 2 3 4 5 |
<%@ page contentType="application/json;charset=UTF-8" language="java" %> <%@taglib prefix="s" uri="/struts-tags"%> {"success": false, "msg": "<s:property value="exception.message"/>"} |
注意:contentType为application/json,这样浏览器会把文本解释成json,然后下面你就可以定义json的内容了,这种方法最自由。
二、JSON类型的result
上面的例子中,返回的是dispatcher类型
0 1 2 3 |
<result name="login">/login.jsp</result> |
我们这里可以改成json类型,用includeProperties参数配置要输出的内容,你可以用.*来输出所有内容来查看都有什么属性,然后再筛选你要的内容,这种方式约束较大。
0 1 2 3 4 5 |
<result name="exception" type="json"> <param name="includeProperties">.*</param> </result> |
三、redirectAction类型的result
我们可以通过redirectAction跳转到action来返回一个Json结果。返回内容较为自由,但异常信息无法传递到action中(或许是我孤陋寡闻)。