您的位置:首页 > 编程语言 > Java开发

Java Web 常用工具类(持续更新)

2017-02-19 21:41 525 查看
1、ExceptionUtil

import java.io.PrintWriter;
import java.io.StringWriter;

public class ExceptionUtil {
/**S
* 获取异常的堆栈信息
*
* @param t
* @return
*/
public static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
t.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
}


2、FastDFSClient

import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

public class FastDFSClient {
private TrackerClient trackerClient = null;
private TrackerServer trackerServer = null;
private StorageServer storageServer = null;
//使用StorageClient1进行上传
private StorageClient1 storageClient1 = null;

public FastDFSClient(String conf) throws Exception {
//获取classpath路径下配置文件"fdfs_client.conf"的路径
//conf直接写相对于classpath的位置,不需要写classpath:
String configPath = this.getClass().getClassLoader().getResource(conf).getFile();
System.out.println(configPath);
ClientGlobal.init(configPath);

trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageServer = trackerClient.getStoreStorage(trackerServer);
storageClient1 = new StorageClient1(trackerServer, storageServer);
}

public String uploadFile(byte[] file_buff, String file_ext_name) throws Exception {

String result = storageClient1.upload_file1(file_buff, file_ext_name, null);

return result;
}

public String uploadFile(byte[] file_buff) throws Exception {

String result = storageClient1.upload_file1(file_buff, null, null);

return result;
}

public String uploadFile(String local_filename, String file_ext_name) throws Exception {

String result = storageClient1.upload_file1(local_filename, file_ext_name, null);

return result;
}
}


3、HttpClientUtil

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

