Servlet learning notes (5) ----- Use servlet to process users registration and login (using cookies)

xiaoxiao2021-03-06  83

1. Almost 3, the only difference is to call the cookie in loginform.java. After you register, the first login will show "this is the first time you have logged on" Every time you log in, you will tell you the number of visitors. When you log in to the fifth time, "Congratulations !!!, you have a gife"

2. Loginform.java code is as follows:

Import javax.servlet. *;

Import javax.servlet.http. *;

Import java.io. *;

Import java.sql. *;

/// Import javax.sql. *;

Public Class Loginform Extends Httpservlet

{

Connection DBCON;

Protected void dopost (httpservletRequest Req,

HTTPSERVLETRESPONSE RESP)

Throws servletexception,

Java.io.ioException

{

Try

{

Class.Forname ("Sun.jdbc.odbc.jdbcodbcdriver");

DBCON = DriverManager.getConnection ("JDBC: ODBC: TEST", "SA", "");

System.out.println ("Connection Establish");

}

Catch (Exception E)

{

System.out.println ("Database Not Found!");

}

Resp.SetContentType ("text / html");

PrintWriter out = Resp.getwriter ();

String username = Req.getParameter ("UserName"). Trim ();

String pass = req.getParameter ("pass"). Trim ();

Try

{

PreparedStatement stat = dbcon.preparestatement

"SELECT * from userData where username =? and pass =?");

Stat.setstring (1, username);

Stat.SetString (2, pass);

ResultSet Result = stat.executeQuery ();

IF (result.next ())

{

Out.println (" ");

Out.println ("Login Successful");

out.println ( "

");

// cookie

Boolean cookiefound = false;

Cookie mycookie = NULL;

Cookie [] cookieset = Req.getCookies ();

For (int i = 0; i

{

IF (cookieset [i] .getname (). Equals ("logincount"))))

{

CookiefOnd = true;

mycookie = cookieset [i];

}

}

IF (cookiefound) {

INT TEMP = Integer.Parseint (mycookie.getvalue ());

TEMP ;

IF (Temp == 5)

{

Out.println ("CONGRATULATIONS !!!, You Have a gife");

}

Out.println ("this is the" temp "time you have logged on");

Mycookie.setValue (String.Valueof (Temp));

INT Age = 60 * 60 * 24 * 30;

Mycookie.setmaxage (age);

Resp.addcookie (MyCookie);

Cookiefound = false;

}

Else

{

INT TEMP = 1;

Out.println ("this is the first time you have logged on";

MyCookie = New cookie ("LoginCount", String.Valueof (Temp));

INT Age = 60 * 60 * 24 * 30;

Mycookie.setmaxage (age);

Resp.addcookie (MyCookie);

}

// end cookie

Out.println (" ");

}

Else

{

Out.println (" ");

Out.println ("Login Error");

out.println ( "

");

Out.println (" ");

}

}

Catch (Exception E)

{

e.tostring ();

}

Try

{

dbcon.close ();

}

Catch (Exception E)

{

System.out.println (E.TOString ());

}

}

}

转载请注明原文地址:https://www.9cbs.com/read-122631.html

New Post(0)