In JSP, bean and servlet are used to realize user registration and login
Statement: original by the author, all rights reserved. Without authorization, it is not allowed to reprint in JSP, and use bean and servlet to jointly realize user registration and login
Author: imagebear Copyright: imagebear
The software and running environment required for this example: 1. Windows 2000 server operating system 2. Jdk1 4 3、JCreator2. 5 (Java source code editing debugger, recommended for hematemesis!) 4. Macromedia jrun MX 5. Macromedia Dreamweaver MX (not required) 6. MySQL database (it is best to install MySQL control center)
1、 Database design open the MySQL database with the MySQL control center, create a new database shopping, and create a new TABLE tbl under it_ User, where the fields are set as follows:
//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); / / load the 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()); } }
//Execute 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; } }
//Insert, delete and modify data 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 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 text, / / replace the carriage return and line feed with < br > / / output to the HTML page public string rs_ getHtmlString(String column) { try{ String str1 = this.rs.getString(column); String str2 = "\r\n"; String str3 = "
"; return this.replaceAll(str1,str2,str3); } catch(sqlException e){ System.out.println(e.toString()); return null; } } // Replace STR2 string in STR1 string with str3 string private static string replaceall (string STR1, string STR2, string str3) {StringBuffer strbuffer = 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; } }
//Judge 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, 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 ','shander')); / / myconn.execute (" update tbl_test set name ='yyyyyyyyyy '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 use the MySQL database, you need the driver of the MySQL database. After downloading, please put the org package to dbconn Java directory to ensure that the bean can run normally
3、 Write the bean registered by the user: 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 ("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 ("illegal character in password!"); 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 (" user name already exists, please select another user name! "); 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 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"," 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()); } } };
Note: 1. The bean file should be the same as dbconn Class files are placed in the same directory. 2. This example mainly studies the registration process. The email detection and other methods are not perfect. If you want to apply them, please design your own methods
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) 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,ServletException { doGet(req,res); } public static String getCookieValue(Cookie[] cookies,String cookieName,String defaultValue) { for(int i=0;i
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")); } }
Description: 1. The default is jdk1 There is no servlet package in 4. Please go to sun's website to download servlet Jar, put it in the JRE \ lib \ directory under the JDK directory, and add a servlet where the JDK is set in jcreator Jar package
2. This servlet is used to verify the user name and password. If correct, write the user name into the cookie, and redirect the current page to index JSP page
5、 Write a bean to check 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,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 defaultValue) { for(int i=0;i
Note: This bean detects the username in the cookie. If it is not empty, it indicates that it has logged in; otherwise, it indicates that it has not logged in. The method is not perfect enough. 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 of jrun's shopping server. The path is:
C:\JRun4\servers\shopping\default-ear\default-war\WEB-INF\classes\
7、 Create a JSP file application DW, and create the following JSP file in C: \ jrun4 \ servers \ shopping \ default ear \ default war \ Directory: index jsp:
<%@ page contentType="text/html;charset=gb2312" pageEncoding="gb2312" %>
| Shopping123 |
<% if(!login){ %>
| copyright © 2003 Shopping123 | ||||
reg. jsp<%@ page contentType="text/html;charset=gb2312" pageEncoding="gb2312" %>
|
|||||||
|
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 = "#ffff" 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"> |
|||||||
|
|||||||
|
|
|||||||
