麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

Struts2 自定義Result

2019-11-14 22:08:58
字體:
來源:轉載
供稿:網友
Struts2 自定義Result

注意:我只要是解決自定義返回Json 和異常處理問題

新建一個類 AjaxResult 繼承 StrutsResultSupport 看看代碼吧

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 的配置文件

<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>

之后我們新建一個公用類 BaseAction

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 我就不在解釋了百度去

例如

public class LoginAction extends BaseAction{
createJSonData("{/"success/":false,/"msg/":/"密碼錯誤。/"}");
return AJAX;

這樣我們的 BaseAction 就完事了,

對象ToString 轉成 json 格式了,方便查看

@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 AjaxErrorMessage

給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);            // }


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 羞羞视频入口 | 日韩欧美色综合 | sese综合| 黄色网欧美| 91黄瓜视频 | 中文字幕亚洲情99在线 | 欧美成人一级片 | 蜜桃视频在线观看视频 | 国产精品视频二区不卡 | av免播放 | 色综合网在线观看 | 污黄视频在线观看 | 中文字幕在线播放第一页 | 玩偶姐姐在线观看免费 | h视频免费在线 | 中文字幕在线观看成人 | 免费香蕉成视频成人网 | 亚洲成人精品久久 | 中文字幕在线观看视频一区 | 黑人一级片视频 | 成人国产免费观看 | 日韩毛片一区二区三区 | 欧美日韩一区,二区,三区,久久精品 | 欧美a在线观看 | 国产一区二区三区四区在线 | 久久国产精 | 亚洲综合视频网 | 亚洲第一成人久久网站 | 亚洲第一页视频 | 国产一区二区三区欧美 | 亚洲一级网站 | a视频网站 | 国产精品久久久久久久久久久久午夜 | 中文字幕在线观看1 | 狠狠干夜夜操 | 欧美大穴 | 日韩视频精品一区 | 日韩一级成人 | 国产91亚洲精品久久久 | 欧美一级黄色网 | 精品久久中文网址 |