1.校验手机号码
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* @author M
* @date 创建时间:2017年6月20日 下午3:29:22
* @version
* @parameter
* @since
* @return
*/
public class PhoneFormatCheckUtil {
/**
* 大陆号码或香港号码均可
*/
public static boolean isPhoneLegal(String str)throws PatternSyntaxException {
return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
}
/**
* 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数
* 此方法中前三位格式有:
* 13+任意数
* 15+除4的任意数
* 18+除1和4的任意数
* 17+除9的任意数
* 147
*/
public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}
/**
* 香港手机号码8位数,5|6|8|9开头+7位任意数
*/
public static boolean isHKPhoneLegal(String str)throws PatternSyntaxException {
String regExp = "^(5|6|8|9)\\d{7}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}
}
2.获取时间
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static Date getCurrentDate(){
return new Date(System.currentTimeMillis());
}
/**
* 获取指定毫秒数前的日期
* @param oriDate
* @param interval
* @return
*/
public static Date getLastSpecificDate(Date oriDate, Long interval){
Long mmOri = oriDate.getTime();
Long mmDest = mmOri-interval;
Date destDate = new Date(mmDest);
return destDate;
}
/**
* 获取当天开始时间
* @param
* @param
* @return todayBeginDate("yyyy-MM-dd 00:00:00")
*/
public static Date getTodayBeginDate(){
Date todayBeginDate = new Date();
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal_1 = Calendar.getInstance();
String firstDay = format.format(cal_1.getTime())+" 00:00:00";
todayBeginDate = sdf.parse(firstDay);
} catch (ParseException e) {
e.printStackTrace();
}
return todayBeginDate;
}
/**
* 获取当天结束时间
* @param
* @param
* @return todayEndDate("yyyy-MM-dd 23:59:59")
*/
public static Date getTodayEndDate(){
Date todayEndDate = new Date();
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal_1 = Calendar.getInstance();
String firstDay = format.format(cal_1.getTime())+" 23:59:59";
todayEndDate = sdf.parse(firstDay);
} catch (ParseException e) {
e.printStackTrace();
}
return todayEndDate;
}
/**
* 获取当月开始时间
* @param
* @param
* @return firstMonDate("yyyy-MM-dd 00:00:00")
*/
public static Date getFirstMonDate(){
Date firstMonDate = new Date();
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal_1 = Calendar.getInstance();
cal_1.add(Calendar.MONTH, 0);
cal_1.set(Calendar.DAY_OF_MONTH,1);
String firstDay = format.format(cal_1.getTime())+" 00:00:00";
firstMonDate = sdf.parse(firstDay);
} catch (ParseException e) {
e.printStackTrace();
}
return firstMonDate;
}
/**
* 获取当月结束时间
* @param
* @param
* @return endMonDate("yyyy-MM-dd 23:59:59")
*/
public static Date getEndMonDate(){
Date endMonDate = new Date();
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal_1 = Calendar.getInstance();
cal_1.add(Calendar.MONTH, 1);
cal_1.set(Calendar.DAY_OF_MONTH,0);
String firstDay = format.format(cal_1.getTime())+" 23:59:59";
endMonDate = sdf.parse(firstDay);
} catch (ParseException e) {
e.printStackTrace();
}
return endMonDate;
}
/**
* 获取当前周的开始时间(输出的是上个星期周日的日期)
* @param
* @param
* @return weekFirstDay("yyyy-MM-dd 00:00:00")
*/
public static Date getWeekFirstDay() {
Date weekFirstDay = new Date();
try {
Calendar cal =Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
String firstDay = format.format(cal.getTime());
weekFirstDay = df.parse(firstDay);
} catch (ParseException e) {
e.printStackTrace();
}
return weekFirstDay;
}
/**
* 获取当前周的结束时间
* @param
* @param
* @return weekEndDay("yyyy-MM-dd 59:59:59")
*/
public static Date getWeekEndDay() {
Date weekEndDay = new Date();
try {
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.add(Calendar.WEEK_OF_YEAR, 1);
String firstDay = format.format(cal.getTime())+ " 23:59:59";
weekEndDay = df.parse(firstDay);
} catch (ParseException e) {
e.printStackTrace();
}
return weekEndDay;
}
/**
* 获取当年的开始时间
* @param
* @param
* @return firstYearDate("yyyy-MM-dd 00:00:00")
*/
public static Date getFirstYearDate(){
Date firstYearDate = new Date();
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal_1 = Calendar.getInstance();
cal_1.add(Calendar.YEAR, 0);
cal_1.set(Calendar.DAY_OF_YEAR,1);
String firstDay = format.format(cal_1.getTime())+" 00:00:00";
firstYearDate = sdf.parse(firstDay);
} catch (ParseException e) {
e.printStackTrace();
}
return firstYearDate;
}
/**
* 获取当年的结束时间
* @param
* @param
* @return endYearDate("yyyy-MM-dd 59:59:59")
*/
public static Date getEndYearDate(){
Date endYearDate = new Date();
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal_1 = Calendar.getInstance();
cal_1.add(Calendar.YEAR, 1);
cal_1.set(Calendar.DAY_OF_YEAR,-1);
String firstDay = format.format(cal_1.getTime())+" 23:59:59";
endYearDate = sdf.parse(firstDay);
} catch (ParseException e) {
e.printStackTrace();
}
return endYearDate;
}
}
3.后台get和post请求(跨域),getsession,response
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.dadi.base.WebConstants;
import com.dadi.common.entity.User;
public class HttpUtils {
public final static String Error_perfix = "ERROR:";
public final static String SESSION_ID = "sessionId";
public static final String RE_LOGIN_FLAG = "--NEED_TO_RELOGIN--";
/**
* 判断是不是ajax请求
* @param request
* @return
*/
public static boolean isAjax(ServletRequest request){
return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"));
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
Map<String, List<String>> map = connection.getHeaderFields();
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
return result;
}
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* post方法 参数为json对象
* @param url
* @param jsonParam 封装为json对象的参数;
* @return
*/
public static String sendPost(String url,JSONObject jsonParam) {
try{
URL realUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(jsonParam.toString().getBytes("UTF-8"));
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
System.out.println(sb);
reader.close();
connection.disconnect();
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
return HttpUtils.Error_perfix+"url解析异常!";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return HttpUtils.Error_perfix+"不支持的编码格式!";
} catch (IOException e) {
e.printStackTrace();
return HttpUtils.Error_perfix+"服务端异常!";
}
}
/**
* 获取session
*
* @return
*/
public static HttpSession getSession() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
return request.getSession();
}
/**
* 获取当前用户
*
* @return
*/
public static User getCurrentUser() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
return (User) request.getSession().getAttribute(WebConstants.CUR_USER);
}
/**
* 下载远程文件到指定位置
* @param url 文件远程Url
* @param destPath 目标位置绝对路径,包含文件名
* @return 返回存储后的文件路径包,含文件名
* @throws Exceptio,
*/
public static String getRemoteFile(String url,String destPath) {
InputStream is = null;
try {
URL urlGet = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlGet
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
connection.connect();
is = connection.getInputStream();
FileUtil.saveFileToDisk(is,destPath);
} catch (Exception e) {
e.printStackTrace();
}
return destPath;
}
/**
* 获取http响应信息
*
* @param code
* 响应代码
* @param msg
* 响应消息
* @param data
* 响应数据
* @return
*/
public static Map<String, Object> getResponse(int code, String msg, Object data) {
Map<String, Object> rsp = new HashMap<String, Object>();
if (code != 0) {
rsp.put("code", code);
}
if (msg != null && !"".equals(msg)) {
rsp.put("msg", msg);
}
if (data != null) {
rsp.put("data", data);
}
return rsp;
}
/**
* 获取http响应信息
*
* @param code
* 响应代码
* @param msg
* 响应消息
* @param data
* 响应数据
* @return
*/
public static Map<String, Object> getResponse(int code) {
Map<String, Object> rsp = new HashMap<String, Object>();
switch (code) {
case 200:
rsp = getResponse(code, "操作成功", null);
break;
case 201:
rsp = getResponse(code, "参数异常", null);
case 400:
rsp = getResponse(code, "服务端异常!", null);
default:
break;
}
return rsp;
}
}