web项目封装统一返回

BaseController.java:

package com.erpeng.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import com.ketech.utils.common.AjaxUtils;
import com.ketech.utils.common.Result;
import com.ketech.utils.common.ResultType;
import com.ketech.utils.common.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;



public abstract class BaseController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // binder.registerCustomEditor(Date.class, EditorHolder.dateEditor);
        // binder.registerCustomEditor(Integer.class, EditorHolder.integerEditor);
        // binder.registerCustomEditor(Long.class, EditorHolder.longEditor);
        binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class,
                new DecimalFormat("##.00"), true));
        /**
         * 自动转换日期类型的字段格式
         */
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));

        /**
         * 防止XSS攻击
         */
        //binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
    }

    /**
     * Description:通用返回
     * @param response
     * @param success boolean
     * @param code 状态码
     * @param data 对象
     * @param message 返回信息
     * @author around
     * @date 2017年8月15日上午9:03:54
     */
    public <T> void doResult(HttpServletResponse response, boolean success, Integer code,
                             T data,String message) {
        AjaxUtils.renderJson(response, Result.result(data, success, code, message));
    }

    public <T> void doResult(HttpServletResponse response, boolean success, Integer code,
                             T data,T pageInfo,String message) {
        AjaxUtils.renderJson(response, Result.result(data,pageInfo, success, code, message));
    }

    @ExceptionHandler
    public void throwsException(HttpServletResponse response, Exception e) {
        e.printStackTrace();
        AjaxUtils.renderJson(response, Result.result(getStackMsg(e), false,
                StatusCode.EXCEPTIONERROR, ResultType.ERROE));
    }

    private static String getStackMsg(Throwable e) {
        StringBuffer sb = new StringBuffer();
        StackTraceElement[] stackArray = e.getStackTrace();
        for (int i = 0; i < stackArray.length; i++) {
            StackTraceElement element = stackArray[i];
            sb.append(element.toString() + "\n");
        }
        return sb.toString();
    }

    /**
     * Description:会话失效判断监听
     *
     * @author around
     * @date 2017年10月12日下午1:34:45
     */
    public void loginOut(HttpServletResponse resp) {
        doResult(resp, false, StatusCode.LOGINOUT, null, ResultType.LOGINOUT);
    }

}

AjaxUtils工具类

package com.XX.utils.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletResponse;

import com.ketech.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author:
 * @date  : 2017年6月5日 上午09:55:48
 * @Desc  :ajax工具类
 */
public class AjaxUtils {

	private static final String HEADER_ENCODING = "encoding";
	private static final String HEADER_NOCACHE = "no-cache";
	private static final String DEFAULT_ENCODING = "UTF-8";
	private static final boolean DEFAULT_NOCACHE = true;

	public static ObjectMapper mapper = JsonUtils.mapper;

	static {
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}

	/**
	 * 直接输出内容的简便函数
	 */
	public static void render(HttpServletResponse response, final String contentType, final String content,
			final String... headers) {
		initResponseHeader(response, contentType, headers);
		PrintWriter write = null;
		try {
			write = response.getWriter();
			write.write(content);
			write.flush();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (write != null) {
				write.close();
			}
		}
	}

	/**
	 * 直接输出文本.
	 */
	public static void renderText(HttpServletResponse response, final String text, final String... headers) {
		render(response, CommonConstants.CONTENT_TYPE.TEXT_TYPE, text, headers);
	}

	/**
	 * 直接输出HTML.
	 * 
	 */
	public static void renderHtml(HttpServletResponse response, final String html, final String... headers) {
		render(response, CommonConstants.CONTENT_TYPE.HTML_TYPE, html, headers);
	}

	/**
	 * 直接输出XML.
	 * 
	 */
	public static void renderXml(HttpServletResponse response, final String xml, final String... headers) {
		render(response, CommonConstants.CONTENT_TYPE.XML_TYPE, xml, headers);
	}

	/**
	 * 直接输出JSON.
	 */
	public static void renderJson(HttpServletResponse response, final String jsonString, final String... headers) {
		render(response, CommonConstants.CONTENT_TYPE.JSON_TYPE, jsonString, headers);
	}

