常用工具类

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) {
            // TODO Auto-generated catch block
            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) {
            // TODO Auto-generated catch block
            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);//设置为1号,当前日期既为本月第一天 
            String firstDay = format.format(cal_1.getTime())+" 00:00:00";
            firstMonDate = sdf.parse(firstDay);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            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) {
            // TODO Auto-generated catch block
            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) {
            // TODO Auto-generated catch block
            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) {
            // TODO Auto-generated catch block
            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);//设置为1号,当前日期既为本月第一天 
                String firstDay = format.format(cal_1.getTime())+" 00:00:00";
                firstYearDate = sdf.parse(firstDay);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                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);//设置为1号,当前日期既为本月第一天 
                String firstDay = format.format(cal_1.getTime())+" 23:59:59";
                endYearDate = sdf.parse(firstDay);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                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);
            // 打开和URL之间的连接
            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));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            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块来关闭输入流
        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);
            // 打开和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)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            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块来关闭输出流、输入流
        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.writeBytes(obj.toString());//这个中文会乱码
               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) {
               // TODO Auto-generated catch block
               e.printStackTrace();
               return HttpUtils.Error_perfix+"url解析异常!";
           } catch (UnsupportedEncodingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
               return HttpUtils.Error_perfix+"不支持的编码格式!";
           } catch (IOException e) {
               // TODO Auto-generated catch block
               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"); // 必须是get方式请求

            connection.setRequestProperty("Content-Type",

                    "application/x-www-form-urlencoded");

            connection.setDoOutput(true);

            connection.setDoInput(true);

            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒

            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

            connection.connect();

            // 获取文件转化为byte流

            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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值