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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值