	/**
	 * 直接输出JSON,使用Jackson转换Java对象.
	 */
	public static void renderJson(HttpServletResponse response, final Object data, final String... headers) {
		initResponseHeader(response, CommonConstants.CONTENT_TYPE.JSON_TYPE, headers);
		try {
			mapper.writeValue(response.getWriter(), data);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}

	/**
	 * 直接输出支持跨域Mashup的JSONP.
	 */
	public static void renderJsonp(HttpServletResponse response, final String callbackName, final Object object,
			final String... headers) {
		String jsonString = null;
		try {
			jsonString = mapper.writeValueAsString(object);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}

		String result = new StringBuilder().append(callbackName).append("(").append(jsonString).append(");").toString();

		// 渲染Content-Type为javascript的返回内容,输出结果为javascript语句,
		render(response, CommonConstants.CONTENT_TYPE.JS_TYPE, result, headers);
	}

	/**
	 * 分析并设置contentType与headers.
	 */
	private static void initResponseHeader(HttpServletResponse response, final String contentType,
			final String... headers) {
		String encoding = DEFAULT_ENCODING;
		boolean noCache = DEFAULT_NOCACHE;
		for (String header : headers) {
			String headerName = StringUtils.substringBefore(header, ":");
			String headerValue = StringUtils.substringAfter(header, ":");

			if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
				encoding = headerValue;
			} else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
				noCache = Boolean.parseBoolean(headerValue);
			} else {
				throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
			}
		}

		// 设置headers参数
		String fullContentType = contentType + ";charset=" + encoding;
		response.setContentType(fullContentType);
		if (noCache) {
			setDisableCacheHeader(response);
		}
	}

	/**
	 * 设置禁止客户端缓存的Header.
	 */
	public static void setDisableCacheHeader(HttpServletResponse response) {
		// Http 1.0 header
		response.setDateHeader("Expires", 1L);
		response.addHeader("Pragma", "no-cache");
		// Http 1.1 header
		response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
	}

	public static void renderJsonporJson(HttpServletResponse response, final String callbackName, final Object object,
			final String... headers) {
		if (callbackName != null && !callbackName.equals("")) {
			renderJsonp(response, callbackName, object, headers);
		} else {
			renderJson(response, object, headers);
		}
	}

	public static void renderJsonporJson2(HttpServletResponse response, final String callbackName, final String data,
			final String... headers) {
		if (callbackName != null && !callbackName.equals("")) {

			String result = callbackName + "(" + data + ")";
			renderText(response, result, headers);
		} else {
			renderJson(response, data, headers);
		}
	}
}

Result 通用返回包装对象:

package com.XX.utils.common;

/**
 * @Desc   :结果处理类
 */
/**
 * Description:通用返回包装对象

 */
public class Result implements java.io.Serializable {

	private static final long serialVersionUID = -7074012067378557866L;

	/** 返回结果集 */
	private Object data;
	
	/**分页信息 */
	private Object pageInfo;
	
	/** 成功失败 */
	private boolean success;
	
	/** 信息 */
	private String message;
	
	/** 状态码 */
	private Integer code;
	
	/** 前端弹窗模式:"warning", "error", "success", "info" */
	private String icon;
	
	public Result() {}
	
	public Result(boolean success, String message) {
		this.success = success;
		this.message = message;
		if (success) icon = "success";
		else icon = "error";
	}
	
	public Result(boolean success, Integer code, String message) {
		this(success, message);
		this.code = code;
	}
	
	public Result(boolean success, Integer code, Object data, String message) {
		this(success, code, message);
		this.data = data;
	}

	
	public static Result result(Object data, boolean success, Integer code, String message) {
		Result result = new Result();
		result.data = data;
		result.success = success;
		result.message = message;
		result.code = code;
		return result;
	}
	
	public static Result result(Object data,Object pageInfo, boolean success, Integer code, String message) {
		Result result = new Result();
		result.pageInfo = pageInfo;
		result.data = data;
		result.success = success;
		result.message = message;
		result.code = code;
		return result;
	}
	

	//返回成功结果
	public static  Result resultSuccess(Object data, String message) {
		Result result = new Result();
		result.data = data;
		result.success = true;
		result.message = message;
		return result;
	}

	//返回失败
	public static  Result resultError(String message) {
		Result result = new Result();
		result.success = false;
		result.message = message;
		return result;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getIcon() {
		return icon;
	}

	public void setIcon(String icon) {
		this.icon = icon;
	}

	public Object getPageInfo() {
		return pageInfo;
	}

	public void setPageInfo(Object pageInfo) {
		this.pageInfo = pageInfo;
	}

	
}

自定义状态码StatusCode:

package com.XX.utils.common;


/**
 * 状态码,对应前端处理
 */
public class StatusCode {
	
