用户日志留存所采用的技术手段
生活随笔
收集整理的這篇文章主要介紹了
用户日志留存所采用的技术手段
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
首先寫個注解類,用來標識方法滿足切入點
package com.enation.framework.database; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 表示對標記有xxx注解的類,做代理 注解@Retention可以用來修飾注解,是注解的注解,稱為元注解。 * Retention注解有一個屬性value,是RetentionPolicy類型的,Enum RetentionPolicy是一個枚舉類型, * 這個枚舉決定了Retention注解應該如何去保持,也可理解為Rentention 搭配 * RententionPolicy使用。RetentionPolicy有3個值:CLASS RUNTIME SOURCE * 用@Retention(RetentionPolicy * .CLASS)修飾的注解,表示注解的信息被保留在class文件(字節(jié)碼文件)中當程序編譯時,但不會被虛擬機讀取在運行的時候; * 用@Retention(RetentionPolicy.SOURCE * )修飾的注解,表示注解的信息會被編譯器拋棄,不會留在class文件中,注解的信息只會留在源文件中; * 用@Retention(RetentionPolicy.RUNTIME * )修飾的注解,表示注解的信息被保留在class文件(字節(jié)碼文件)中當程序編譯時,會被虛擬機保留在運行時, * 所以他們可以用反射的方式讀取。RetentionPolicy.RUNTIME * 可以讓你從JVM中讀取Annotation注解的信息,以便在分析程序的時候使用. * * 類和方法的annotation缺省情況下是不出現(xiàn)在javadoc中的,為了加入這個性質(zhì)我們用@Documented * java用 @interface Annotation{ } 定義一個注解 @Annotation,一個注解是一個類。 * @interface是一個關鍵字,在設計annotations的時候必須把一個類型定義為@interface,而不能用class或interface關鍵字 * * @author daizequn* */ @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MethodLog { String remark() default ""; String operType() default "0"; // String desc() default ""; }用戶日志實體
package com.enation.app.shop.core.model; import com.enation.framework.database.DynamicField; import com.enation.framework.database.PrimaryKeyField; /*** 用戶日志實體* @author daizequn * 2015-12-2*/ public class Log extends DynamicField {private Integer log_id;//主鍵IDprivate Integer member_id;//用戶idprivate String member_uname;//用戶賬號private String member_name;//用戶昵稱private String method;//操作方法private String methodargs;//方法參數(shù)(暫時不用到)private String allmethod;//完整操作方法private String html;//操作頁面private String des;//操作描述private String ipaddr;//操作ip private String pointkey;//搜索關鍵詞private Long staytime;//停留時間private String opentime;//打開頁面時間private String closetime;//關閉頁面時間@PrimaryKeyFieldpublic Integer getLog_id() {return log_id;}public void setLog_id(Integer log_id) {this.log_id = log_id;}public Integer getMember_id() {return member_id;}public void setMember_id(Integer member_id) {this.member_id = member_id;}public String getMember_uname() {return member_uname;}public void setMember_uname(String member_uname) {this.member_uname = member_uname;}public String getMember_name() {return member_name;}public void setMember_name(String member_name) {this.member_name = member_name;}public String getMethod() {return method;}public void setMethod(String method) {this.method = method;}public String getMethodargs() {return methodargs;}public void setMethodargs(String methodargs) {this.methodargs = methodargs;}public String getHtml() {return html;}public void setHtml(String html) {this.html = html;}public String getDes() {return des;}public void setDes(String des) {this.des = des;}public String getIpaddr() {return ipaddr;}public void setIpaddr(String ipaddr) {this.ipaddr = ipaddr;}public String getPointkey() {return pointkey;}public void setPointkey(String pointkey) {this.pointkey = pointkey;}public Long getStaytime() {return staytime;}public void setStaytime(Long staytime) {this.staytime = staytime;}public String getOpentime() {return opentime;}public void setOpentime(String opentime) {this.opentime = opentime;}public String getAllmethod() {return allmethod;}public void setAllmethod(String allmethod) {this.allmethod = allmethod;}public String getClosetime() {return closetime;}public void setClosetime(String closetime) {this.closetime = closetime;} }
在spring的xml文件上加上
<!-- 用戶日志 --><bean id="logManager" class="com.enation.app.shop.core.service.impl.LogManager" parent="baseSupport" />用戶日志接口
package com.enation.app.shop.core.service; import com.enation.app.shop.core.model.Log; import com.enation.framework.database.Page;/*** 用戶日志接口* 2015-12-2*/ public interface ILogManager {/*** 添加一個用戶日志* @param log* @return*/public int add(Log log);/*** 用戶行為日志數(shù)據(jù)* daizequn 2015-12-6*/Page memberBehaviorLogList(int page, int pageSize, String startDate,String endDate, String sortType);}用戶日志實現(xiàn)類
package com.enation.app.shop.core.service.impl; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.enation.app.shop.core.model.Log; import com.enation.app.shop.core.service.ILogManager; import com.enation.eop.sdk.database.BaseSupport; import com.enation.framework.database.Page;/*** 用戶日志操作業(yè)務實現(xiàn)* @author daizequn* 2015-12-2*/public class LogManager extends BaseSupport implements ILogManager {/*** 添加用戶日志記錄*/@Transactional(propagation = Propagation.REQUIRED)public int add(Log log) {this.baseDaoSupport.insert("log", log);Integer logid = this.baseDaoSupport.getLastId("log");log.setLog_id(logid);return logid;}/*** 用戶行為日志數(shù)據(jù)* daizequn 2015-12-6*/@Overridepublic Page memberBehaviorLogList(int page, int pageSize, String startDate, String endDate, String sortType) {// 返回打開頁面的時間段內(nèi)的用戶行為日志StringBuffer sql = new StringBuffer();sql.append("SELECT g.* FROM es_log g WHERE 1=1 ");if(startDate!=null&&!"".equals(startDate)){sql.append(" and g.opentime>= '"+startDate+"'");}if(endDate!=null&&!"".equals(endDate)){sql.append(" and g.closetime<= '"+endDate+"'");}if(sortType != null && ("ASC".equals(sortType) || "DESC".equals(sortType))){sql.append(" ORDER BY g.opentime " + sortType + " ");}else{sql.append(" ORDER BY g.opentime DESC ");}return this.baseDaoSupport.queryForPage(sql.toString(), page, pageSize, Log.class);}}在spring的xml文件上加上
<bean id="logAction" class="com.enation.app.shop.core.action.api.LogAction" scope="prototype"/> package com.enation.app.shop.core.action.api; import java.lang.reflect.Method; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import com.enation.app.base.core.model.Member; import com.enation.app.shop.core.model.Log; import com.enation.app.shop.core.service.impl.LogManager; import com.enation.app.shop.core.utils.DateUtils; import com.enation.app.shop.core.utils.IpUtils; import com.enation.eop.sdk.context.UserConext; import com.enation.framework.context.spring.SpringContextHolder; import com.enation.framework.context.webcontext.ThreadContextHolder; import com.enation.framework.database.MethodLog; /** * \ * * @Aspect 實現(xiàn)spring aop 切面(Aspect): * 一個關注點的模塊化,這個關注點可能會橫切多個對象。事務管理是J2EE應用中一個關于橫切關注點的很好的例子。 在Spring * AOP中,切面可以使用通用類(基于模式的風格) 或者在普通類中以 @Aspect 注解(@AspectJ風格)來實現(xiàn)。 * * AOP代理(AOP Proxy): AOP框架創(chuàng)建的對象,用來實現(xiàn)切面契約(aspect contract)(包括通知方法執(zhí)行等功能)。 * 在Spring中,AOP代理可以是JDK動態(tài)代理或者CGLIB代理。 注意:Spring * 2.0最新引入的基于模式(schema-based * )風格和@AspectJ注解風格的切面聲明,對于使用這些風格的用戶來說,代理的創(chuàng)建是透明的。 * @author q * */ @Component @Aspect public class LogAction { /*@Autowired private ILogManager manager; */public LogAction() { System.out.println("Aop"); } /** * 在Spring * 2.0中,Pointcut的定義包括兩個部分:Pointcut表示式(expression)和Pointcut簽名(signature * )。讓我們先看看execution表示式的格式: * 括號中各個pattern分別表示修飾符匹配(modifier-pattern?)、返回值匹配(ret * -type-pattern)、類路徑匹配(declaring * -type-pattern?)、方法名匹配(name-pattern)、參數(shù)匹配((param * -pattern))、異常類型匹配(throws-pattern?),其中后面跟著“?”的是可選項。 * * @param point * @throws Throwable */ @Pointcut("@annotation(com.enation.framework.database.MethodLog)") public void methodCachePointcut() { } // // @Before("execution(* com.wssys.controller.*(..))") // public void logAll(JoinPoint point) throws Throwable { // System.out.println("打印========================"); // } // // // @After("execution(* com.wssys.controller.*(..))") // public void after() { // System.out.println("after"); // } // 方法執(zhí)行的前后調(diào)用 // @Around("execution(* com.wssys.controller.*(..))||execution(* com.bpm.*.web.account.*.*(..))") // @Around("execution(* com.wssys.controller.*(..))") // @Around("execution(* org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(..))") //@Around("methodCachePointcut()") //@Around("execution(* com.enation.app.shop.core.action.api.*(..))") @Around("methodCachePointcut()") public Object commit(ProceedingJoinPoint point) throws Throwable { Member member = UserConext.getCurrentMember();Object object = null; if(member!=null){HttpServletRequest request = ThreadContextHolder.getInstance().getHttpRequest();String opentime=DateUtils.date2Str(new Date(), "yyyy-MM-dd HH:mm:ss");//操作時間String ipaddr = IpUtils.getRemoteAddr(request);//操作ipInteger memberid;//用戶idString memberuname;//用戶賬號 String membername; //用戶賬號memberid=member.getMember_id();memberuname = member.getUname(); membername = member.getName();String monthRemark = getMthodRemark(point); String monthName = point.getSignature().getName(); String packages = point.getThis().getClass().getName(); if (packages.indexOf("$$EnhancerBySpringCGLIB$$") > -1) { // 如果是CGLIB動態(tài)生成的類 try {packages = packages.substring(0, packages.indexOf("$$")); } catch (Exception ex) { ex.printStackTrace(); } } // Object[] method_param = null; // // Object object; // try { // method_param = point.getArgs(); //獲取方法參數(shù) // // String param=(String) point.proceed(point.getArgs()); object = point.proceed(); // } catch (Exception e) { // // 異常處理記錄日志..log.error(e); // throw e; // } Log log = new Log(); log.setIpaddr(ipaddr);//操作ip log.setMember_id(memberid);//用戶idlog.setMember_uname(memberuname);//用戶賬號log.setMember_name(membername);//用戶昵稱log.setMethod(packages + "." + monthName); //操作方法log.setDes(monthRemark); //操作描述log.setOpentime(opentime);//操作時間HttpServletRequest httpRequest=(HttpServletRequest)request; String strBackUrl = "http://" + request.getServerName() //服務器地址 + ":" + request.getServerPort() //端口號 + httpRequest.getContextPath() //項目名稱 + httpRequest.getServletPath() //請求頁面或其他地址 + "?" + (httpRequest.getQueryString()); //參數(shù) log.setAllmethod(strBackUrl);//完整操作方法//這里有點糾結(jié) 就是不好判斷第一個object元素的類型 只好通過 方法描述來 做一一 轉(zhuǎn)型感覺 這里 有點麻煩 可能是我對 aop不太了解 希望懂的高手給予我指點 //有沒有更好的辦法來記錄操作參數(shù) 因為參數(shù)會有 實體類 或者javabean這種參數(shù)怎么把它里面的數(shù)據(jù)都解析出來? // if ("刪除商品".equals(monthRemark)) { Member member2 = (Member) method_param[0]; // String method_paramArr=""; // if(method_param.length!=0){ // for(int i=0;i<=method_param.length;i++){ // method_paramArr=method_paramArr+method_param[i]; // } // log.setMethodargs(method_paramArr); // }else{ // log.setMethodargs("方法無參(不代表前臺沒傳參數(shù)過來)"); // } // } else { log.setMethodargs("操作參數(shù):" + method_param[0]); // } LogManager manager = SpringContextHolder.getBean("logManager");manager.add(log);return object;}return point.proceed();} // 方法運行出現(xiàn)異常時調(diào)用 // @AfterThrowing(pointcut = "execution(* com.wssys.controller.*(..))", // throwing = "ex") public void afterThrowing(Exception ex) { System.out.println("afterThrowing"); System.out.println(ex); } // 獲取方法的中文備注____用于記錄用戶的操作日志描述 public static String getMthodRemark(ProceedingJoinPoint joinPoint) throws Exception { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] method = targetClass.getMethods(); String methode = ""; for (Method m : method) { if (m.getName().equals(methodName)) { Class[] tmpCs = m.getParameterTypes(); if (tmpCs.length == arguments.length) { MethodLog methodCache = m.getAnnotation(MethodLog.class); if (methodCache != null) { methode = methodCache.remark(); } break; } } } return methode; } }LogtimeAction
package com.enation.app.shop.core.action.api; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.enation.app.base.core.model.Member; import com.enation.app.shop.core.model.Log; import com.enation.app.shop.core.service.impl.LogManager; import com.enation.app.shop.core.utils.DateUtils; import com.enation.app.shop.core.utils.IpUtils; import com.enation.eop.sdk.context.UserConext; import com.enation.framework.action.WWAction; import com.enation.framework.context.spring.SpringContextHolder; import com.enation.framework.context.webcontext.ThreadContextHolder; /*** * * @author Daizequn */ @Component @Scope("prototype") @ParentPackage("eop_default") @Namespace("/api/shop") @Action("logtime") @SuppressWarnings({ "rawtypes", "unchecked", "serial", "static-access" }) public class LogtimeAction extends WWAction {private String html;private String opentime;private String closetime;public String addLogtime() {Member member=UserConext.getCurrentMember();if(member!=null&&opentime!=null&&closetime!=null&&!closetime.equals(opentime)){this.showSuccessJson("成功關閉");Integer memberid;String memberuname; String membername; String pointkey;HttpServletRequest request = ThreadContextHolder.getInstance().getHttpRequest();HttpServletRequest httpRequest=(HttpServletRequest)request; String strBackUrl = "http://" + request.getServerName() //服務器地址 + ":" + request.getServerPort() //端口號 + httpRequest.getContextPath() //項目名稱 + httpRequest.getServletPath() //請求頁面或其他地址 + "?" + (httpRequest.getQueryString()); //參數(shù) try {strBackUrl=URLDecoder.decode(strBackUrl,"utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}memberid=member.getMember_id();memberuname = member.getUname(); membername = member.getName();String ipaddr = IpUtils.getRemoteAddr(request);//操作IPLog log = new Log(); log.setIpaddr(ipaddr);//操作IPlog.setMember_id(memberid);//用戶idlog.setMember_uname(memberuname);//用戶賬號log.setMember_name(membername);//用戶昵稱html=html.replace("//www.ZhUiChaGuOji.org/cn/=**://", "");try {html=URLDecoder.decode(html,"utf-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}if(html.contains("search-keyword-")){pointkey=html.substring(html.indexOf("-")+9);pointkey=pointkey.replace(".html", "");log.setPointkey(pointkey);}log.setHtml(html);//操作頁面log.setAllmethod(strBackUrl);//完整操作方法log.setClosetime(closetime);//保存關閉時間try {String createtime=DateUtils.getDateStrTime();log.setOpentime(opentime);//保存打開頁面時間log.setStaytime(DateUtils.getIntervalSecond(opentime, createtime));//停留時間} catch (Exception e) {e.printStackTrace();}LogManager manager = SpringContextHolder.getBean("logManager");manager.add(log); }return this.JSON_MESSAGE;}public String getHtml() {return html;}public void setHtml(String html) {this.html = html;}public String getOpentime() {return opentime;}public void setOpentime(String opentime) {this.opentime = opentime;}public String getClosetime() {return closetime;}public void setClosetime(String closetime) {this.closetime = closetime;}} @MethodLog(remark = "刪除商品")/*** 刪除購物車一項* * @param cartid* :要刪除的購物車id,int型,即 CartItem.item_id* * @return 返回json字串 result 為1表示調(diào)用成功0表示失敗 message 為提示信息* * {@link CartItem }*/@MethodLog(remark = "刪除商品") public String delete() {try {HttpServletRequest request = ThreadContextHolder.getInstance().getHttpRequest();String cartid = request.getParameter("cartid");cartManager.delete(request.getSession().getId(), Integer.valueOf(cartid));this.showSuccessJson("刪除成功");} catch (RuntimeException e) {this.logger.error("刪除購物項失敗", e);this.showErrorJson("刪除購物項失敗");}return this.JSON_MESSAGE;}
工具類
package com.enation.app.shop.core.utils;import java.text.Format; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern;/*** * @author HuangGenFa* @create-Date:2008-3-25* @desc:用于轉(zhuǎn)換日期,和獲得當前日期* */public class DateUtils {public DateUtils() {}/*** 日期時間,去掉時間* * @param date* 2008-05-05 12:00:00.0* @return String 如:2008-05-05*/public static String getDateToString(Date date) {String datetime = "";if (date != null) {datetime = date.toString();String writedate[] = datetime.split(" ");datetime = writedate[0];}return datetime;}public static String date2Str(Date date, String fmtDate) {String strRtn = null;if (date == null) {return "";}if (fmtDate.length() == 0) {fmtDate = "yyyy/MM/dd";}Format fmt = new SimpleDateFormat(fmtDate);try {strRtn = fmt.format(date);} catch (Exception e) {// e.printStackTrace();}return strRtn;}/*** 轉(zhuǎn)換日期,格式化形式為yyyy-MM-dd hh:mm:ss的字符串 例如:2008-8-8 8:08:08* * @return Date* @throws Exception* @author CaiMingXi*/public static Date str2Date2mmss(String dateStr) throws Exception {Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");date = sdf.parse(dateStr);return date;}/*** dateStr字符串日期轉(zhuǎn)為date* @param dateStr* @return* @throws Exception*/public static Date st2Date(String dateStr) throws Exception {Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");date = sdf.parse(dateStr);return date;}/*** 根據(jù)日期字符串和轉(zhuǎn)換形式,轉(zhuǎn)換為日期* * @return Date* @throws Exception*/public static Date str2Date(String dateStr, String fmtDate)throws Exception {Date date = new Date();if (fmtDate.length() == 0) {fmtDate = "yyyy-MM-dd";}SimpleDateFormat sdf = new SimpleDateFormat(fmtDate);date = sdf.parse(dateStr);return date;}/*** 得到當前日期,格式化形式為yyyy-MM-dd的字符串* * @throws Exception* @return String*/public static String getDateStr() throws Exception {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Date now = new Date();String today = sdf.format(now).toString();return today;}/*** 得到當前日期,格式化形式為yyyy-MM-dd的字符串* * @throws Exception* @return String*/public static String getDateStrZ() throws Exception {SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");Date now = new Date();String today = sdf.format(now).toString();return today;}/*** 得到當前日期,格式化形式為yyyy-MM-dd hh:mm:ss的字符串 例如:2008-8-8 8:08:08* * @throws Exception* @author CaiMingXi* @return String*/public static String getDateStrTime() throws Exception {String today = "";try{SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date now = new Date();today = sdf.format(now).toString();return today;}catch(Exception ec){ec.printStackTrace();}return today;}/*** ==============================================================================================================================* 將數(shù)字日期轉(zhuǎn)換為中文 HuangGenFa 2008-7-12*/private static final String[] NUMBERS = { "O", "一", "二", "三", "四", "五","六", "七", "八", "九" };/** 通過 yyyy-MM-dd 得到中文大寫格式 yyyy MM dd 日期 */public static synchronized String toChinese(String str) {StringBuffer sb = new StringBuffer();sb.append(getSplitDateStr(str, 0)).append("年").append(getSplitDateStr(str, 1)).append("月").append(getSplitDateStr(str, 2)).append("日");return sb.toString();}/** 分別得到年月日的大寫 默認分割符 "-" */public static String getSplitDateStr(String str, int unit) {// unit是單位 0=年 1=月 2日String[] DateStr = str.split("-");if (unit > DateStr.length)unit = 0;StringBuffer sb = new StringBuffer();for (int i = 0; i < DateStr[unit].length(); i++) {if ((unit == 1 || unit == 2) && Integer.valueOf(DateStr[unit]) > 9) {sb.append(convertNum(DateStr[unit].substring(0, 1))).append("十").append(convertNum(DateStr[unit].substring(1, 2)));break;} else {sb.append(convertNum(DateStr[unit].substring(i, i + 1)));}}if (unit == 1 || unit == 2) {return sb.toString().replaceAll("^一", "").replace("O", "");}return sb.toString();}/** 轉(zhuǎn)換數(shù)字為大寫 */private static String convertNum(String str) {return NUMBERS[Integer.valueOf(str)];}/** 判斷是否是零或正整數(shù) */public static boolean isNumeric(String str) {Pattern pattern = Pattern.compile("[0-9]*");Matcher isNum = pattern.matcher(str);if (!isNum.matches()) {return false;}return true;}/*** @author CaiMingXi 將一個日期字符串轉(zhuǎn)化成Calendar* @return Calendar*/public static Calendar switchStringToCalendar(String sDate) {Date date = switchStringToDate(sDate);Calendar c = Calendar.getInstance();c.setTime(date);return c;}/*** @author CaiMingXi 自定義日期返回相差天數(shù)的日期 例 第一個參數(shù) 2008-9-6 第二個參數(shù)為 7 那么返回值為* 2008-8-30* @param sDate* 日期字符串* @param n* 相差的天數(shù)* @return String*/public static String switchStringToDate(String sDate, int n) {Calendar c = switchStringToCalendar(sDate);c.add(Calendar.DAY_OF_MONTH, -n);return "" + c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"+ c.get(Calendar.DATE);}/*** @author CaiMingXi 自定義日期返回相差天數(shù)的日期 例 第一個參數(shù) 2008-9-6 第二個參數(shù)為 7 那么返回值為* 2008-9-13* @param sDate* 日期字符串* @param n* 相差的天數(shù)* @return String*/public static String switchStringHToDate(String sDate, int n) {Calendar c = switchStringToCalendar(sDate);c.add(Calendar.DAY_OF_MONTH, +n);return "" + c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"+ c.get(Calendar.DATE);}/*** 返回相差天數(shù)的日期* @param date 日期* @param days 天數(shù)* @return*/public static Date switchToDate(Date date,int days) {Calendar c = Calendar.getInstance();c.setTime(date);c.add(Calendar.DAY_OF_MONTH,+days);return c.getTime();}/*** 返回相差月數(shù)的日期* @param date 日期* @param month 月數(shù)* @return*/public static Date switchToMonth(Date date,int month) {Calendar c = Calendar.getInstance();c.setTime(date);c.add(Calendar.MONTH, 1);return c.getTime();}/*** @author CaiMingXi 取得系統(tǒng)當前時間前n天,格式為yyyy-mm-dd* @param n* 相差的天數(shù)* @return String*/public static String getNDayBeforeCurrentDate(int n) {Calendar c = Calendar.getInstance();c.add(Calendar.DAY_OF_MONTH, -n);return "" + c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"+ c.get(Calendar.DATE);}/*** @author CaiMingXi 取得系統(tǒng)當前時間后n天,格式為yyyy-mm-dd* @param n* 相差的天數(shù)* @return String*/public static String getHDayBeforeCurrentDate(int n) {Calendar c = Calendar.getInstance();c.add(Calendar.DAY_OF_MONTH, +n);return "" + c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"+ c.get(Calendar.DATE);}/*** @author CaiMingXi 輸入兩個字符串型的日期,比較兩者的大小* @return boolean*/public static boolean compareTwoDateBigOrSmall(String fromDate,String toDate) {Date dateFrom = switchStringToDate(fromDate);Date dateTo = switchStringToDate(toDate);if (dateFrom.before(dateTo)) {return true;} else {return false;}}/*** @author CaiMingXi 將一個日期字符串轉(zhuǎn)化成日期* @return Date*/public static Date switchStringToDate(String sDate) {Date date = null;try {SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");date = df.parse(sDate);} catch (Exception e) {// System.out.println("日期轉(zhuǎn)換失敗:" + e.getMessage());}return date;}/*** @author CaiMingXi 比較日期返回天數(shù)* @return int*/public static int getDifferDays(String strBegin, String strEnd) {SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");Date date1 = null, date2 = null;int days = 0;try {date1 = f.parse(strBegin);date2 = f.parse(strEnd);days = (int) ((date2.getTime() - date1.getTime()) / 86400000);} catch (Exception e) {// TODO 自動生成 catch 塊e.printStackTrace();}return days;}/*** @author ZhaiZhengqiang 比較日期返回天數(shù)* @return int*/public static int getDifferDays(Date begin, Date end) {int days = (int)((end.getTime() - begin.getTime()) / 86400000);return days;}public static int getDifferDays2(Date begin, Date end) {SimpleDateFormat smdf = new SimpleDateFormat("yyyy-MM-dd");String start = smdf.format(begin);String end2 = smdf.format(end);int days=getDifferDays(start, end2);return days;}/** * 計算兩個日期之間相差的月數(shù) * @param date1 * @param date2 * @return */ public static int getMonths(Date date1, Date date2){ int iMonth = 0; int flag = 0; try{ Calendar objCalendarDate1 = Calendar.getInstance(); objCalendarDate1.setTime(date1); Calendar objCalendarDate2 = Calendar.getInstance(); objCalendarDate2.setTime(date2); if (objCalendarDate2.equals(objCalendarDate1)) return 0; if (objCalendarDate1.after(objCalendarDate2)){ Calendar temp = objCalendarDate1; objCalendarDate1 = objCalendarDate2; objCalendarDate2 = temp; } if (objCalendarDate2.get(Calendar.DAY_OF_MONTH) < objCalendarDate1.get(Calendar.DAY_OF_MONTH)) flag = 1; if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1.get(Calendar.YEAR)) iMonth = ((objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1.get(Calendar.YEAR)) * 12 + objCalendarDate2.get(Calendar.MONTH) - flag) - objCalendarDate1.get(Calendar.MONTH); else iMonth = objCalendarDate2.get(Calendar.MONTH) - objCalendarDate1.get(Calendar.MONTH) - flag; } catch (Exception e){ e.printStackTrace(); } return iMonth; } private static String HanDigiStr[] = new String[] { "零", "壹", "貳", "叁","肆", "伍", "陸", "柒", "捌", "玖" };private static String HanDiviStr[] = new String[] { "", "拾", "佰", "仟", "萬","拾", "佰", "仟", "億", "拾", "佰", "仟", "萬", "拾", "佰", "仟", "億", "拾","佰", "仟", "萬", "拾", "佰", "仟" };/*** 輸入字符串必須正整數(shù),只允許前導空格(必須右對齊),不宜有前導零* @param NumStr* @return* @author CaiMingXi*/private static String PositiveIntegerToHanStr(String NumStr) { String RMBStr = "";boolean lastzero = false;boolean hasvalue = false; // 億、萬進位前有數(shù)值標記int len, n;len = NumStr.length();if (len > 15)return "數(shù)值過大!";for (int i = len - 1; i >= 0; i--) {if (NumStr.charAt(len - i - 1) == ' ')continue;n = NumStr.charAt(len - i - 1) - '0';if (n < 0 || n > 9)return "輸入含非數(shù)字字符!";if (n != 0) {if (lastzero)RMBStr += HanDigiStr[0]; // 若干零后若跟非零值,只顯示一個零// 除了億萬前的零不帶到后面// if( !( n==1 && (i%4)==1 && (lastzero || i==len-1) ) ) //// 如十進位前有零也不發(fā)壹音用此行if (!(n == 1 && (i % 4) == 1 && i == len - 1)) // 十進位處于第一位不發(fā)壹音RMBStr += HanDigiStr[n];RMBStr += HanDiviStr[i]; // 非零值后加進位,個位為空hasvalue = true; // 置萬進位前有值標記} else {if ((i % 8) == 0 || ((i % 8) == 4 && hasvalue)) // 億萬之間必須有非零值方顯示萬RMBStr += HanDiviStr[i]; // “億”或“萬”}if (i % 8 == 0)hasvalue = false; // 萬進位前有值標記逢億復位lastzero = (n == 0) && (i % 4 != 0);}if (RMBStr.length() == 0)return HanDigiStr[0]; // 輸入空字符或"0",返回"零"return RMBStr;}/** 數(shù)字轉(zhuǎn)換大寫* @param val* @return 字符串 返回大寫字符串* @createDate 2009-4-17*/public static String NumToRMBStr(double val) {String SignStr = "";String TailStr = "";long fraction, integer;int jiao, fen;if (val < 0) {val = -val;SignStr = "負";}if (val > 99999999999999.999 || val < -99999999999999.999)return "數(shù)值位數(shù)過大!";// 四舍五入到分long temp = Math.round(val * 100);integer = temp / 100;fraction = temp % 100;jiao = (int) fraction / 10;fen = (int) fraction % 10;if (jiao == 0 && fen == 0) {TailStr = "整";} else {TailStr = HanDigiStr[jiao];if (jiao != 0)TailStr += "角";if (integer == 0 && jiao == 0) // 零元后不寫零幾分TailStr = "";if (fen != 0)TailStr += HanDigiStr[fen] + "分";}// 下一行可用于非正規(guī)金融場合,0.03只顯示“叁分”而不是“零元叁分”// if( !integer ) return SignStr+TailStr;return "¥" + SignStr + PositiveIntegerToHanStr(String.valueOf(integer))+ "元" + TailStr;}/*** 返回乘以10000以后的值* @param val* @return* @author CaiMingXi*/public static String NumToRMBStrW(double val) {String SignStr = "";String TailStr = "";long fraction, integer;int jiao, fen;if (val < 0) {val = -val;SignStr = "負";}if (val > 99999999999999.999 || val < -99999999999999.999)return "數(shù)值位數(shù)過大!";// 四舍五入到分long temp = Math.round(val * 100);integer = temp / 100;fraction = temp % 100;jiao = (int) fraction / 10;fen = (int) fraction % 10;if (jiao == 0 && fen == 0) {TailStr = "整";} else {TailStr = HanDigiStr[jiao];if (jiao != 0)TailStr += "角";if (integer == 0 && jiao == 0) // 零元后不寫零幾分TailStr = "";if (fen != 0)TailStr += HanDigiStr[fen] + "分";}// 下一行可用于非正規(guī)金融場合,0.03只顯示“叁分”而不是“零元叁分”// if( !integer ) return SignStr+TailStr;// 返回乘以10000以后的值return SignStr + PositiveIntegerToHanStr(String.valueOf(integer)) + "元"+ TailStr;}/*** @author dzq 比較日期返回分鐘* @return Long*/public static Long getIntervalMini(String strSmall, String strBig) {SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");long date1=0L;long date2=0L;long mini=0L;try {date1 = f.parse(strSmall).getTime();date2=f.parse(strBig).getTime();mini=((date2-date1)/1000);} catch (ParseException e) {e.printStackTrace();}return (mini/60);}/*** @author dzq 比較日期返回分鐘* @return Long*/public static Long getIntervalSecond(String strSmall, String strBig) {SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");long date1=0L;long date2=0L;long second=0L;try {date1 = f.parse(strSmall).getTime();date2=f.parse(strBig).getTime();second=((date2-date1)/1000);} catch (ParseException e) {e.printStackTrace();}return (second);}/*** 返回 增加月份后的日期=日期+加上期限(月份數(shù))* @author dzq * @param date 日期* @param expires 期限* @return String*/public static String addExpires(Date date, Integer expires) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.MONTH, expires);Date nDate = calendar.getTime(); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String newDate=f.format(nDate);return newDate;}/*** 返回 增加月份后的日期=日期+加上期限(月份數(shù))* @author dzq * @param date 日期* @param expires 期限* @return Date*/public static Date addExpiresDate(Date date, Integer expires) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.MONTH, expires);Date nDate = calendar.getTime(); return nDate;}/*** ==============================================================================================================================*/public static void main(String[] args) {// String fromDate = "2008-10-6"; // String toDate = "2008-10-9"; // Date dateFrom = switchStringToDate(fromDate); // Date dateTo = switchStringToDate(toDate);try {// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // int d = getDifferDays2(new Date(),DateUtil.getMonthLastDate(new Date())); // System.out.println(getDateStrTime());System.out.println(getIntervalSecond("2015-12-04 10:12:10", "2015-12-05 10:13:10"));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} // System.out.println(DateUtils.getIntervalMini("2011-06-11 08:17:15", "2011-06-13 08:17:15"));} } package com.enation.app.shop.core.utils;import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale;public class DateUtil {private static final String PATTERN_DATE = "yyyy-MM-dd";private static final String PATTERN_TIME = "HH:mm:ss";private static final String PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss";private static final String PATTERN_FULL = "yyyy-MM-dd HH:mm:ss.SSS";public static final Date parse(String pattern, String source) {try {return new SimpleDateFormat(pattern, Locale.US).parse(source);} catch (ParseException e) {throw new RuntimeException("parse date error : ", e);}}public static final Date parseDateTime(String source) {try {return new SimpleDateFormat(PATTERN_DATETIME).parse(source);} catch (ParseException e) {throw new RuntimeException("parse date error : ", e);}}public static final Date parseDate(String source) {try {return new SimpleDateFormat(PATTERN_DATE).parse(source);} catch (ParseException e) {throw new RuntimeException("parse date error : ", e);}}public static final Date parseTime(String source) {try {return new SimpleDateFormat(PATTERN_TIME).parse(source);} catch (ParseException e) {throw new RuntimeException("parse date error : ", e);}}public static final Date parseFull(String source) {try {return new SimpleDateFormat(PATTERN_FULL).parse(source);} catch (ParseException e) {throw new RuntimeException("parse date error : ", e);}}public static final String format(String pattern, Date date) {return new SimpleDateFormat(pattern, Locale.US).format(date);}public static final String formatDateTime(Date date) {return new SimpleDateFormat(PATTERN_DATETIME).format(date);}public static final String formatDate(Date date) {return new SimpleDateFormat(PATTERN_DATE).format(date);}public static final String formatTime(Date date) {return new SimpleDateFormat(PATTERN_TIME).format(date);}public static final String formatFull(Date date) {return new SimpleDateFormat(PATTERN_FULL).format(date);}public static final String format(String outPatt, String inPatt, String source) {return format(outPatt, parse(inPatt, source));}public static final String getTimestamp(String pattern) {return format(pattern, new Date());}public static final int calDValueOfYear(Date fromDate, Date toDate) {Calendar sCal = Calendar.getInstance();Calendar eCal = Calendar.getInstance();sCal.setTime(fromDate);eCal.setTime(toDate);return eCal.get(Calendar.YEAR) - sCal.get(Calendar.YEAR);}public static final int calDValueOfMonth(Date fromDate, Date toDate) {Calendar sCal = Calendar.getInstance();Calendar eCal = Calendar.getInstance();sCal.setTime(fromDate);eCal.setTime(toDate);return 12 * (eCal.get(Calendar.YEAR) - sCal.get(Calendar.YEAR)) + (eCal.get(Calendar.MONTH) - sCal.get(Calendar.MONTH));}public static final int calDValueOfDay(Date fromDate, Date toDate) {return (int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24));}public static final Date getFirstDayOfMonth(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.set(Calendar.DAY_OF_MONTH, 1);calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(Calendar.MILLISECOND, 0);return calendar.getTime();}public static final Date getFirstDayOfWeek(Date date) {return getFirstDayOfWeek(date, Calendar.MONDAY);}public static final Date getLastDayOfWeek(Date date) {return getLastDayOfWeek(date, Calendar.MONDAY);}public static final Date getFirstDayOfWeek(Date date, int firstDayOfWeek) {Calendar calendar = Calendar.getInstance();calendar.setFirstDayOfWeek(firstDayOfWeek);calendar.setTime(date);calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(Calendar.MILLISECOND, 0);return calendar.getTime();}public static final Date getLastDayOfWeek(Date date, int firstDayOfWeek) {Calendar calendar = Calendar.getInstance();calendar.setFirstDayOfWeek(firstDayOfWeek);calendar.setTime(date);calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(Calendar.MILLISECOND, 0);calendar.add(Calendar.DAY_OF_YEAR, 7);calendar.add(Calendar.MILLISECOND, -1);return calendar.getTime();}public static final Date[] getWeek(Date date) {return getWeek(date, Calendar.MONDAY);}public static final Date[] getWeek(Date date, int firstDayOfWeek) {Calendar calendar = Calendar.getInstance();calendar.setFirstDayOfWeek(firstDayOfWeek);calendar.setTime(date);calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(Calendar.MILLISECOND, 0);Date firstDate = calendar.getTime();calendar.add(Calendar.DAY_OF_YEAR, 7);calendar.add(Calendar.MILLISECOND, -1);Date lastDate = calendar.getTime();return new Date[] { firstDate, lastDate };}public static java.sql.Date toSQLDate(Date date) {return new java.sql.Date(date.getTime());}public static java.sql.Date getSQLDate() {return new java.sql.Date(System.currentTimeMillis());}public static java.sql.Timestamp getSQLTimestamp() {return new java.sql.Timestamp(System.currentTimeMillis());}public static java.sql.Timestamp getTimestamp(int day) {return new java.sql.Timestamp(System.currentTimeMillis()+24*60*60*1000*day);}public static Date add(Date date, int field, int increment) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(field, increment);return cal.getTime();}public static Date set(Date date, int field, int value) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.set(field, value);return cal.getTime();}/*** 當月第一天* @return*/public static Date getMonthFirstDate(){Calendar curCal = Calendar.getInstance();curCal.set(Calendar.DAY_OF_MONTH, 1);return curCal.getTime();}/*** 當月最后一天* @return*/public static Date getMonthLastDate(){Calendar curCal = Calendar.getInstance();curCal.set(Calendar.DATE, 1); curCal.roll(Calendar.DATE, - 1); return curCal.getTime();}/*** 當月最后一天* @return*/public static Date getMonthLastDate(Date date){Calendar curCal = Calendar.getInstance();curCal.setTime(date);curCal.set(Calendar.DATE, 1); curCal.roll(Calendar.DATE, - 1); return curCal.getTime();}/*** 當月最后一天* @return*/public static Date getSqMonthLastDate(Date date, Integer sq){Calendar curCal = Calendar.getInstance();curCal.setTime(date);curCal.add(Calendar.MONTH, sq);curCal.set(Calendar.DATE, 1); curCal.roll(Calendar.DATE, - 1); return curCal.getTime();}/*** 獲取一個月以前* @return*/public static Date getMonthBefore(){return DateUtil.getNDatesBefore(-30);}/*** 獲取多少天之前* n為正數(shù)是,表示多少天后* 負數(shù)時,表示多少天前* @param n* @return*/public static Date getNDatesBefore(Integer n){Calendar curCal = Calendar.getInstance();curCal.add(Calendar.DATE, n);return curCal.getTime();}public Integer getMonthWeekCount(Date date){Calendar c = Calendar.getInstance();int week = c.get(Calendar.WEEK_OF_MONTH);//獲取是本月的第幾周return week;}/*** 給任意一個日期,輸出當周的周一* 周日要回退幾天* @return*/public static Date getMonday(Date date) {Calendar curCal = Calendar.getInstance();curCal.setTime(date);int week = curCal.get(Calendar.DAY_OF_WEEK);//周日的話回退幾天,找周一if(week == Calendar.SUNDAY)curCal.add(Calendar.DATE, -3);curCal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);return curCal.getTime(); }public static void main(String[] args) { System.out.println(DateUtil.getTimestamp("yyyyMMdd"));String str=DateUtil.formatDate(DateUtil.add(new Date(), Calendar.DAY_OF_YEAR, -30));System.out.println(str);}} package com.enation.app.shop.core.utils;import java.io.Serializable;public class IpInfo implements Serializable {private static final long serialVersionUID = 1L;private String region;// 省private String city;// 市private String county;// 區(qū)private String isp;// ISP公司private String citySimpleName;// 市級簡稱public IpInfo() {super();}public IpInfo(String region, String city) {super();this.region = region;this.city = city;}public IpInfo(String region, String city, String county) {super();this.region = region;this.city = city;this.county = county;}public String getRegion() {return region;}public void setRegion(String region) {this.region = region;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getCounty() {return county;}public void setCounty(String county) {this.county = county;}public String getIsp() {return isp;}public void setIsp(String isp) {this.isp = isp;}public String getCitySimpleName() {if (city != null) {citySimpleName = city.replace("市", "").replace("地區(qū)", "");}return citySimpleName;}public void setCitySimpleName(String citySimpleName) {this.citySimpleName = citySimpleName;}} package com.enation.app.shop.core.utils;import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser;public class IpUtils {/*** 獲得用戶遠程地址*/public static String getRemoteAddr(HttpServletRequest request) {String remoteAddr = request.getHeader("X-Real-IP");if (StringUtils.isNotBlank(remoteAddr)) {remoteAddr = request.getHeader("X-Forwarded-For");} else if (StringUtils.isNotBlank(remoteAddr)) {remoteAddr = request.getHeader("Proxy-Client-IP");} else if (StringUtils.isNotBlank(remoteAddr)) {remoteAddr = request.getHeader("WL-Proxy-Client-IP");}return remoteAddr != null ? remoteAddr : request.getRemoteAddr();}public static void main(String[] args) {String ip = "183.58.24.176";try {IpInfo ipInfo = IpUtils.getIpInfo(ip); // System.out.println(ipInfo.getRegion() + ipInfo.getCity() // + ipInfo.getCounty() + " " + ipInfo.getIsp());System.out.println(ipInfo.getCity()+ ipInfo.getCounty() );} catch (Exception e) {e.printStackTrace();}}public static IpInfo getIpInfo(HttpServletRequest request) {String ip = getRemoteAddr(request);IpInfo ipInfo = getIpInfo(ip);if (ipInfo == null || StringUtils.isBlank(ipInfo.getCity())) {ipInfo = new IpInfo();}System.out.println("訪問ip:" + ip + " " + ipInfo.getRegion()+ ipInfo.getCity() + ipInfo.getCounty() + " "+ ipInfo.getIsp());return ipInfo;}/*** 獲取地址* * @param ip* @param encoding* @return* @throws Exception*/public static IpInfo getIpInfo(String ip) {String path = "http://ip.taobao.com/service/getIpInfo.php";String params = "ip=" + ip;String returnStr = doGet(path, params, "utf-8");if (returnStr != null) {Gson gson = new Gson();JsonParser parser = new JsonParser();JsonObject json = parser.parse(returnStr).getAsJsonObject();if ("0".equals(json.get("code").toString())) {return gson.fromJson(json.get("data"), IpInfo.class);}}return null;}/*** 從url獲取結(jié)果* * @param path* @param params* @param encoding* @return*/public static String doGet(String path, String params, String encoding) {URL url = null;HttpURLConnection connection = null;try {url = new URL(path);connection = (HttpURLConnection) url.openConnection();// 新建連接實例connection.setConnectTimeout(2000);// 設置連接超時時間,單位毫秒connection.setReadTimeout(2000);// 設置讀取數(shù)據(jù)超時時間,單位毫秒connection.setDoInput(true);// 是否打開輸入流true|falseconnection.setDoOutput(true);// 是否打開輸出流true|falseconnection.setRequestMethod("GET");// 提交方法POST|GETconnection.setUseCaches(false);// 是否緩存true|falseconnection.connect();// 打開連接端口DataOutputStream out = new DataOutputStream(connection.getOutputStream());out.writeBytes(params);out.flush();out.close();BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));StringBuffer buffer = new StringBuffer();String line = "";while ((line = reader.readLine()) != null) {buffer.append(line);}reader.close();return buffer.toString();} catch (SocketTimeoutException socketTimeoutException) {return null;} catch (Exception e) {e.printStackTrace();} finally {if (connection != null) {connection.disconnect();// 關閉連接}}return null;}}html頁面
var opentime;//打開頁面的時間 var closetime;//關閉頁面的時間 Date.prototype.Format = function (fmt) { //author: meizz var o = {"M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小時 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 };if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));for (var k in o)if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));return fmt; }function checkLeave(){ closetime = new Date().Format("yyyy-MM-dd hh:mm:ss"); var html=window.location.href;/* event.returnValue="確定離開當前頁面嗎?"+html; */ $.ajax({url:"${ctx}/api/shop/logtime!addLogtime.do?ajax=yes",dataType:"json",cache: true,data:{opentime:opentime,closetime:closetime,html:html},success:function(result){if(result.result==1){}else{/* layer.msg("出錯了", { icon: 7,time: 2000 }, function(){}); */} /* layer.close(index); */},error:function(){/* layer.close(index); *//* layer.msg("出錯了:(", { icon: 7,time: 2000 }, function(){}); */} }); }$(function(){opentime = new Date().Format("yyyy-MM-dd hh:mm:ss"); });
?
轉(zhuǎn)載于:https://www.cnblogs.com/nbkyzms/p/5116459.html
總結(jié)
以上是生活随笔為你收集整理的用户日志留存所采用的技术手段的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魔兽世界怀旧服白骨碎片怎么得?白骨碎片任
- 下一篇: GetWindowLong和SetWin