注意:我只要是解決自定義返回Json 和異常處理問題ajax
新建一個類 AjaxResult 繼承 StrutsResultSupport 看看代碼吧json
public class AjaxResult extends StrutsResultSupport { /** * serialVersionUID */ private static final long serialVersionUID = 1L; private static final String AJAX_SUCCESS = "{\"success\":true}"; private static final String SUCCESS_PERFIX = "{\"success\":true,result:["; private static final String FAILURE_PERFIX = "{\"success\":false,result:[],"; private static final String SUFFIX = "]}"; private Writer writer; private String defaultEncoding = "UTF-8"; @Inject("struts.i18n.encoding") public void setDefaultEncoding(String encoding) { this.defaultEncoding = encoding; } protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { Object action = invocation.getAction(); String responseData = ""; if ((action instanceof BaseAction)) { BaseAction ajaxAction = (BaseAction) action; HttpServletResponse response = ServletActionContext.getResponse(); String encoding = getEncoding(finalLocation); String contentType = getContentType(finalLocation); if (encoding != null) { contentType = contentType + ";charset=" + encoding; } response.setContentType(contentType); String successData = ajaxAction.getResponseData(); if (successData != null) { if ("success".equals(successData)) { responseData = "{\"success\":true}"; } else { responseData = successData; } } // if(true){ // String errorResultLocation = ajaxAction.getErrorResultLocation(); // String exceptionMessage = // invocation.getStack().findString("exception.message"); // exceptionMessage = exceptionMessage.replaceAll("\r", " "); // exceptionMessage = exceptionMessage.replaceAll("\n", " "); // exceptionMessage = exceptionMessage.replaceAll("\t", " "); // responseData = getFailureData(null, exceptionMessage); // } getWriter().write(responseData); } } private String getFailureData(String errorResultLocation, String exceptionMessage) { String errors = "errors:[{msg:\"" + exceptionMessage + "\"}]"; // if (StringUtils.isNotBlank(errorResultLocation)) { // String target = ",\"target\":\"" + errorResultLocation; // return "{\"success\":false,result:[]," + errors + target + "\"}"; // } return "{\"success\":false,result:[]," + errors + "}"; } public void setWriter(Writer writer) { this.writer = writer; } protected Writer getWriter() throws IOException { if (this.writer != null) { return this.writer; } return ServletActionContext.getResponse().getWriter(); } protected String getContentType(String templateLocation) { return "application/json"; } protected String getEncoding(String templateLocation) { String encoding = this.defaultEncoding; if (encoding == null) { encoding = System.getProperty("file.encoding"); } if (encoding == null) { encoding = "UTF-8"; } return encoding; } }
接下來,咱們須要一個Struts 的配置文件session
<package name="ajax-default" abstract="true" extends="struts-default"> <result-types> <result-type name="ajax" class="com.guy.core.common.util.AjaxResult" /> </result-types> <global-results> <result name="ajax" type="ajax" /> </global-results> </package>
以後咱們新建一個公用類 BaseActionapp
public class BaseAction extends ActionSupport implements ModelDriven,SessionAware, ParameterAware, ServletRequestAware, ServletResponseAware{ /** * serialVersionUID */ protected final Log logger = LogFactory.getLog(getClass()); private static final long serialVersionUID = 1L; public String SUCCESS="SUCCESS"; public static final String AJAX = "ajax"; protected Map session; protected Map parameters; protected HttpServletRequest servletRequest; protected HttpServletResponse servletResponse; private String responseData; protected void createJSonData(String jsonData) { setResponseData(jsonData); } public String getResponseData() { return responseData; } public void setResponseData(String responseData) { this.responseData = responseData; } public Map getSession() { return session; } public void setSession(Map session) { this.session = session; } public Map getParameters() { return parameters; } public void setParameters(Map parameters) { this.parameters = parameters; } public HttpServletRequest getServletRequest() { return servletRequest; } public void setServletRequest(HttpServletRequest servletRequest) { this.servletRequest = servletRequest; } public HttpServletResponse getServletResponse() { return servletResponse; } public void setServletResponse(HttpServletResponse servletResponse) { this.servletResponse = servletResponse; } @Override public Object getModel() { return null; } }
全部的action 都繼承BaseAction ModelDriven 我就不在解釋了百度去ide
例如 ui
public class LoginAction extends BaseAction{
createJSonData("{\"success\":false,\"msg\":\"密碼錯誤。\"}");return AJAX;
這樣咱們的 BaseAction 就完事了,this
對象ToString 轉成 json 格式了,方便查看spa
@Override
public String toString() { return ToStringBuilder.reflectionToString(this); }
1 <interceptor-ref name="landingIct"> 2 <!-- 包括的方法,也就是攔截器攔截的方法<param name="includeMethods">方法1,方法2</param> 3 4 excludeMethods表示排除指定的方法,即不對標記爲excludeMethods的方法進行攔截 5 --> 6 <param name="excludeMethods">landing</param> 7 </interceptor-ref> 8 <!-- 默認攔截器棧,若是不寫則經過默認攔截器完成的功能將失效。如:國際化等等詳細查看struts-default --> 9 <!-- 10 若是action中沒有自定義的攔截器,struts2會爲該action添加默認的攔截器,即defaultStack;若是action中用戶本身添加了自定義攔截器,將覆蓋掉系統的defaultStack,這時候須要咱們顯式調用該攔截器棧。 11 -->
拋出異常 處理,在beasAction設置 IsAjaxError AjaxErrorMessagecode
給get set 方法, 對象
新建 AjaxExceptionInterceptor
public String intercept(ActionInvocation invocation) throws Exception { String result; try { result = invocation.invoke(); } catch (Exception e) { if (this.logEnabled) { handleLogging(e); } List exceptionMappings = invocation.getProxy().getConfig().getExceptionMappings(); String mappedResult = findResultFromExceptions(exceptionMappings, e); if (mappedResult != null) { result = mappedResult; Object action = invocation.getAction(); if (action instanceof AjaxProvider) { AjaxProvider ajaxAction = (AjaxProvider)action; Map results = invocation.getProxy().getConfig().getResults(); ResultConfig resultConfig = (ResultConfig)results.get(result); String location = (String)resultConfig.getParams().get("location"); ajaxAtion.setIsAjaxError ("true"); ajaxAction.setAjaxErrorMessage(location); result = "ajaxError"; } super.publishException(invocation, new ExceptionHolder(e)); } else { throw e; } } return result; }
baseAction 這裏判斷下是否有異常,有的花轉成json輸出到頁面
// if(true){ // String errorResultLocation = ajaxAction.getErrorResultLocation(); // String exceptionMessage = // invocation.getStack().findString("exception.message"); // exceptionMessage = exceptionMessage.replaceAll("\r", " "); // exceptionMessage = exceptionMessage.replaceAll("\n", " "); // exceptionMessage = exceptionMessage.replaceAll("\t", " "); // responseData = getFailureData(null, exceptionMessage); // }