Source rendering, User check login servlet and Count complete code:
Package com.zkj;
Developed by inheriting HttpServlet
Import javax.servlet.http.*;
Import java.io.*;
Import javax.servlet.*;
public class Check extends httpservlet{
public void Init () throws servletexception{
try{
System.out.println ("Init is called");
The ability to add page access times
Get current number of times
FileReader FR = null;
BufferedReader bfr = null;
String Scount;
Try
{
FR = new FileReader ("D:\\data.txt");
BFR = new BufferedReader (FR);
Scount = Bfr.readline ();
This.getservletcontext (). SetAttribute ("Logintimes", Scount);
}catch (Exception e) {
}finally{
if (BFR! = null)
Bfr.close ();
}
}catch (Exception e) {
}
}
public void Destroy () {
try{
Write a new number of times back to the file
FileWriter FW = NULL;
BufferedWriter BFW = null;
try{
FW = new FileWriter ("D:\\data.txt");
BFW = new BufferedWriter (FW);
Bfw.write ("" + This.getservletcontext (). getattribute ("Logintimes"));
}catch (Exception e) {
}
finally{
if (BFW! = null)
Bfw.close ();
}
System.out.println ("Destroy is called");
}catch (Exception e) {
}
}
Handling GET Requests
public void Doget (HttpServletRequest req, httpservletresponse Res) {
SYSTEM.OUT.PRINTLN ("service It");
try{
Receive user name and password
String U=req.getparameter ("username");
String p=req.getparameter ("passwd");
Connecting to a database
Userbeanmanager UBM = new Userbeanmanager ();
Boolean bhas = Ubm.checkuservalid (U, p);
Verify
U.equals ("zkj") && p.equals ("123")
if (Bhas)
{
Legal user Access
String chk = req.getparameter ("Keep");
if (chk! = null) {
Save user name and password in cookie
Cookie CK = new Cookie ("MyName", u);
Cookie PS = new Cookie ("Mypass", p);
Set the life long
Ck.setmaxage (14*24*3600);
Ps.setmaxage (14*24*3600);
Write back to Client
Res.addcookie (CK);
Res.addcookie (PS);
}
Count increase write to ServletContext
String Scount = This.getservletcontext (). getattribute ("Logintimes"). ToString ();
int ncount = Integer.parseint (Scount);
Ncount + +;
This.getservletcontext (). SetAttribute ("Logintimes", Ncount + "");
//Transfer name to welcome
Res.sendredirect ("welcome?uname=" + u);
}else{
Res.sendredirect ("login");
}
}catch (Exception e) {
E.printstacktrace ();
}
}
Processing post requests is generally common, with a business logic
public void DoPost (HttpServletRequest req, httpservletresponse Res) {
This.doget (req, res);
}
}
To avoid reading and writing files multiple times, you need to read the original count in Init, save the count value to write to destroy
Servlet Learning Counter