使用ServletContext对象完成网页计数器
生活随笔
收集整理的這篇文章主要介紹了
使用ServletContext对象完成网页计数器
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用ServletContext對象完成網(wǎng)頁計數(shù)器
?*?? ??? ?在用戶登錄校驗(yàn)中創(chuàng)建計數(shù)器并自增,然后存儲到ServletContext對象中
?*?? ??? ?在主頁面里取出計數(shù)器數(shù)據(jù)顯示給用戶即可。
?
當(dāng)服務(wù)器停掉后,重新啟動。這個網(wǎng)頁計數(shù)器又要重新開始計數(shù)。這顯然不符合邏輯。故需要想一個辦法,即使在服務(wù)器被停掉后,網(wǎng)頁計數(shù)器也能正常計數(shù)。
?
? ? 解決
解決方法:?
LoginServlet.java
package com.dym.servlet;import java.io.IOException;import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import com.dym.pojo.User; import com.dym.service.LoginService; import com.dym.service.impl.LoginServiceImpl;/*** 使用ServletContext對象完成網(wǎng)頁計數(shù)器* 在用戶登錄校驗(yàn)中創(chuàng)建計數(shù)器并自增,然后存儲到ServletContext對象中* 在主頁面里取出計數(shù)器數(shù)據(jù)顯示給用戶即可。* @author Administrator**/ public class LoginServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//設(shè)置請求編碼格式:req.setCharacterEncoding("utf-8");//設(shè)置響應(yīng)編碼格式resp.setContentType("text/html;charset=utf-8");//獲取請求信息String uname=req.getParameter("uname");//使用String進(jìn)行數(shù)據(jù)重新編碼 // uname=new String(uname.getBytes("iso8859-1"),"utf-8"); //解決了亂碼問題String pwd=req.getParameter("pwd");System.out.println(uname+":"+pwd);//處理請求信息//獲取業(yè)務(wù)層對象LoginService ls=new LoginServiceImpl();User u=ls.checkLoginService(uname, pwd);System.out.println(u);//響應(yīng)處理結(jié)果if(u!=null){//創(chuàng)建Cookie信息,實(shí)現(xiàn)三天免登錄Cookie c=new Cookie("uid",u.getUid()+"");//設(shè)置Cookie的有效期c.setMaxAge(3*24*60*60);c.setPath("/login/ck");//添加Cookie信息resp.addCookie(c);//請求轉(zhuǎn)發(fā)//req.getRequestDispatcher("main").forward(req, resp);//將數(shù)據(jù)存儲到session對象中HttpSession hs=req.getSession();hs.setAttribute("user",u);//創(chuàng)建網(wǎng)頁計數(shù)器//獲取計數(shù)數(shù)據(jù)ServletContext sc=this.getServletContext();if(sc.getAttribute("nums")!=null){int nums=Integer.parseInt((String) sc.getAttribute("nums"));//計數(shù)器自增nums+=1;//再次存儲到ServletContext對象中sc.setAttribute("nums",nums);}else{sc.setAttribute("nums", 1);}//重定向resp.sendRedirect("/login/main");return;}else{//使用request對象實(shí)現(xiàn)不同servlet的數(shù)據(jù)流轉(zhuǎn)req.setAttribute("str", "用戶名或密碼錯誤");//使用請求轉(zhuǎn)發(fā)req.getRequestDispatcher("page").forward(req, resp);//請求轉(zhuǎn)發(fā)后直接return結(jié)束即可。return;}} }CookieServlet.java
package com.dym.servlet;import java.io.IOException;import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import com.dym.pojo.User; import com.dym.service.LoginService; import com.dym.service.impl.LoginServiceImpl; /*** Cookie信息校驗(yàn)* 判斷請求中是否攜帶正確的Cookie信息* 如果有則校驗(yàn)Cookie信息是否正確* 如果校驗(yàn)正確則直接響應(yīng)主頁面給用戶* 如果校驗(yàn)不正確則響應(yīng)登錄頁面給用戶* 沒有則請求轉(zhuǎn)發(fā)給登錄頁面*/ public class CookieServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//設(shè)置請求編碼格式req.setCharacterEncoding("utf-8");//設(shè)置響應(yīng)編碼格式resp.setContentType("text/html;charset=utf-8");//獲取請求信息//獲取Cookie信息Cookie[] cks=req.getCookies();//處理請求信息if(cks!=null){//遍歷Cookie信息String uid="";for(Cookie c:cks){if("uid".equals(c.getName())){uid=c.getValue();}}//校驗(yàn)UID是否存在if("".equals(uid)){//請求轉(zhuǎn)發(fā)req.getRequestDispatcher("page").forward(req, resp);return;}else{//校驗(yàn)UID用戶信息//獲取業(yè)務(wù)層對象LoginService ls=new LoginServiceImpl();User u=ls.checkUidService(uid);if(u!=null){//將用戶數(shù)據(jù)存儲到session對象中req.getSession().setAttribute("user",u);//網(wǎng)頁計數(shù)器自增int nums=(int) this.getServletContext().getAttribute("nums");nums+=1;this.getServletContext().setAttribute("nums", nums);//重定向resp.sendRedirect("/login/main");return;}else{//請求轉(zhuǎn)發(fā)req.getRequestDispatcher("page").forward(req, resp);return;}}}else{//響應(yīng)處理結(jié)果//請求轉(zhuǎn)發(fā)req.getRequestDispatcher("page").forward(req, resp);return;}} }MainServlet.java
package com.dym.servlet;import java.io.IOException;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import com.dym.pojo.User;public class MainServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//設(shè)置請求編碼格式req.setCharacterEncoding("utf-8");//設(shè)置響應(yīng)編碼格式resp.setContentType("text/html;charset=utf-8");//獲取請求信息//獲取session中的數(shù)據(jù)User u=(User)req.getSession().getAttribute("user");//獲取網(wǎng)頁瀏覽次數(shù)int nums=(int) this.getServletContext().getAttribute("nums");//處理請求信息//響應(yīng)處理結(jié)果resp.getWriter().write("<html>");resp.getWriter().write("<head>");resp.getWriter().write("</head>");resp.getWriter().write("<body>");resp.getWriter().write("<h3>歡迎"+u.getUname()+"訪問dym管理系統(tǒng)</h3>");resp.getWriter().write("當(dāng)前網(wǎng)頁瀏覽次數(shù)為:"+nums);resp.getWriter().write("<hr>");resp.getWriter().write("<form action='show' method='get'>");resp.getWriter().write("<input type='submit' value='查看個人信息'>");resp.getWriter().write("</form>");resp.getWriter().write("</body>");resp.getWriter().write("</html>");} }NumServlet.java
package com.dym.servlet;import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;public class NumServlet extends HttpServlet {//覆寫init初始化方法,將數(shù)據(jù)讀取到ServletContext對象中@Overridepublic void init() throws ServletException {//獲取文件中的計數(shù)器數(shù)據(jù)//獲取文件路徑String path=this.getServletContext().getRealPath("/nums/nums.txt");//聲明流對象FileReader fr=null;BufferedReader br=null;try {fr=new FileReader(path);br=new BufferedReader(fr);String nums=br.readLine();System.out.println(nums);this.getServletContext().setAttribute("nums", nums);} catch (Exception e) {e.printStackTrace();}finally{try {fr.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}//覆寫銷毀方法,存儲計數(shù)器到文件中@Overridepublic void destroy() {//獲取網(wǎng)頁計數(shù)器int nums=(int) this.getServletContext().getAttribute("nums");//獲取文件路徑String path=this.getServletContext().getRealPath("/nums/nums.txt");//聲明流對象BufferedWriter bw=null;FileWriter fw=null;try {fw=new FileWriter(path);bw=new BufferedWriter(fw);bw.write(nums+"");bw.flush();} catch (Exception e) {e.printStackTrace();}finally{try {fw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {bw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}} }備注:可以在我的博客下載那去下載源代碼
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的使用ServletContext对象完成网页计数器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ServletConfig 对象
- 下一篇: Web.xml 文件与server.xm