public class IpUtils{
private static Map<String, Object> map = SingletonMap.getInstance();
/**
* blob转byte array
* @param blob
* @return
* @throws SQLException
*/
public static byte[] blob2ByteArr(Blob blob) throws SQLException {
if (blob == null) {
return null;
}
BufferedInputStream is = null;
try {
is = new BufferedInputStream(blob.getBinaryStream());
byte[] bytes = new byte[(int) blob.length()];
int len = bytes.length;
int offset = 0;
int read = 0;
while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {
offset += read;
}
return new String(bytes,"GBK").getBytes();
} catch (Exception e) {
return null;
} finally {
try {
is.close();
is = null;
} catch (IOException e) {
return null;
}
}
}
/**
* 获取ip地址
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip != null && !ip.isEmpty()) {
ip = ip.split(",")[0].trim();
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("PRoxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* 获取当前月份
* @return
*/
public static int getMonth() {
Calendar c = Calendar.getInstance();
return c.get(Calendar.MONTH) + 1;
}
/**
* 获取当前月份
* @return
*/
public static int getDay() {
Calendar c = Calendar.getInstance();
return c.get(Calendar.DAY_OF_MONTH);
}
/**
* 获得当前classpath路径
* @author ming
* */
public static String getClasspath (String path) {
if (path == null) {
path = "";
}
String classpath = Thread.currentThread().getContextClassLoader().getResource(path).getPath();
return classpath;
}
/**
* @author ming
* 获得默认路径
*/
public static String getDefaultClasspath () {
return getClasspath(null);
}
/**
* 获得webinfo路径
* @author ming
*/
public static String getWebInfPath () {
String classpath = getClasspath(null);
return classpath.replace("classes/", "");
}
/**
* @author ming
* 获得项目根目录路径
*/
public static String getRootPath () {
return (String)map.get(Constant.ROOT_PATH_KEY);
}
/**
* 保存文件到指定路径
* @param stream
* @param path
* @param filename
* @return
* @throws IOException
*/
@SuppressWarnings("unused")
public static File saveFileFromInputStream(InputStream stream, String path,
String filename) throws IOException {
File file = new File(path + File.separator + filename);
FileOutputStream fs = new FileOutputStream(file);
byte[] buffer = new byte[1024 * 1024];
int bytesum = 0;
int byteread = 0;
while ((byteread = stream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
fs.flush();
}
fs.close();
stream.close();
return file;
}
}
根据ip获取地理位置/天气信息等:
http://www.jb51.net/article/54287.htm
http://blog.csdn.net/wssiqi/article/details/8550951