1. 程式人生 > >常用工具類(三):獲取介面引數與統一返回結果

常用工具類(三):獲取介面引數與統一返回結果

public class ParamUtils {
    private static Logger logger = LoggerFactory.getLogger(ParamUtils.class);
    private static Gson gson = new Gson();
    private static View viewer = new View();

    public static String getParam(HttpServletRequest request) {
        String param = null;
        if ("GET".equals(request.getMethod())) {
            param = request.getParameter("param");
        } else {
            param = getPostParm(request);
        }
        return cleanXSS(param);
    }

    private static String getPostParm(HttpServletRequest request) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        BufferedReader reader = null;
        try {
            reader = request.getReader();
            if (!reader.ready()) return jb.toString();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (IllegalStateException e){
            logger.error("getReader 被呼叫了兩次的原因麼" );
        } catch (Exception e) {
            logger.error("讀取請求引數出錯", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    logger.error("BufferedReader 關閉有誤", e);
                }
            }
        }
        return jb.toString();
    }

    public static String encodeURI(String uri) {
        try {
            return URLEncoder.encode(uri, "UTF-8");
        } catch (Exception e) {
            return uri;
        }
    }

    //切割一個範圍  "limit":"1,10"
    public static int[] parseLimit(String limit) {
        String[] strings = limit.split(",");
        int[] result = new int[2];
        result[0] = Integer.parseInt(strings[0]);
        result[1] = Integer.parseInt(strings[1]);
        return result;
    }

    private static String cleanXSS(String value) {
        if (value == null) {
            return null;
        }
        value = value.replaceAll("eval", "");
        value = value.replaceAll("<script>", "");
        value = value.replaceAll("<javascript>", "");
        return value;
    }

    public static void errorParam(String info, HttpServletResponse resp) {
        ResultBean resultBean = new ResultBean();
        resultBean.setCode(getErrorCode());
        resultBean.setInfo(info);
        String data = gson.toJson(resultBean);
        viewer.viewString(data, resp);
    }

    public static ResultBean errorParamResultBean(String info) {
        ResultBean resultBean = new ResultBean();
        resultBean.setCode(getErrorCode());
        resultBean.setInfo(info);
        return resultBean;
    }

    public static int getErrorCode() {
        return 0;
    }

    public static int getSuccessCode() {
        return 1;
    }

    public static String getStatusKey() {
        return "code";
    }

    public static String getDataKey() {
        return "info";
    }
}

有的介面返回值為空,但是仍然希望能夠輸出內容,此時可以使用response物件輸出內容到網頁

public class View {
    private Logger logger = LoggerFactory.getLogger(View.class);
    private static Gson gson = new Gson();
    private static final JsonFactory jsonFactory = new JsonFactory();

    public void setHttpServletResponse(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "http://angular.js");
        response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setContentType("application/json");
    }

    public void writeResult(String result, HttpServletResponse response) {
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            if (result == null) {
                ResultBean resultBean = new ResultBean();
                resultBean.setCode(0);
                resultBean.setMsg("請求出錯");
                writer.write(gson.toJson(resultBean));
                writer.flush();
            } else {
                writer.write(result);
                writer.flush();
            }
        } catch (IOException e) {
            logger.error("", e);
        } finally {
            writer.close();
        }
    }

    public void viewString(String str, HttpServletResponse response) {
		// 1k以下資料顯示
        if (str == null || str.length() < 1024 * 1) logger.info("結果:" + str);
        setHttpServletResponse(response);
        writeResult(str, response);
    }
}