	/** 没有权限 */
	public static final Integer NOPERMISS = 401;
	
	/** 权限不足 */
	public static final Integer PERMISSION_LESS = 402;

	/** 会话ing */
	public static final Integer LOGING = 299;
	
	/** 会话失效 */
	public static final Integer LOGINOUT = 400;
	
	/** 操作成功*/
	public static final Integer OPERATIONSUCCESS = 200;
	
	/** 操作失败*/
	public static final Integer OPERATIONERROR = 500;
	
	/** 查询成功 */
	public static final Integer FINDSUCCESS = 201;
	
	/** 查询失败 */
	public static final Integer FINDERROR = 501;
	
	/** 保存成功 */
	public static final Integer SAVESUCCESS = 202;
	
	/** 保存失败 */
	public static final Integer SAVEERROR = 502;
	
	/** 删除成功 */
	public static final Integer REMOVESUCCESS = 203;
	
	/** 删除失败 */
	public static final Integer REMOVEERROR = 503;
	
	/** 退出成功 */
	public static final Integer TOLOGINOUT = 204;
	
	/** 程序异常 */
	public static final Integer EXCEPTIONERROR = 510;
	
	/** 缺少必填项 */
	public static final Integer LACKVALUE = 511;
	
	/** 字段重复 */
	public static final Integer DUPLICATIONERROR = 512;
	
	/** 无对应数据 */
	public static final Integer NORETRUNDATA = 513;
	
	/** 默认状态 */
	public static final Integer DEFAULT = 251;
	
	
}

ResultType返回类型常量:

package com.XX.utils.common;


/**
 * 返回类型常量

 */
public class ResultType {
	
	public static final String ERROE = "程序异常";
	
	public static final String NO_PERMISSIONS = "权限不足";
	
	public static final String LOGINOUT = "会话过期";

	public static final String ADD_SUCCESS = "新增成功";
	public static final String ADD_FAULT = "新增失败";
	
	public static final String SAVE_SUCCESS = "保存成功";
	public static final String SAVE_FAULT = "保存失败";
	
	public static final String REMOVE_SUCCESS = "删除成功";
	public static final String REMOVE_FAULT = "删除失败";
	
	public static final String FIND_SUCCESS = "查询成功";
	public static final String FIND_FAULT = "查询失败";
	
	public static final String FIND_NULL = "未找到数据";
	
	public static final String INPUT_ERROR = "数据填写错误";
	public static final String INPUT_REPEAT = "数据填写重复";
	public static final String INPUT_NULL = "请填写必要信息";
	
	public static final String NAME_REPEAT = "名称重复";
	
	public static final String SAVE_FAC_FAULT="请正确填写厂商信息";
	public static final String USER_REPEAT="用户已存在";
	public static final String LOGISTICS_REPEAT="物流公司已存在";
	
	public static final String CHOOSE_INFO="请选择相应数据";
	
	public static final String OPERATION_SUCCESS="操作成功";
	public static final String OPERATION_FAULT="操作失败";
	
	public static final String PARENTNAME_NULL="省厅上报功能未开通";
	
}

通用常量CommonConstants:

package com.XX.utils.common;

/**
 * @Desc   :通用常量
 */
public class CommonConstants {
	public interface CONTENT_TYPE {
		public static final String TEXT_TYPE = "text/plain";
		public static final String JSON_TYPE = "application/json";
		public static final String XML_TYPE = "text/xml";
		public static final String HTML_TYPE = "text/html";
		public static final String JS_TYPE = "text/javascript";
		public static final String EXCEL_TYPE = "application/vnd.ms-excel";
	}

	public interface ENCODE {
		public static final String UTF_8 = "UTF-8";
		public static final String ISO_8859_1 = "ISO-8859-1";
		public static final String GB2312 = "GB2312";
		public static final String GET = "GET";
		public static final String POST = "POST";
	}

	/**
	 * 全局常量-文件路径等适用
	 * @author around
	 * @date 2017-6-15
	 */
	public interface FilePath {
		//系统文件上传分类
		public static final String SEPARATOR = "/";
		/** 用户照片 */
		public static final String USER_IMAGE = "userImg";
		//厂商图片
		public static final String FACTORY_IMAGE ="factory";
		
		public static final String EXCEL = "excel";
	}

	public static final String SUCCESS = "success";
	public static final String FAIL = "fail";

	public static final String USERINFO = "userinfo";//用户对象session名
	
	/** 数据库实例 */
	public static final String DATABASE= "cloud";
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java大表哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值