Statement: Original by the author, all rights reserved. Unauthorized reproduction is not allowed. Use beans and servlets to jointly implement user registration and login in jsp.
Author: imagebear
Copyright: imagebear
Software and operating environment required for this example:
1. Windows2000 Server operating system
2.jdk1.4
3. JCreator2.5 (java source code editing debugger, recommended for those who vomit blood!)
4. Macromedia JRun MX
5. Macromedia Dreamweaver MX (optional)
6. MySQL database (it is best to install MySQL Control Center)
1. Database design Open the MySQL database with MySQL Control Center, create a new database shopping, and create a new table tbl_user under it, with each field set as follows:
2. Write the connection database bean: DBConn.java
//DBConn.java
//include required classes
import java.sql.*;
//========================================== =
// Define ClassDBConn
//==========================================
public classDBConn
{
public String sql_driver = "org.gjt.mm.mysql.Driver";
public String sql_url = "jdbc:mysql://localhost:3306";
public String sql_DBName = "shopping";
public String user = "sa";
public String pwd = "";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
public boolean setDriver(String drv)
{
this.sql_driver = drv;
return true;
}
public String getDriver()
{
return this.sql_driver;
}
public boolean setUrl(String url)
{
this.sql_url = url;
return true;
}
public boolean setDBName(String dbname)
{
this.sql_DBName = dbname;
return true;
}
public String getDBName()
{
return this.sql_DBName;
}
public boolean setUser(String user)
{
this.user = user;
return true;
}
public String getUser()
{
return this.user;
}
public boolean setPwd(String pwd)
{
this.pwd = pwd;
return true;
}
public String getPwd()
{
return this.pwd;
}
publicDBConn()
{
try{
Class.forName(sql_driver);//Load database driver
this.conn = DriverManager.getConnection(sql_url + "/" + sql_DBName + "?user=" + user + "&password=" + pwd + "&useUnicode=true&characterEncoding=gb2312");
this.stmt = this.conn.createStatement();
}catch(Exception e){
System.out.println(e.toString());
}
}
//Perform query operation
public ResultSet executeQuery(String strSql)
{
try{
this.rs = stmt.executeQuery(strSql);
return this.rs;
}catch(SQLException e){
System.out.println(e.toString());
return null;
}catch(NullPointerException e){
System.out.println(e.toString());
return null;
}
}
//Perform data insertion, deletion, and modification operations
public boolean execute(String strSql)
{
try{
if(this.stmt.executeUpdate(strSql) == 0)
return false;
else
return true;
}catch(SQLException e){
System.out.println(e.toString());
return false;
}catch(NullPointerException e){
System.out.println(e.toString());
return false;
}
}
//The result set pointer jumps to a certain row
public boolean rs_absolute(int row)
{
try{
this.rs.absolute(row);
return true;
}catch(SQLException e){
System.out.println(e.toString());
return false;
}
}
public void rs_afterLast()
{
try{
this.rs.afterLast();
}catch(SQLException e){
System.out.println(e.toString());
}
}
public void rs_beforeFirst()
{
try{
this.rs.beforeFirst();
}catch(SQLException e){
System.out.print(e.toString());
}
}
public void rs_close()
{
try{
this.rs.close();
}catch(SQLException e){
System.out.print(e.toString());
}
}
public void rs_deleteRow()
{
try{
this.rs.deleteRow();
}catch(SQLException e){
System.out.print(e.toString());
}
}
public boolean rs_first()
{
try{
this.rs.first();
return true;
}catch(SQLException e){
System.out.print(e.toString());
return false;
}
}
public String rs_getString(String column)
{
try{
return this.rs.getString(column);
}catch(SQLException e){
System.out.println(e.toString());
return null;
}
}
//This method is used to obtain large sections of text,
//Replace the carriage return and line feed with <br>
//Output to html page
public String rs_getHtmlString(String column)
{
try{
String str1 = this.rs.getString(column);
String str2 = "rn";
String str3 = "<br>";
return this.replaceAll(str1,str2,str3);
}catch(SQLException e){
System.out.println(e.toString());
return null;
}
}
//Replace the str2 string in the str1 string with the str3 string
private static String replaceAll(String str1,String str2,String str3)
{
StringBuffer strBuf = new StringBuffer(str1);
int index=0;
while(str1.indexOf(str2,index)!=-1)
{
index=str1.indexOf(str2,index);
strBuf.replace(str1.indexOf(str2,index),str1.indexOf(str2,index)+str2.length(),str3);
index=index+str3.length();
str1=strBuf.toString();
}
return strBuf.toString();
}
public int rs_getInt(String column)
{
try{
return this.rs.getInt(column);
}catch(SQLException e){
System.out.println(e.toString());
return -1;
}
}
public int rs_getInt(int column)
{
try{
return this.rs.getInt(column);
}catch(SQLException e){
System.out.println(e.toString());
return -1;
}
}
public boolean rs_next()
{
try{
return this.rs.next();
}catch(SQLException e){
System.out.println(e.toString());
return false;
}
}
//Determine whether there is data in the result set
public boolean hasData()
{
try{
boolean has_Data = this.rs.first();
this.rs.beforeFirst();
return has_Data;
}catch(SQLException e){
System.out.println(e.toString());
return false;
}
}
public boolean rs_last()
{
try{
return this.rs.last();
}catch(SQLException e){
System.out.println(e.toString());
return false;
}
}
public boolean rs_previous()
{
try{
return this.rs.previous();
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}
//main method, used for debugging
public static void main(String args[])
{
try{
DBConn myconn = new DBConn();
//myconn.setDBName("shopping");
//myconn.DBConn();
//myconn.execute("Insert Into tbl_test(id,name) values('10','shandaer')");
//myconn.execute("Update tbl_test set name='yyyyyyyyyyyy' where id=10");
//myconn.execute("Delete from tbl_test where id=1");
ResultSet rs = myconn.executeQuery("select * from tbl_user order by id desc limit 1");
//boolean hasData = myconn.hasData();
//System.out.println("has data:" + hasData);
//rs.first();
while (myconn.rs.next())
{
int id = myconn.rs_getInt("id") + 1;
System.out.print(id);
System.out.println(myconn.rs_getInt("id") + myconn.rs_getString("name"));
//System.out.println('n' + myconn.rs_getHtmlString("name"));
//System.out.println(myconn.rs.getString("name") + myconn.rs_getInt(1));
}
}catch(Exception e){
System.err.println(e.toString());
}
}
}
Statement: Because you are using a MySQL database, you need to download the MySQL database driver. After downloading, please put the org package in the directory where DBConn.java is located to ensure that the bean can run normally.
3. Write the bean for user registration: reg.java
//reg.java
//import required classes
import java.sql.*;
public class reg
{
public int newID = 0;
public boolean result = false;
public boolean reg(String username,String password,String confirm,String email)
{
try{
if(!this.checkUser(username))
return false;
if(!this.checkPwd(password))
return false;
if(!this.verifyPwd(password,confirm))
return false;
if(!this.checkEmail(email))
return false;
if(!this.userNotExit(username))
return false;
this.getNewID();
this.result = this.register(username,password,confirm,email);
return this.result;
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}//End boolean reg
public boolean checkUser(String user)
{
try{
if(user.indexOf("'")!=-1)
{
System.out.println("The name contains illegal characters!");
return false;
}else
return true;
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}
public boolean checkPwd(String pwd)
{
try{
if(pwd.indexOf("'")!=-1)
{
System.out.println("Password contains illegal characters!");
return false;
}else
return true;
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}
public boolean verifyPwd(String pwd,String confirm)
{
try{
if(!pwd.equals(confirm))
{
System.out.println("The passwords entered twice are inconsistent!");
return false;
}else
return true;
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}
public boolean checkEmail(String email)
{
try{
if(email.indexOf("'")!=-1)
{
System.out.println("E-mail contains illegal characters!");
return false;
}else
return true;
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}
public boolean userNotExit(String user)
{
try{
DBConn userDBConn = new DBConn();
userDBConn.executeQuery("select * from tbl_user where name='" + user + "'");
if(userDBConn.rs_next())
{
System.out.println("The username already exists, please choose another username!");
return false;
}else
return true;
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}
public int getNewID()
{
try{
DBConn newIDDBConn = new DBConn();
newIDDBConn.executeQuery("select * from tbl_user order by id desc limit 1");
if(newIDDBConn.rs_next())
{
this.newID = newIDDBConn.rs_getInt("id") + 1;
System.out.println(this.newID);
}else{
this.newID = 1;
}
return this.newID;
}catch(Exception e){
System.out.println(e.toString());
return -1;
}
}
public int getID()
{
return this.newID;
}
public boolean register(String username,String password,String confirm,String email)
{
try{
DBConn regDBConn = new DBConn();
String strSQL = "insert into tbl_user(id,name,pwd,email) values('" + this.newID +"','" + username + "','" + password + "','" + email + " ')";
regDBConn.execute(strSQL);
return true;
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}
public static void main(String args[])
{
try{
reg newreg = new reg();
System.out.println(newreg.reg("sssssssss","ssssss","ssssss"," [email protected] "));
DBConn myconn = new DBConn();
myconn.executeQuery("select * from tbl_user");
while(myconn.rs_next())
{
System.out.println(myconn.rs_getInt("id") + " " + myconn.rs_getString("name") + " " + myconn.rs_getString("pwd") + " " + myconn.rs_getString("email") );
}
System.out.println(newreg.getID());
}catch(Exception e){
System.err.println(e.toString());
}
}
};
illustrate:
1. The bean file should be placed in the same directory as the DBConn.class file mentioned above.
2. This example mainly studies the registration process. The email detection and other methods are not perfect. If you want to apply it, please design your own method.
4. Write the Servlet for user login: login.java
//login.java
//import required classes
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
//class login
public class login extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throwsIOException,ServletException
{
String username = req.getParameter("username");
String password = req.getParameter("password");
if(this.checklogin(username,password))
{
Cookie mylogin = new Cookie("username",username);
mylogin.setVersion(1);
mylogin.setPath("/");
mylogin.setComment("Your login username");
res.addCookie(mylogin);
}
//Cookie[] myCookies = req.getCookies();
//String nameValue = this.getCookieValue(myCookies,"username","not found");
//PrintWriter out = res.getWriter();
//out.println("username" + ":" + nameValue);
//out.println("Test Cookie Success!");
res.sendRedirect("/index.jsp");
}
public void doPost(HttpServletRequest req,HttpServletResponse res)
throwsIOException,ServletException
{
doGet(req,res);
}
public static String getCookieValue(Cookie[] cookies,String cookieName,String defaultValue)
{
for(int i=0;i<cookies.length;i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
return(defaultValue);
}
public boolean checklogin(String username,String password)
{
try{
DBConn loginConn = new DBConn();
loginConn.executeQuery("select * from tbl_user where name='" + username + "'");
if(loginConn.rs_next())
{
System.out.println("Connection created!");
if(loginConn.rs_getString("pwd").trim().equals(password))
{
System.out.println(loginConn.rs_getString("name"));
return true;
}
else
{
return false;
}
}
System.out.println("Test Login Success!");
return false;
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}
public static void main(String args[])
{
login mylogin = new login();
System.out.println(mylogin.checklogin("shandong","shandong"));
}
}
illustrate:
1. There is no servlet package in the default jdk1.4. Please go to the sun company website to download servlet.jar, put it in the jrelib directory under the jdk directory, and add the servlet.jar package to the jdk setting in JCreator
2. This Servlet is used to verify the username and password. If correct, the username will be written into the cookie. After completion, the current page will be redirected to the index.jsp page.
5. Write a bean to detect whether the user has logged in: checkLogin.java
//checkLogin.java
//import required classes
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
//class checkLogin
public class checkLogin
{
public String username = "";
public boolean check(HttpServletRequest req,HttpServletResponse res)
throwsIOException,ServletException
{
String cookieName = "username";
Cookie[] myCookies = req.getCookies();
this.username = this.getCookieValue(myCookies,cookieName,"not found");
PrintWriter out = res.getWriter();
if(this.username != null)
{
//out.println("Good morning," + this.username + "!");
return true;
}else{
out.println("Login failed!");
return false;
}
}
public String getUserName()
{
return this.username;
}
public static String getCookieValue(Cookie[] cookies,String cookieName,String defaultValue)
{
for(int i=0;i<cookies.length;i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
return(defaultValue);
}
}
Description: This bean detects the username in the cookie. If it is not empty, it means you are logged in, otherwise it means you are not logged in. The method is not perfect, you can expand it yourself.
6. Create a shopping server in JRun. Open JRun Administrator and create a new shopping server. The port here is 8101.
Copy all the compiled class files mentioned above together with the org package to the classes folder in the directory where JRun's shopping server is located. The path is:
C:JRun4serversshoppingdefault-eardefault-warWEB-INFclasses
7. Create jsp file application DW in the C:JRun4serversshoppingdefault-eardefault-war directory Create a new jsp file as follows:
index.jsp:
<%@ page contentType="text/html;charset=gb2312" pageEncoding="gb2312" %>
<html>
<head>
<title>Shopping123</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="styles/shoppingstyle.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0">
<jsp:useBean id="checklogin" class="checkLogin" scope="page"/>
<%
boolean login = checklogin.check(request,response);
%>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr bgcolor="#990000">
<td height="80" colspan="5"><table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="120"> </td>
<td class="caption">Shopping123</td>
<td width="200"> </td>
</tr>
</table></td>
</tr>
<tr>
<td width="200" align="center" valign="top"><table width="100%" height="20" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
</table>
<%
if(!login){
%>
<table width="90%" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<form name="form1" method="post" action="/servlet/login">
<tr align="center" bgcolor="#CCCCCC">
<td height="30" colspan="2" class="deepred">Storage entrance</td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF">Member</td>
<td align="center" bgcolor="#FFFFFF"><input name="username" type="text" id="username" size="10"></td>
</tr>
<tr>
<td height="24" align="center" bgcolor="#FFFFFF">Password</td>
<td align="center" bgcolor="#FFFFFF"><input name="password" type="text" id="password" size="10"></td>
</tr>
<tr>
<td height="24" align="center" bgcolor="#FFFFFF"><a href="reg.jsp" target="_blank" class="red">Register</a></td>
<td align="center" bgcolor="#FFFFFF"><input type="submit" name="Submit" value="Enter"></td>
</tr>
</form>
</table>
<%
}
else
{
out.println("Hello," + checklogin.getUserName() + "!");
}
%>
</td>
<td width="1" valign="top" bgcolor="#CCCCCC"></td>
<td width="400"> </td>
<td width="1" valign="top" bgcolor="#CCCCCC"></td>
<td width="200"> </td>
</tr>
<tr align="center" bgcolor="#990000">
<td height="60" colspan="5" class="white">copyright© 2003 Shopping123</td>
</tr>
</table>
</body>
</html>
reg.jsp<%@ page contentType="text/html;charset=gb2312" pageEncoding="gb2312" %>
<html>
<head>
<title>Shopping123</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="styles/shoppingstyle.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0">
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr bgcolor="#990000">
<td height="80" colspan="5"><table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="120"> </td>
<td class="caption">Shopping123</td>
<td width="200"> </td>
</tr>
</table></td>
</tr>
<tr>
<td width="100" align="center" valign="top"> </td>
<td width="1" valign="top"></td>
<td width="400" align="center" valign="top"><table width="100%" height="20" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
</table>
<table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<form action="regpost.jsp" method="post" name="form1">
<tr align="center">
<td height="30" colspan="2" bgcolor="#CCCCCC" class="deepred">Member registration</td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF">Member</td>
<td align="center" bgcolor="#FFFFFF"><input name="username" type="text" id="username" size="16"></td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF">Password</td>
<td align="center" bgcolor="#FFFFFF"><input name="password" type="password" id="password" size="16"></td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF">Verify password</td>
<td align="center" bgcolor="#FFFFFF"><input name="confirm" type="password" id="confirm" size="16"></td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF">E-mail</td>
<td align="center" bgcolor="#FFFFFF"><input name="email" type="text" id="email" size="16"></td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF"><input type="submit" name="Submit" value="Rewrite"></td>
<td align="center" bgcolor="#FFFFFF"><input type="submit" name="Submit2" value="Register"></td>
</tr>
</form>
</table></td>
<td width="1" valign="top"></td>
<td width="100"> </td>
</tr>
<tr align="center" bgcolor="#990000">
<td height="60" colspan="5" class="white">copyright© 2003 Shopping123</td>
</tr>
</table>
</body>
</html>
regpost.jsp: Registration form submission page <%@ page contentType="text/html;charset=gb2312" pageEncoding="gb2312" %>
<%@ page import="reg"%>
<html>
<head>
<title>Shopping123</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="styles/shoppingstyle.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0">
<%
String username = new String(request.getParameter("username").getBytes("ISO8859_1")).trim();
String password = new String(request.getParameter("password").getBytes("ISO8859_1")).trim();
String confirm = new String(request.getParameter("confirm").getBytes("ISO8859_1")).trim();
String email = new String(request.getParameter("email").getBytes("ISO8859_1")).trim();
%>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr bgcolor="#990000">
<td height="80" colspan="5"><table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="120"> </td>
<td class="caption">Shopping123</td>
<td width="200"> </td>
</tr>
</table></td>
</tr>
<tr>
<td width="100" align="center" valign="top"> </td>
<td width="1" valign="top"></td>
<td width="400" align="center" valign="top">
<table width="100%" height="20" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
</table>
<jsp:useBean id="regID" class="reg" scope="session"/>
<%
if(regID.reg(username,password,confirm,email))
{
out.print("ok");
String newID = regID.getID() + "";
%>
<table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr align="center">
<td height="30" colspan="2" bgcolor="#CCCCCC" class="deepred">Congratulations, your registration is successful! </td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF">Number</td>
<td align="center" bgcolor="#FFFFFF"><%=newID%></td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF">Member</td>
<td align="center" bgcolor="#FFFFFF"><%=username%></td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF">Password</td>
<td align="center" bgcolor="#FFFFFF"><%=password%></td>
</tr>
<tr>
<td width="50%" height="24" align="center" bgcolor="#FFFFFF">E-mail</td>
<td align="center" bgcolor="#FFFFFF"><%=email%></td>
</tr>
</table>
<%
out.print("<br>");
out.print("<a href=javascript:window.close()>Close</a>");
}else{
out.print("Registration failed!<br>");
out.print("This username is already used, please use another username!");
out.print("<a href=javascript:history.go(-1)>Return</a>");
}
%>
</td>
<td width="1" valign="top"></td>
<td width="100"> </td>
</tr>
<tr align="center" bgcolor="#990000">
<td height="60" colspan="5" class="white">copyright© 2003 Shopping123</td>
</tr>
</table>
</body>
</html>
So far, we have completed a user registration and login system. Because this was completed by myself while learning, there must be many imperfections in the code. Everyone is welcome to criticize and correct me. All the above codes have been tested by me.