首页 > 代码库 > Struts2 自定义Result

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 = http://www.mamicode.com/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 =http://www.mamicode.com/ 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);     }

Struts2 自定义Result