public static String doGet(String url, Map<String, String>param) {

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();

// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);

// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

public static String doGet(String url) {
return doGet(url, null);
}

public static String doPost(String url, Map<String, String>param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair>paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return resultString;
}

public static String doPost(String url) {
return doPost(url, null);
}

public static String doPostJson(String url,String json) {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

String resultString = "";
CloseableHttpResponse response = null;
try {
//创建post请求
HttpPost httpPost = new HttpPost(url);
//创建请求内容
StringEntity entity = new StringEntity(json,ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
//执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(),"UTF-8");

} catch (Exception e) {
e.printStackTrace();
}finally {
try {
response.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return resultString;
}
}


4、JsonUtils

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();

/**
* 将对象转换成json字符串。
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}

/**
* 将json结果集转化为对象
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 将json数据转换成pojo对象list
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}

return null;
}

}


5、CookieUtils

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* Cookie 工具类
*
*/
public final class CookieUtils {

/**
* 得到Cookie的值, 不编码
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, false);
}

/**
* 得到Cookie的值,
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}

/**
* 得到Cookie的值,
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}

/**
* 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue) {
setCookie(request, response, cookieName, cookieValue, -1);
}

/**
* 设置Cookie的值 在指定时间内生效,但不编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage) {
setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
}

/**
* 设置Cookie的值 不设置生效时间,但编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, boolean isEncode) {
setCookie(request, response, cookieName, cookieValue, -1, isEncode);
}

/**
* 设置Cookie的值 在指定时间内生效, 编码参数
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage, boolean isEncode) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
}

/**
* 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage, String encodeString) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
}

/**
* 删除Cookie带cookie域名
*/
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName) {
doSetCookie(request, response, cookieName, "", -1, false);
}

/**
* 设置Cookie的值,并使其在指定时间内生效
*
* @param cookieMaxage cookie生效的最大秒数
*/
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
try {
if (cookieValue == null) {
cookieValue = "";
} else if (isEncode) {
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0)
cookie.setMaxAge(cookieMaxage);
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
System.out.println(domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 设置Cookie的值,并使其在指定时间内生效
*
* @param cookieMaxage cookie生效的最大秒数
*/
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
try {
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0)
cookie.setMaxAge(cookieMaxage);
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
System.out.println(domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 得到cookie的域名
*/
private static final String getDomainName(HttpServletRequest request) {
String domainName = null;

String serverName = request.getRequestURL().toString();
if (serverName == null || serverName.equals("")) {
domainName = "";
} else {
serverName = serverName.toLowerCase();
serverName = serverName.substring(7);
final int end = serverName.indexOf("/");
serverName = serverName.substring(0, end);
final String[] domains = serverName.split("\\.");
int len = domains.length;
if (len > 3) {
// www.xxx.com.cn
domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
} else if (len <= 3 && len > 1) {
// xxx.com or xxx.cn
domainName = "." + domains[len - 2] + "." + domains[len - 1];
} else {
domainName = serverName;
}
}

if (domainName != null && domainName.indexOf(":") > 0) {
String[] ary = domainName.split("\\:");
domainName = ary[0];
}
return domainName;
}

}


6、CommonUtil

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.github.pagehelper.StringUtil;

public class CommonUtil
{

//private static final String EN_NAME = "en_name";

//private static final String ZH_NAME = "zh_name";

//private static final String ZB_NAME = "zb_name";

/**
* 获取HttpServletRequest;
*
* @return [参数说明]
*
* @return HttpServletRequest [返回类型说明]
* @exception throws
*                [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static HttpServletRequest getHttpRequest()
{
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}

/**
* 获取文件扩展名;
*
* @param fileName
* @return [参数说明]
*
* @return String [返回类型说明]
* @exception throws
*                [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static String getFileExtension(String fileName)
{
if (StringUtil.isEmpty(fileName))
{
return null;
}
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}

/**
* 获取文件扩展名;
*
* @param fileName
* @return [参数说明]
*
* @return String [返回类型说明]
* @exception throws
*                [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static String getFileName(String fileName)
{
String fileExtension = getFileExtension(fileName);
return fileName.substring(0, fileName.lastIndexOf(fileExtension) - 1);
}

/**
* 用来去掉List中空值和相同项的。
*
* @param list
* @return
*/
public static List<String> removeSameItem(List<String> list)
{
List<String> difList = new ArrayList<String>();
for (String t : list)
{
if (t != null && !difList.contains(t))
{
difList.add(t);
}
}
return difList;
}

/**
* 返回用户的IP地址
*
* @param request
* @return
*/
public static String toIpAddr(HttpServletRequest request)
{
String ip = request.getHeader("X-Forwarded-For");
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.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return ip;
}

/**
* 去除字符串最后一个逗号,若传入为空则返回空字符串
*
* @descript
* @param para
* @return
* @author zoomy
* @date 2015年3月29日
* @version 1.0
*/
public static String trimComma(String para)
{
if (StringUtils.isNotBlank(para))
{
if (para.endsWith(","))
{
return para.substring(0, para.length() - 1);
} else
{
return para;
}
} else
{
return "";
}
}

public static Integer valueOf(String value, int def)
{
try
{
if (StringUtil.isNotEmpty(value))
{
return Integer.parseInt(value);
}
} catch (Exception e)
{
return def;
}
return def;
}

public static Integer valueOf(String value)
{
return valueOf(value, 0);
}

/**
* html转议
*
* @descript
* @param content
* @return
* @author LJN
* @date 2015年4月27日
* @version 1.0
*/
public static String htmltoString(String content)
{
if (content == null)
return "";
String html = content;
html = html.replace("'", "'");
html = html.replaceAll("&", "&");
html = html.replace("\"", """); // "
html = html.replace("\t", "  ");// 替换跳格
html = html.replace(" ", " ");// 替换空格
html = html.replace("<", "<");
html = html.replaceAll(">", ">");

return html;
}

/**
* html转议
*
* @descript
* @param content
* @return
* @author LJN
* @date 2015年4月27日
* @version 1.0
*/
public static String stringtohtml(String content)
{
if (content == null)
return "";
String html = content;
html = html.replace("'", "'");
html = html.replaceAll("&", "&");
html = html.replace(""", "\""); // "
html = html.replace("  ", "\t");// 替换跳格
html = html.replace(" ", " ");// 替换空格
html = html.replace("<", "<");
html = html.replaceAll(">", ">");
return html;
}

public static Long[] stringArrayToLongArray(String str[])
{
Long[] num = null;
if (str != null && str.length > 0)
{
int len = str.length;
num = new Long[len];
for (int i = 0; i < len; i++)
{
num[i] = Long.valueOf(str[i]);
}
}
return num;
}

public static String fromDateH()
{
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return format1.format(new Date());
}

/**
* 返回当前时间 格式:yyyy-MM-dd
*
* @return String
*/
public static String fromDateY()
{
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
return format1.format(new Date());
}
}


7、PropertiesUtils

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Reader;
import java.util.Iterator;
import java.util.Properties;
import java.util.Map.Entry;

import org.apache.ibatis.io.Resources;

/**
* 对属性文件操作的工具类 获取,新增,修改 注意: 以下方法读取属性文件会缓存问题,在修改属性文件时,不起作用, InputStream in =
* PropertiesUtils.class.getResourceAsStream("/config.properties"); 解决办法: String
* savePath = PropertiesUtils.class.getResource("/config.properties").getPath();
*/
public class PropertiesUtils
{
/**
* 获取属性文件的数据 根据key获取值
*
* @param fileName
*            文件名 (注意:加载的是src下的文件,如果在某个包下.请把包名加上)
* @param key
* @return
*/
public static String findPropertiesKey(String key)
{

try
{
Properties prop = getProperties();
return prop.getProperty(key);
} catch (Exception e)
{
return "";
}

}

public static void main(String[] args)
{
Properties prop = new Properties();
InputStream in = PropertiesUtils.class.getResourceAsStream("/config.properties");
try
{
prop.load(in);
Iterator<Entry<Object, Object>> itr = prop.entrySet().iterator();
while (itr.hasNext())
{
Entry<Object, Object> e = (Entry<Object, Object>) itr.next();
System.err.println((e.getKey().toString() + "" + e.getValue().toString()));
}
in.close();
} catch (Exception e)
{

}
}

/**
* 返回 Properties
*
* @param fileName
*            文件名 (注意:加载的是src下的文件,如果在某个包下.请把包名加上)
* @param
* @return
*/
public static Properties getProperties()
{
Properties prop = new Properties();
try
{
Reader reader = Resources.getResourceAsReader("/config.properties");
prop.load(reader);
reader.close();
} catch (Exception e)
{
return null;
}
return prop;
}

public static Properties getjdbcProperties()
{
Properties prop = new Properties();
try
{
Reader reader = Resources.getResourceAsReader("/jdbc.properties");
prop.load(reader);
reader.close();
} catch (Exception e)
{
return null;
}
return prop;
}

/**
* 写入properties信息
*
* @param key
*            名称
* @param value
*            值
*/
public static void modifyProperties(String key, String value)
{
try
{
// 从输入流中读取属性列表(键和元素对)
Properties prop = getProperties();
prop.setProperty(key, value);
String path = PropertiesUtils.class.getResource("/config.properties").getPath();
FileOutputStream outputFile = new FileOutputStream(path);
prop.store(outputFile, "modify");
outputFile.close();
outputFile.flush();
} catch (Exception e)
{
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: