一 : code授权码 , 服务端丶客户端
二 : 数据库查询接口
三 : RSA加密丶Escape编码等方法
VerifyCode授权码,客户端
/*** * VerifyCode(授权码)客户端 */ @Controller public class VerifyCode { private static String verifyCode = null; // 授权码 private static long valid_date = 0; // (授权码)有效期至(毫秒) private static String server_puKey = null; // 中控端,加密公钥 // 获取授权码 // 同时只有一个线程可进入此方法 public static synchronized String getCode() { if (verifyCode == null || new Date().getTime() >= valid_date) { applyCode(); } return verifyCode; } public static String getServerKey() { return server_puKey; } /** 向"中控"服务器,请求Code验证码 **/ public static void applyCode() { try { String puKey = RSAUtils.getPukeyStr(); // RSA公钥(接收参数加密密钥) String redirect_uri = "http://127.0.0.1:8080/" + Config.server_name + "/getCode"; // 回调地址(接受参数) String url = "http://127.0.0.1:8080/control_center/getCode?redirect_uri=URI&puKey=PUKEY"; // "中控"服务器接口 url = url.replace("URI", Escape.escape(redirect_uri)).replace("PUKEY", Escape.escape(puKey)); Global.info(url); String str = HttpGetRequest.doGet(url); if (str != null) { JSONObject json = JSONObject.fromObject(str); int ret = json.getInt("ret"); if (ret == 0) { Thread.sleep(200); // 此线程休眠200(毫秒),等待中控服务器信息反馈完毕 } else { // 获取code失败 Global.error(json.getString("errorMag")); } } } catch (Exception e) { e.printStackTrace(); } } /** 获取到验证码 */ @RequestMapping("/getCode") public void getCode(HttpServletResponse response, String verifyCode, String valid_time, String server_puKey) { if (verifyCode != null) { try { // 对verifyCode进行解码,解密(已被加密) VerifyCode.verifyCode = RSAUtils.decrypt(Escape.unescape(verifyCode), RSAUtils.getPrkey()); VerifyCode.valid_date = new Date().getTime() + Integer.parseInt(valid_time); VerifyCode.server_puKey = Escape.unescape(server_puKey); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } HttpUtils.write(response, "{'ret':0}"); } }
VerifyCode授权码,服务端
/** * verifyCode(授权)服务端 **/ @Controller public class VerifyCode extends Global { // 密钥组,JSONObject中存储pukey丶uri等信息 private static Map<String, JSONObject> codes = new HashMap<String, JSONObject>(); // 获取verifyCode(uri:回调地址,valid_time:有效时长(毫秒)) private static String getCode(String puKey, String uri, long valid_time) { if (puKey != null) { String verifyCode = getRandomStr(50); // 50位随机字符串(不含特殊符号) codes.put(verifyCode, getJSON("puKey", puKey, "uri", uri, "start_time", new Date().getTime(), "valid_time", valid_time)); return verifyCode; } return null; } // 获取code public static JSONObject ready(String code) { JSONObject js = codes.get(code); if (js != null && (new Date().getTime() - js.getLong("start_time")) > js.getLong("valid_time")) { js = null; codes.remove(code); } return js; } // 获取control_center验证码(url匹配:一般只允许http://127.0.0.1/地址获取) @RequestMapping("/getCode") public void getCode(HttpServletResponse response, String redirect_uri, String puKey) { try { redirect_uri = Escape.unescape(redirect_uri); // escape编码解析,js语言方法 if (Pattern.compile(Config.regex).matcher(redirect_uri).find()) { // 公钥 puKey = Escape.unescape(puKey); // 获取VerifyCode验证码,有效期(毫秒/总24h) long valid_time = 8640000; String verifyCode = getCode(puKey, redirect_uri, valid_time); // 加密verifyCode(公钥) String en_verifyCode = RSAUtils.encrypt(verifyCode, RSAUtils.getPukey(puKey)); // 回调verifyCode码(加密后,接收方需进行解码) String url = redirect_uri + "?verifyCode=" + Escape.escape(en_verifyCode) + "&valid_time=" + valid_time + "&server_puKey=" + Escape.escape(RSAUtils.getPukeyStr()); info("getCode redirect_uri:" + url); HttpGetRequest.doGet(url); // 发送,获取成功 HttpUtils.write(response, "{'ret':0,'successMsg':'Code has been callback to the redirect_uri address!'}"); } // 正则匹配失败,uri不是安全域名 else { HttpUtils.write(response, "{'ret':10002,'errorMsg':'redirect_uri is not a secure domain name!'}"); } } catch (Exception e) { HttpUtils.write(response, "{'ret':10001,'errorMsg':'parameter anomaly!'}"); e.printStackTrace(); } } }
DBServer服务端
/** * 数据库服务器端 */ @Controller public class DBServer extends Global { // 查询用户信息 @RequestMapping("/queryUser") public void queryUser(HttpServletResponse response, String openid, String code) { JSONObject json = VerifyCode.ready(code); if (json != null) { WxUser wxUser = WechatDB.getUserByOpenid(openid); if (wxUser != null) { try { String data = "{'ret':0,'successMsg':'found user success!','data':" + getJSON("user", wxUser) + "}"; // 此处使用公钥加密信息(数据太长,需使用分段加密丶解密) data = RSAUtils.encrypt(data, RSAUtils.getPukey(json.getString("puKey"))); // 对data字符串进行编码传输(防止乱码) HttpUtils.write(response, Escape.escape(data)); } catch (Exception e) { e.printStackTrace(); HttpUtils.write(response, "{'ret':10003,'errorMsg':'parsing error , please get code again !'}"); } } else { HttpUtils.write(response, "{'ret':10002,'errorMsg':'the user was not found!'}"); } } else { HttpUtils.write(response, "{'ret':10001,'errorMsg':'code is invalid!'}"); } } // 尝试减去用户积分 @RequestMapping("/subSocre") public void subSocre(HttpServletResponse response, String openid, String code, String socre) { JSONObject json = VerifyCode.ready(code); if (json != null) { try { Boolean success = WechatDB.subSocerByOpenid(openid, Integer.parseInt(socre)); String data = "{'ret':0,'successMsg':'return success!','data':{'success':" + success + "}}"; // 对data字符串进行编码传输(防止乱码) HttpUtils.write(response, Escape.escape(data)); } catch (Exception e) { e.printStackTrace(); HttpUtils.write(response, "{'ret':10003,'errorMsg':'parsing error , please get code again !'}"); } } else { HttpUtils.write(response, "{'ret':10001,'errorMsg':'code is invalid!'}"); } } // 保存用户 @RequestMapping("/saveUser") public void saveUser(HttpServletResponse response, String data, String code) { JSONObject json = VerifyCode.ready(code); if (json != null) { try { // 对data解码丶解密 data = Escape.unescape(data); data = RSAUtils.decrypt(data, RSAUtils.getPrkey()); // 将data转化为WxUser对象 WxUser wxUser = (WxUser) JSONObject.toBean(JSONObject.fromObject(data).getJSONObject("user"), WxUser.class); // 尝试保存用户信息 Boolean success = WechatDB.saveWechatUser(wxUser); String s_data = "{'ret':0,'successMsg':'return success!','data':{'success':" + success + "}}"; // 对data字符串进行编码传输(防止乱码) HttpUtils.write(response, Escape.escape(s_data)); } catch (Exception e) { e.printStackTrace(); HttpUtils.write(response, "{'ret':10003,'errorMsg':'parsing error , please get code again !'}"); } } else { HttpUtils.write(response, "{'ret':10001,'errorMsg':'code is invalid!'}"); } } }
DBClient客户端
/*** * 连接中控服务器数据库,客户端 * */ public class DBClient extends Global { /** 获取用户信息 **/ public static WxUser getUserByOpenid(String openid) { try { String url = "http://127.0.0.1:8080/control_center/queryUser?openid=" + openid + "&code=" + VerifyCode.getCode(); // 连接中控服务器,获取openid对应的用户信息 String json_string = HttpGetRequest.doGet(url); if (json_string != null) { // info("源字符串:" + json_string); // 对json_string解码(数据已被编码,中文乱码) json_string = Escape.unescape(json_string); // json_string已被加密,此处需对信息进行解密(!可能需要分段解密) json_string = RSAUtils.decrypt(json_string, RSAUtils.getPrkey()); // info("解码解密:" + json_string); JSONObject json = JSONObject.fromObject(json_string); int ret = json.getInt("ret"); // 数据返回成功 if (ret == 0) { JSONObject data = json.getJSONObject("data"); return (WxUser) JSONObject.toBean(data.getJSONObject("user"), WxUser.class); } // code码失效 else if (ret == 10001) { info("'中控中心'查询:,code码失效!"); } // 不存在此openid的用户信息 else if (ret == 10002) { info("'中控中心'查询:,不存在此openid的用户信息!"); } // 参数解析失败(可能是上传的密钥问题) else if (ret == 10003) { info("'中控中心'查询:,参数解析失败(可能是上传的密钥问题)"); } } else { info("'中控中心'DBServer无响应!"); } } catch (Exception e) { e.printStackTrace(); } return null; } /** 尝试减去用户积分 **/ public static Boolean subSocreByOpenid(String openid, Integer socre) { try { String url = "http://127.0.0.1:8080/control_center/subSocre?openid=" + openid + "&code=" + VerifyCode.getCode() + "&socre=" + socre; // 连接中控服务器,获取openid对应的用户信息 String json_string = HttpGetRequest.doGet(url); if (json_string != null) { // info("源字符串:" + json_string); // 对json_string解码(数据已被编码,中文乱码) json_string = Escape.unescape(json_string); // info("解码解密:" + json_string); JSONObject json = JSONObject.fromObject(json_string); int ret = json.getInt("ret"); // 数据返回成功 if (ret == 0) { JSONObject data = json.getJSONObject("data"); return data.getBoolean("success"); } // code码失效 else if (ret == 10001) { info("'中控中心'查询:,code码失效!"); } // 参数解析失败(可能是上传的密钥问题) else if (ret == 10003) { info("'中控中心'查询:,参数解析失败(可能是上传的密钥问题)"); } } else { info("'中控中心'DBServer无响应!"); } } catch (Exception e) { e.printStackTrace(); } return false; } /** 保存一位用户的信息 **/ public static Boolean saveWechatUser(WxUser wxUser) { try { String s_data = getJSON("user", wxUser).toString(); // 对s_data进行加密(使用server_puKey) s_data = RSAUtils.encrypt(s_data, RSAUtils.getPukey(VerifyCode.getServerKey())); String url = "http://127.0.0.1:8080/control_center/saveUser?data=" + Escape.escape(s_data) + "&code=" + VerifyCode.getCode(); // 连接中控服务器,获取openid对应的用户信息 String json_string = HttpGetRequest.doGet(url); if (json_string != null) { // 对json_string解码(数据已被编码,中文乱码) json_string = Escape.unescape(json_string); JSONObject json = JSONObject.fromObject(json_string); int ret = json.getInt("ret"); // 数据返回成功 if (ret == 0) { JSONObject data = json.getJSONObject("data"); return data.getBoolean("success"); } // code码失效 else if (ret == 10001) { info("'中控中心'查询:,code码失效!"); } // 参数解析失败(可能是上传的密钥问题) else if (ret == 10003) { info("'中控中心'查询:,参数解析失败(可能是上传的密钥问题)"); } } else { info("'中控中心'DBServer无响应!"); } } catch (Exception e) { e.printStackTrace(); } return false; } }
RSAutils加密丶解密类( Base64编码,需视当前编译环境,自行更改 )
/** * 加解密RSA方式 从字符串中获取加密秘钥和从文件中获取加密秘钥 */ public class RSAUtils { // 指定加密算法为RSA private static final String ALGORITHM = "RSA"; // 密钥长度,用来初始化密钥(常用512/1024/2048/4096) private static final int KEYSIZE = 1024; // 密钥对象 private static PublicKey puKey = null; private static PrivateKey prKey = null; // 加密字符串最大长度(默认KEYSIZE=1024) private static int MAX_ENCRYPT_BLOCK = 117; // MAX_ENCRYPT_BLOCK=KEYSIZE/8-11; // 解密字符串最大长度(默认KEYSIZE=1024) private static int MAX_DECRYPT_BLOCK = 128; // MAX_DECRYPT_BLOCK=KEYSIZE/8; /** 公钥加密 **/ public static String encrypt(String src, PublicKey key) throws Exception { return encode(encrypt(key, src.getBytes())); } /** 私钥解密 **/ public static String decrypt(String src, PrivateKey key) throws Exception { return new String(decrypt(key, decode(src))); } /** * 获取公钥(带标签) **/ public static String getPukeyTag() { if (puKey == null) initKeyPair(); return "-----BEGIN PUBLIC KEY-----\n" + getPukeyStr() + "\n-----END PUBLIC KEY-----"; } public static String getPukeyStr() { if (puKey == null) initKeyPair(); return new String(encode(puKey.getEncoded())); } public static PublicKey getPukey() { return puKey; } /** * 从字符串中加载公钥 */ public static RSAPublicKey getPukey(String publicKeyStr) throws Exception { try { byte[] buffer = decode(publicKeyStr); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("无此算法"); } catch (InvalidKeySpecException e) { throw new Exception("公钥非法"); } catch (NullPointerException e) { throw new Exception("公钥数据为空"); } } /** * 获取私钥 (带标签) **/ public static String getPrkeyTag() { if (prKey == null) initKeyPair(); return "-----BEGIN RSA PRIVATE KEY-----\n" + getPrkeyStr() + "\n-----END RSA PRIVATE KEY-----"; } public static String getPrkeyStr() { if (prKey == null) initKeyPair(); return new String(encode(prKey.getEncoded())); } public static PrivateKey getPrkey() { return prKey; } /** * 从字符串中加载私钥 */ public static RSAPrivateKey getPrivateKey(String privateKeyStr) throws Exception { try { byte[] buffer = decode(privateKeyStr); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("无此算法"); } catch (InvalidKeySpecException e) { throw new Exception("私钥非法"); } catch (NullPointerException e) { throw new Exception("私钥数据为空"); } } // 生成密钥对 private static void initKeyPair() { // RSA算法要求有一个可信任的随机数源 SecureRandom secureRandom = new SecureRandom(); try { // 为RSA算法创建一个KeyPairGenerator对象 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM); // 利用上面的随机数据源初始化这个KeyPairGenerator对 keyPairGenerator.initialize(KEYSIZE, secureRandom); // 生成密匙对 KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 得到私钥 prKey = keyPair.getPrivate(); // 得到公钥 puKey = keyPair.getPublic(); // 加解密数据最大长度 MAX_DECRYPT_BLOCK = KEYSIZE / 8; MAX_ENCRYPT_BLOCK = MAX_DECRYPT_BLOCK - 11; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); prKey = null; puKey = null; } } // 解密算法(分段) private static byte[] decrypt(PrivateKey privateKey, byte[] encryptedData) throws Exception { Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm()); cipher.init(2, privateKey); int inputLen = encryptedData.length; int offSet = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int i = 0; inputLen - offSet > 0; offSet = i * MAX_DECRYPT_BLOCK) { byte[] cache; if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); ++i; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } // 加密算法(分段) private static byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception { Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); cipher.init(1, publicKey); int inputLen = data.length; int offSet = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int i = 0; inputLen - offSet > 0; offSet = i * MAX_ENCRYPT_BLOCK) { byte[] cache; if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); ++i; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } /** Base64解码 **/ public static String encode(byte[] src) { return (new Base64Encoder()).encode(src); } /** base64编码 **/ public static byte[] decode(String src) { return (new Base64Encoder()).decode(src); } }
Escape编码类(与js的escape()丶unescape()保持一致),在传输中防止乱码
/** * js语言escape()编码丶解码方法 **/ public class Escape { public static String escape(String src) { int i; char j; StringBuffer tmp = new StringBuffer(); tmp.ensureCapacity(src.length() * 6); for (i = 0; i < src.length(); i++) { j = src.charAt(i); if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j)) tmp.append(j); else if (j < 256) { tmp.append("%"); if (j < 16) tmp.append("0"); tmp.append(Integer.toString(j, 16)); } else { tmp.append("%u"); tmp.append(Integer.toString(j, 16)); } } return tmp.toString(); } public static String unescape(String src) { StringBuffer tmp = new StringBuffer(); tmp.ensureCapacity(src.length()); int lastPos = 0, pos = 0; char ch; while (lastPos < src.length()) { pos = src.indexOf("%", lastPos); if (pos == lastPos) { if (src.charAt(pos + 1) == 'u') { ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16); tmp.append(ch); lastPos = pos + 6; } else { ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16); tmp.append(ch); lastPos = pos + 3; } } else { if (pos == -1) { tmp.append(src.substring(lastPos)); lastPos = src.length(); } else { tmp.append(src.substring(lastPos, pos)); lastPos = pos; } } } return tmp.toString(); } /** * @disc 对字符串重新编码 * @param src * @return */ public static String isoToGB(String src) { String strRet = null; try { strRet = new String(src.getBytes("ISO_8859_1"), "GB2312"); } catch (Exception e) { } return strRet; } /** * @disc 对字符串重新编码 * @param src * @return */ public static String isoToUTF(String src) { String strRet = null; try { strRet = new String(src.getBytes("ISO_8859_1"), "UTF-8"); } catch (Exception e) { } return strRet; } }
其他一些方法:
public class Global { // debug等级,0不显示,1错误,2debug,3info private static final Integer debugLevel = 3; /** INFO信息输出 **/ public static void info(Object object) { if (debugLevel > 2) { System.out.println(Config.server_name + "信息 : " + object); Logger.info(Config.server_name + "信息 : " + object); } } /** DEBUG信息输出 **/ public static void debug(Object object) { if (debugLevel > 1) { System.out.println(Config.server_name + "调试 : " + object); Logger.debug(Config.server_name + "调试 : " + object); } } /** ERROR信息输出 **/ public static void error(Object object) { if (debugLevel > 0) { System.out.println(Config.server_name + "错误 : " + object); Logger.error(Config.server_name + "错误 : " + object); } } /** 将对象转化为String数组 **/ public static String[] string(Object... args) { String[] str_arr = new String[args.length]; for (int i = 0; i < args.length; i++) str_arr[i] = (String) args[i]; return str_arr; } /** 快速建立JSON对象 **/ public static JSONObject getJSON(Object... args) { JSONObject json = new JSONObject(); if (args.length % 2 == 0) { for (int i = 0; i < args.length; i += 2) { json.put(args[i], args[i + 1]); } } else { Global.error("Global.getJSON() 's args.length% != 0"); } return json; } /** 获取一个length长度的随机字符串 ***/ public static String getRandomStr(int length) { // 定义一个字符串(A-Z,a-z,0-9)即62位; String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890"; // 随机数种子 Random random = getRandom(); StringBuffer strbuff = new StringBuffer(); for (int i = 0; i < length; ++i) { // 字符串长度 int number = random.nextInt(62); // 产生0-61的数字 strbuff.append(str.charAt(number)); // 将产生的数字通过length次承载到strbuff中 } // 将承载的字符转换成字符串 return strbuff.toString(); } /** 获取一个random对象 . (基于Date.now's getTime()作为种子) **/ public static Random getRandom() { return new Random(new Date().getTime()); } }
/** * 错误丶调试信息输出到本地txt文件 * */ public class Logger { // 项目编译(运行)路径 private static String runpath = null; /** 获取项目编译(运行)路径 **/ private static String getRun() { if (runpath == null) { try { runpath = Logger.class.getClassLoader().getResource("").toURI().getPath(); runpath = runpath.substring(0, runpath.indexOf(Config.server_name)) + Config.server_name; } catch (URISyntaxException e) { System.out.println("获取项目路径出现异常!"); e.printStackTrace(); runpath = null; } } return runpath; } /** 错误输出日志 ***/ public static void error(Object message) { FileOutputStream writer = null; try { // 获取文件路径 String path = getRun() + "/logs/error.txt"; // 如果文件不存在,则创建对应文件 File file = new File(path); if (!file.exists()) { new File(file.getParent()).mkdir(); file.createNewFile(); } // 写入的数据 String data = new SimpleDateFormat("yyyy年MM月dd日 EEEE HH:mm:ss") .format(new Date(System.currentTimeMillis())) + "\n" + message.toString() + "\n\n\n"; // 创建写入流(追加文末写入) writer = new FileOutputStream(path, true); writer.write(data.getBytes()); writer.flush(); writer.close(); writer = null; } catch (IOException e) { System.out.println(Config.server_name + "错误:Logger.error() throw exception!"); e.printStackTrace(); } } /** 调试输出日志 ***/ public static void debug(Object message) { FileOutputStream writer = null; try { // 获取文件路径 String path = getRun() + "/logs/debug.txt"; // 如果文件不存在,则创建对应文件 File file = new File(path); if (!file.exists()) { new File(file.getParent()).mkdir(); file.createNewFile(); } // 写入的数据 String data = new SimpleDateFormat("yyyy年MM月dd日 EEEE HH:mm:ss") .format(new Date(System.currentTimeMillis())) + "\n" + message.toString() + "\n\n\n"; // 创建写入流(追加文末写入) writer = new FileOutputStream(path, true); writer.write(data.getBytes()); writer.flush(); writer.close(); writer = null; } catch (IOException e) { System.out.println(Config.server_name + "错误:Logger.debug() throw exception!"); e.printStackTrace(); } } /** 错误输出日志 ***/ public static void info(Object message) { FileOutputStream writer = null; try { // 获取文件路径 String path = getRun() + "/logs/info.txt"; // 如果文件不存在,则创建对应文件 File file = new File(path); if (!file.exists()) { new File(file.getParent()).mkdir(); file.createNewFile(); } // 写入的数据 String data = new SimpleDateFormat("yyyy年MM月dd日 EEEE HH:mm:ss") .format(new Date(System.currentTimeMillis())) + "\n" + message.toString() + "\n\n\n"; // 创建写入流(追加文末写入) writer = new FileOutputStream(path, true); writer.write(data.getBytes()); writer.flush(); writer.close(); writer = null; } catch (IOException e) { System.out.println(Config.server_name + "错误:Logger.info() throw exception!"); e.printStackTrace(); } } /** servlet日志 ***/ public static void servlet(Object message) { FileOutputStream writer = null; try { // 获取文件路径 String path = getRun() + "/logs/servlet.txt"; // 如果文件不存在,则创建对应文件 File file = new File(path); if (!file.exists()) { new File(file.getParent()).mkdir(); file.createNewFile(); } // 写入的数据 String data = new SimpleDateFormat("yyyy年MM月dd日 EEEE HH:mm:ss") .format(new Date(System.currentTimeMillis())) + "\n==================================================================================\n" + message.toString() + "\n==================================================================================\n\n\n"; // 创建写入流(追加文末写入) writer = new FileOutputStream(path, true); writer.write(data.getBytes()); writer.flush(); writer.close(); writer = null; } catch (IOException e) { System.out.println(Config.server_name + "错误:Logger.servlet() throw exception!"); e.printStackTrace(); } } }
HttpUtils
public class HttpUtils { public static void write(HttpServletResponse response, Object o) { try { response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.println(o.toString()); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void write(HttpServletResponse response, String o) { try { response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.println(o); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void writeJson(HttpServletResponse respone, String result) { try { respone.setHeader("Access-Control-Allow-Origin", "*"); respone.setCharacterEncoding("utf-8"); respone.setContentType("application/json;charset=utf-8"); PrintWriter out = respone.getWriter(); out.print(result); out.flush(); out.close(); } catch (Exception e) { // //System.out.println("Comm_Util_writeJson---->" + e); e.printStackTrace(); } } }