網(wǎng)頁(yè)計(jì)數(shù)器想必大家都有見(jiàn)到過(guò)吧,記錄每一個(gè)訪問(wèn)者,下面有個(gè)不錯(cuò)的示例,感興趣的朋友可以參考下
代碼如下://過(guò)濾器類 public class EcondingFilter implements Filter { private String charset = null; private ServletContext context = null; private String path = ""; /** * 在銷(xiāo)毀前將數(shù)據(jù)存入本地文件中 */ public void destroy() { //獲取servleContext中的屬性的那個(gè)值 String nums = (String) context.getAttribute("nums"); //創(chuàng)建寫(xiě)入流 FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter(path); bw = new BufferedWriter(fw); bw.write(nums); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("filter銷(xiāo)毀"); } 代碼如下:public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub System.out.println("doFilter前"); String path = ((HttpServletRequest)request).getServletPath();//獲取每次訪問(wèn)的action的相對(duì)路徑 <img alt="" src="http://img.blog.csdn.net/20130728233435953?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2tyZ3diag==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center"><img alt="" src="http://img.blog.csdn.net/20130728233445625?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2tyZ3diag==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center"> //判斷路徑,如果是登陸的那個(gè)action,就讓保存的context里面的那個(gè)屬性加1 if(path.endsWith("/login.action")){ context.setAttribute("nums",Integer.parseInt(context.getAttribute("nums").toString())+1+""); } request.setCharacterEncoding(charset); response.setCharacterEncoding(charset); chain.doFilter(request, response); System.out.println("doFilter后"); } 代碼如下:public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub System.out.println("filter初始化"); //獲取編碼格式 charset = filterConfig.getInitParameter("encoding"); //獲取servletContext context = filterConfig.getServletContext(); System.out.println(charset); path = context.getRealPath(""); File file = new File("D:text.txt"); if (!file.exists()) {//判斷文件是否存在 // 如果文件不存在,就創(chuàng)建一個(gè)文件,保存在D盤(pán)中 file = new File("d:text.txt"); FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter(file); bw = new BufferedWriter(fw); bw.write(0 + "");// 寫(xiě)入初始化數(shù)據(jù)0 } catch (Exception e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //當(dāng)每次tomcat啟動(dòng)服務(wù)時(shí),進(jìn)行讀取創(chuàng)建的那個(gè)文件 path = "d:text.txt"新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注