Implementing Web Counters with ServletContext

Source: Internet
Author: User
Tags set time

(1) Thinking Analysis:

Use ServletContext and Notepad two things, the number of landing in the TXT file, the first is in the condition of landing Using the servlet's init () function to initialize the TXT counter file and read it and then access the website after the user logs in, no repetition of the technology is counted only once, until destroy () and then the counter file is added 1;

(2) Login interface

Package Com.tsinghua;import Javax.servlet.http.*;import java.io.*;p ublic class Login extends HttpServlet {public void Doget (httpservletrequest req,httpservletresponse res) {//Business logic try {//Chinese garbled res.setcontenttype ("TEXT/HTML;CHARSET=GBK" ); PrintWriter pw=res.getwriter ();//Return to login interface pw.println ("


(2) Handling requests for landing pages

Package Com.tsinghua;import javax.servlet.http.*;import java.io.*;import java.sql.*;p ublic class LoginCl extends HttpServlet {//rewrite init function public void init () {try {///will only be called once//create a Filereaderfilereader f=new filereader ("f:\\    MyCounter.txt ");     BufferedReader br=new BufferedReader (f);  Reads a row of data String numval=br.readline (); Be sure to close the file stream Br.close ();//Put the Times value into Servletcontextthis.getservletcontext (). SetAttribute ("Visittimes", numval);    System.out.println ("Inti is called");    } catch (Exception ex) {ex.printstacktrace ();        }}//overrides the destroy function public void destroy () {try {//writes a new number of times to FileWriter fw=new FileWriter ("F:\\mycounter.txt");        <span style= "White-space:pre" ></span>bufferedwriter bw=new BufferedWriter (FW); <span style= "White-space:pre" ></span>//write data to file <span style= "White-space:pre" ></span>        Bw.write (This.getservletcontext (). getattribute ("Visittimes"). toString ()); <span style= "White-space:pre" ></span>//close file stream <spanStyle= "White-space:pre" ></span>bw.close ();    System.out.println ("Destroy is called");        } catch (Exception ex) {ex.printstacktrace (); }}//processing GET request//req: Used to obtain the client (browser) information//res: Used to return information to the client (browser) public void doget (HttpServletRequest req,httpservletresponse RES) {//business logic Connection ct=null; Statement Sm=null; ResultSet Rs=null;try {//Accept user name and password string u=req.getparameter ("Usrename"); String p=req.getparameter ("passwd");//Call userbeancl,1. Create an Object Userbeancl ubc=new userbeancl ();//2. Use the Userbeancl method if ( Ubc.checkuser (u,p)) {///legal user string Keep=req.getparameter ("Keep"), if (keep!=null) {//Save user name and password in client (cookie)//Create Cookie Name=new Cookie ("MyName", u); Cookie Pass=new Cookie ("mypasswd", p);//Set Time Name.setmaxage (14*24*3600);p ass.setmaxage (14*24*3600);// Write back to client Res.addcookie (name); Res.addcookie (pass);} Put the username and password into the session httpsession Hs=req.getsession (TRUE); Hs.setmaxinactiveinterval (+); Hs.setattribute ("Uname", u )///the value corresponding to Visittime in Serlvetcontext ++string times=this.getservletcontext (). getattribute ("VisittimeS "). ToString ();//times++ re-servletthis.getservletcontext (). SetAttribute (" Visittimes ", (Integer.parseint ( Times) +1) + "");//Jump to Welres.sendredirect ("Main");}    else{//illegal//Jump Res.sendredirect ("login");//write the URL of the servlet you want to go to} catch (Exception ex) {ex.printstacktrace ();    }finally{try {if (rs!=null) {rs.close ();    } if (Sm!=null) {sm.close ();    } if (Ct!=null) {ct.close ();    }} catch (Exception ex) {ex.printstacktrace (); }}//processing POST request//req: Used to obtain the client (browser) information//res: Used to return information to the client (browser) public void DoPost (HttpServletRequest req,httpservlet Response res) {this.doget (req,res);}}


(3) Submit to Wel page after successful login

Package Com.tsinghua;import javax.servlet.http.*;import java.io.*;import java.sql.*;import java.util.*;p ublic class Wel extends HttpServlet {//Processing GET request//req: Information for obtaining a client (browser)//res: Used to return information to the client (browser) public void doget (HttpServletRequest req , HttpServletResponse Res) {//business logic Connection ct=null; PreparedStatement Ps=null; ResultSet rs=null;//Business logic try {//Gets the user name HttpSession Hs=req.getsession (TRUE) from the session; String Myname= (String) hs.getattribute ("uname"); String name= ""; String passwd= ""; if (myname==null) {//If there is no user information in session, then see if there is cookie information//Get all cookie information from the client cookie [] allcookies= Req.getcookies (); int i=0;//If allcookies is not empty ... if (allcookies!=null) {//Out of Cookiefor (i=0;i<allcookies.length;i+ +) {//Take out the cookie temp=allcookies[i];if (Temp.getname (). Equals ("MyName")) {//Get the value of the cookie Name=temp.getvalue ();} else if (Temp.getname (). Equals ("mypasswd")) {Passwd=temp.getvalue ();}} System.out.println ("myname=" +name+ "pas=" +passwd); if (!name.equals ("") &&!passwd.equals ("")) {// Go to Logincl to verify Res.sendredirect ("Logincl?usrename=" +name+ "&passwd=" +passwd); return;}} Return to login interface Res.sendredirect ("Login?info=error1"); return;} Solve the Chinese garbled res.setcharacterencoding ("GBK"); PrintWriter pw=res.getwriter ();p w.println ("<body bgcolor= #CED3FF >");//Add page access to the function pw.println ("the page was accessed" +    This.getservletcontext (). getattribute ("Visittimes"). ToString () + "secondary <br>");p w.println ("</body>");    } catch (Exception ex) {ex.printstacktrace (); }}public void DoPost (HttpServletRequest req,httpservletresponse res) {this.doget (req,res);}}


There's no writing here. The page to be returned after the login is only implemented when the site user logs on to log off only once!

Implementing Web Counters with ServletContext

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.