当前位置:首页 > JSP教程 > JSP常见问题

在jsp中用bean和servlet联合实现用户注册、登录

声明:作者原创,版权所有。未经授权,不得转载
在jsp中用bean和servlet联合实现用户注册、登录

作者:imagebear
版权:imagebear

本例需要的软件和运行环境:
1、windows2000 server操作系统
2、jdk1.4
3、jcreator2.5(java源码编辑调试器,吐血推荐!)
4、macromedia jrun mx
5、macromedia dreamweaver mx(非必需)
6、mysql数据库(最好安装mysql control center)

一、数据库设计
用mysql control center打开mysql数据库,新建数据库shopping,在其下新建表tbl_user,其中各字段设置如下:


二、编写连接数据库bean:dbconn.java


//dbconn.java

//include required classes
import java.sql.*;

//==========================================
// define class dbconn
//==========================================
public class dbconn
{
 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;
 }

 public dbconn()
 {
  try{
   class.forname(sql_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());
  }
 }

                //执行查询操作
 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;
  }
 }

                //执行数据的插入、删除、修改操作
 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;
  }
 }

                //结果集指针跳转到某一行
 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;
  }
 }

                //此方法用于获取大段文本,
                //将其中的回车换行替换为<br>
                //输出到html页面
 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;
  }
 }

                //把str1字符串中的str2字符串替换为str3字符串
 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;
  }
 }

                //判断结果集中是否有数据
 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方法,调试用
 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());
  }
 }

}

声明:因为使用的是mysql数据库,所以需要mysql数据库的驱动
下载后请将org包放至dbconn.java所在目录下
以确保该bean能正常运行

 

三、编写用户注册的bean: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("姓名中含有非法字符!");
    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("密码中含有非法字符!");
    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("两次输入的密码不一致!");
    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中含有非法字符!");
    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("用户名已存在,请选择其它的用户名!");
    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","imagebear@163.com"));

   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());
  }
 }
};

说明:
1、该bean文件应和上文所述dbconn.class文件放于同一目录下
2、本例主要研究注册的过程,其中的email检测等方法并不完善,若要应用请自行设计方法

 


四、编写用户登陆的servlet: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)
 throws ioexception,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)
 throws ioexception,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"));
 }

}

说明:
1、默认的jdk1.4中并没有servlet包,请至sun公司网页下载servlet.jar,放至jdk目录下的jrelib目录下,并在jcreator中设置jdk处添加servlet.jar包 

2、本servlet用于检验用户名和密码,若正确则将用户名写入cookie,完成后将当前页重定向到index.jsp页

 


五、编写检测用户是否已经登陆的bean: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)
 throws ioexception,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("早上好," + this.username + "!");
   return true;
  }else{
   out.println("登陆失败!");
   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);
 }
}

说明:此bean检测cookie中的username,若不为空则说明已登录,反之说明没有登录。方法不够完善,您可以自行扩充。

 


六、在jrun中建立shopping服务器
打开jrun administrator,新建shopping服务器,这里端口为8101。
将上文所述所有编译后的class文件连同org包拷至jrun的shopping服务器所在目录中的classes文件夹下,路径为:


c:jrun4serversshoppingdefault-eardefault-warweb-infclasses

七、建立jsp文件
应用dw,在c:jrun4serversshoppingdefault-eardefault-war目录下新建如下的jsp文件:
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">卖场入口</td>
        </tr>
        <tr>
          <td width="50%" height="24" align="center" bgcolor="#ffffff">会员</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">密码</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">注册</a></td>
          <td align="center" bgcolor="#ffffff"><input type="submit" name="submit" value="进入"></td>
        </tr>
  </form>
      </table>
   <%
    }
  else
  {
   out.println("您好," + 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">会员注册</td>
        </tr>
        <tr>
          <td width="50%" height="24" align="center" bgcolor="#ffffff">会员</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">密码</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">验证密码</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="重写"></td>
          <td align="center" bgcolor="#ffffff"><input type="submit" name="submit2" value="注册"></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:注册表单提交页面<%@ 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">恭喜您,注册成功!</td>
        </tr>
        <tr>
          <td width="50%" height="24" align="center" bgcolor="#ffffff">编号</td>
          <td align="center" bgcolor="#ffffff"><%=newid%></td>
        </tr>
        <tr>
          <td width="50%" height="24" align="center" bgcolor="#ffffff">会员</td>
          <td align="center" bgcolor="#ffffff"><%=username%></td>
        </tr>
        <tr>
          <td width="50%" height="24" align="center" bgcolor="#ffffff">密码</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()>关闭</a>");
 }else{
  out.print("注册失败!<br>");
  out.print("该用户名已有人使用,请使用另外的用户名!");
  out.print("<a href=javascript:history.go(-1)>返回</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>
 至此,我们已经完成了一个用户注册、登录的系统。 因为这是本人自己边学边做完成的,所以代码一定有很多不完善的地方,欢迎大家批评指正。 以上所有代码均经本人测试通过。



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