开发用的工具Myeclipse6.0,JDK1.5,TOMCAT5.5,SQLSERVLET2000;用的是最基础的j2ee:jsp+javabean+servlet
1,现在在系统完成后的包类:
2,com.he.db里的DB.java,作用是连接数据库和创建stament和resultset和关闭他们。以及增删查该的执行
3,com.he.manager里的Manager.java,作用是实现登录系统所需要用到的各项功能。例如添加帐号,查看是否数据库里有同名帐号等。。
4,com.he.pojo里的Account.java,作用是临时存放并传递帐号的各项属性。
5.com.he.bean里的makeCertpic.java,作用是生成验证码的图片。
6。com.he.servlet里的LoginServlet.java,作用是验证登录。
7。com.he.servlet里的Registe.java作用是进行注册操作。
8。index.jsp,登录界面。
9。registe.jsp,注册界面
10。makeCertpic.jsp 验证码图片的
11.SucceedLogin.jsp 登录成功的页面
12。CheckLogin.jsp 进行未登录就进入登录成功的界面的验证
13.web.xml文件
14.到此,我的注册登录系统基本完成了。新人作品,希望大家批评指正。
1,现在在系统完成后的包类:
2,com.he.db里的DB.java,作用是连接数据库和创建stament和resultset和关闭他们。以及增删查该的执行
1
package
com.he.db;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.sql.Statement;
9
10 public class DB {
11
12 private static DB db = null ;
13 private static Connection conn = null ;
14 private static Statement stmt = null ;
15
16 // 单例模式,new DB类的时候,创建唯一对象,只初始化一次,
17 // 注意:不要显式交闭此static中的Connection和Statement对象,否则抛空指针异常
18 static {
19 try {
20 String driverClass = " net.sourceforge.jtds.jdbc.Driver " ;
21 String url = " jdbc:jtds:sqlserver://localhost:1433;DatabaseName=login " ;
22 String username = " sa " ; // edit
23 String password = "" ; // edit
24 Class.forName(driverClass);
25 conn = DriverManager.getConnection(url,username,password);
26 stmt = conn.createStatement();
27 System.out.println( " --------初始化--------- " );
28 } catch (ClassNotFoundException e) {
29 System.out.println( " ---------- 加载数据库驱动类时发生异常: ---------- " );
30 e.printStackTrace();
31 } catch (SQLException e) {
32 System.out.println( " ------------ getConnection()方法发生异常-------------- " );
33 }
34 }
35
36 // 创建PrepareStatement对象
37 public PreparedStatement prepareStmt(String sql){
38 PreparedStatement pstmt = null ;
39 try {
40 pstmt = conn.prepareStatement(sql);
41 } catch (SQLException e) {
42 System.out.println( " -------------prepareStmt()方法发生异常------------------- " );
43 e.printStackTrace();
44 }
45 return pstmt;
46 }
47
48 // 执行查询所有记录操作
49 public ResultSet exeQuery(String sql){
50 ResultSet rs = null ;
51 try {
52 rs = stmt.executeQuery(sql);
53 } catch (SQLException e) {
54 System.out.println( " ------------exeQuery()方法发生异常: -------------------- " );
55 e.printStackTrace();
56 }
57 return rs;
58 }
59
60 // 执行保存、更新、删除操作
61 public void exeUpdate(String sql){
62 try {
63 stmt.executeUpdate(sql);
64 } catch (SQLException e){
65 System.out.println( " ------------- exeUpdate()方法发生异常------------------ " );
66 e.printStackTrace();
67 }
68 }
69
70
71 // 关闭PreparedStatement对象
72 public void closePstmt(PreparedStatement pstmt){
73 try {
74 pstmt.close();
75 pstmt = null ;
76 } catch (SQLException e){
77 System.out.println( " -------------------- DB.closePstmt()方法发生异常 ------------------------- " );
78 e.printStackTrace();
79 }
80 }
81
82 // 关闭ResultSet对象
83 public void closeRs(ResultSet rs){
84 try {
85 rs.close();
86 rs = null ;
87 } catch (SQLException e){
88 System.out.println( " -------------------- DB.closePstmt()方法发生异常 ------------------------- " );
89 e.printStackTrace();
90 }
91 }
92
93
94 }
95
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.sql.Statement;
9
10 public class DB {
11
12 private static DB db = null ;
13 private static Connection conn = null ;
14 private static Statement stmt = null ;
15
16 // 单例模式,new DB类的时候,创建唯一对象,只初始化一次,
17 // 注意:不要显式交闭此static中的Connection和Statement对象,否则抛空指针异常
18 static {
19 try {
20 String driverClass = " net.sourceforge.jtds.jdbc.Driver " ;
21 String url = " jdbc:jtds:sqlserver://localhost:1433;DatabaseName=login " ;
22 String username = " sa " ; // edit
23 String password = "" ; // edit
24 Class.forName(driverClass);
25 conn = DriverManager.getConnection(url,username,password);
26 stmt = conn.createStatement();
27 System.out.println( " --------初始化--------- " );
28 } catch (ClassNotFoundException e) {
29 System.out.println( " ---------- 加载数据库驱动类时发生异常: ---------- " );
30 e.printStackTrace();
31 } catch (SQLException e) {
32 System.out.println( " ------------ getConnection()方法发生异常-------------- " );
33 }
34 }
35
36 // 创建PrepareStatement对象
37 public PreparedStatement prepareStmt(String sql){
38 PreparedStatement pstmt = null ;
39 try {
40 pstmt = conn.prepareStatement(sql);
41 } catch (SQLException e) {
42 System.out.println( " -------------prepareStmt()方法发生异常------------------- " );
43 e.printStackTrace();
44 }
45 return pstmt;
46 }
47
48 // 执行查询所有记录操作
49 public ResultSet exeQuery(String sql){
50 ResultSet rs = null ;
51 try {
52 rs = stmt.executeQuery(sql);
53 } catch (SQLException e) {
54 System.out.println( " ------------exeQuery()方法发生异常: -------------------- " );
55 e.printStackTrace();
56 }
57 return rs;
58 }
59
60 // 执行保存、更新、删除操作
61 public void exeUpdate(String sql){
62 try {
63 stmt.executeUpdate(sql);
64 } catch (SQLException e){
65 System.out.println( " ------------- exeUpdate()方法发生异常------------------ " );
66 e.printStackTrace();
67 }
68 }
69
70
71 // 关闭PreparedStatement对象
72 public void closePstmt(PreparedStatement pstmt){
73 try {
74 pstmt.close();
75 pstmt = null ;
76 } catch (SQLException e){
77 System.out.println( " -------------------- DB.closePstmt()方法发生异常 ------------------------- " );
78 e.printStackTrace();
79 }
80 }
81
82 // 关闭ResultSet对象
83 public void closeRs(ResultSet rs){
84 try {
85 rs.close();
86 rs = null ;
87 } catch (SQLException e){
88 System.out.println( " -------------------- DB.closePstmt()方法发生异常 ------------------------- " );
89 e.printStackTrace();
90 }
91 }
92
93
94 }
95
3,com.he.manager里的Manager.java,作用是实现登录系统所需要用到的各项功能。例如添加帐号,查看是否数据库里有同名帐号等。。
1
package
com.he.manager;
2
3 import java.sql.PreparedStatement;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6 import java.util.ArrayList;
7 import java.util.Iterator;
8 import java.util.List;
9 import java.util.regex.Pattern;
10
11 import com.he.db.DB;
12 import com.he.pojo.Account;
13 import com.sun.org.apache.xerces.internal.impl.xs.identity.Selector.Matcher;
14
15 public class Manager {
16
17 DB db = new DB();
18
19 // 添加帐号
20 public void addAccount(Account account) {
21 PreparedStatement pstmt = null ;
22 String sql = " insert into account(name,pwd,addtime) values(?,?,?) " ;
23 pstmt = db.prepareStmt(sql);
24 try {
25 pstmt.setString( 1 , account.getName());
26 pstmt.setString( 2 , account.getPwd());
27 pstmt.setString( 3 , account.getAddtime());
28 pstmt.executeUpdate();
29
30 } catch (SQLException e) {
31 System.out
32 .println( " -----------------Manager.addAccount()方法异常------------------------- " );
33 e.printStackTrace();
34 } finally {
35 db.closePstmt(pstmt);
36 }
37 }
38
39 // 查看数据库里是否有指定name的相同记录;
40 public static boolean HasAccount(String name) {
41 DB db = new DB();
42 ResultSet rs = null ;
43 int count = 0 ;
44 String sql = " select count(*) from account where name = ' " + name + " ' " ;
45 rs = db.exeQuery(sql);
46 try {
47 while (rs.next()) {
48 count = rs.getInt( 1 );
49 }
50 } catch (SQLException e) {
51 System.out
52 .println( " ------------Manager.HasAccount()方法异常------------------------ " );
53 e.printStackTrace();
54 } finally {
55 db.closeRs(rs);
56 }
57 if (count > 0 ) {
58 return true ;
59 } else
60 return false ;
61 }
62
63 // 判断提交的帐号密码是否有相应的记录在数据库中;
64 public static boolean CheckAccount(String name, String pwd) {
65 DB db = new DB();
66 ResultSet rs = null ;
67 int count = 0 ;
68 String sql = " select count(*) from account where name = ' " + name
69 + " ' and pwd = ' " + pwd + " ' " ;
70 rs = db.exeQuery(sql);
71 try {
72 while (rs.next()) {
73 count = rs.getInt( 1 );
74 }
75 } catch (SQLException e) {
76 System.out
77 .println( " -----------Manager.CheckAccount()方法异常-------------- " );
78 } finally {
79 db.closeRs(rs);
80 }
81 if (count > 0 ) { // 如果结果大于0;
82 return true ; // 表示此用户存在;
83 } else
84 return false ; // 表示此用户不存在;
85 }
86
87 // 判断提交的帐号密码是否符合要求;
88 public static boolean CheckForm(String name, String pwd) {
89 String regEx = " [a-zA-Z0-9]{4,8}+ " ; // 正则表达示:四到八位的数字或字母
90 if (name.matches(regEx) && pwd.matches(regEx)) return true ;
91 else return false ;
92 }
93
94 }
95
2
3 import java.sql.PreparedStatement;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6 import java.util.ArrayList;
7 import java.util.Iterator;
8 import java.util.List;
9 import java.util.regex.Pattern;
10
11 import com.he.db.DB;
12 import com.he.pojo.Account;
13 import com.sun.org.apache.xerces.internal.impl.xs.identity.Selector.Matcher;
14
15 public class Manager {
16
17 DB db = new DB();
18
19 // 添加帐号
20 public void addAccount(Account account) {
21 PreparedStatement pstmt = null ;
22 String sql = " insert into account(name,pwd,addtime) values(?,?,?) " ;
23 pstmt = db.prepareStmt(sql);
24 try {
25 pstmt.setString( 1 , account.getName());
26 pstmt.setString( 2 , account.getPwd());
27 pstmt.setString( 3 , account.getAddtime());
28 pstmt.executeUpdate();
29
30 } catch (SQLException e) {
31 System.out
32 .println( " -----------------Manager.addAccount()方法异常------------------------- " );
33 e.printStackTrace();
34 } finally {
35 db.closePstmt(pstmt);
36 }
37 }
38
39 // 查看数据库里是否有指定name的相同记录;
40 public static boolean HasAccount(String name) {
41 DB db = new DB();
42 ResultSet rs = null ;
43 int count = 0 ;
44 String sql = " select count(*) from account where name = ' " + name + " ' " ;
45 rs = db.exeQuery(sql);
46 try {
47 while (rs.next()) {
48 count = rs.getInt( 1 );
49 }
50 } catch (SQLException e) {
51 System.out
52 .println( " ------------Manager.HasAccount()方法异常------------------------ " );
53 e.printStackTrace();
54 } finally {
55 db.closeRs(rs);
56 }
57 if (count > 0 ) {
58 return true ;
59 } else
60 return false ;
61 }
62
63 // 判断提交的帐号密码是否有相应的记录在数据库中;
64 public static boolean CheckAccount(String name, String pwd) {
65 DB db = new DB();
66 ResultSet rs = null ;
67 int count = 0 ;
68 String sql = " select count(*) from account where name = ' " + name
69 + " ' and pwd = ' " + pwd + " ' " ;
70 rs = db.exeQuery(sql);
71 try {
72 while (rs.next()) {
73 count = rs.getInt( 1 );
74 }
75 } catch (SQLException e) {
76 System.out
77 .println( " -----------Manager.CheckAccount()方法异常-------------- " );
78 } finally {
79 db.closeRs(rs);
80 }
81 if (count > 0 ) { // 如果结果大于0;
82 return true ; // 表示此用户存在;
83 } else
84 return false ; // 表示此用户不存在;
85 }
86
87 // 判断提交的帐号密码是否符合要求;
88 public static boolean CheckForm(String name, String pwd) {
89 String regEx = " [a-zA-Z0-9]{4,8}+ " ; // 正则表达示:四到八位的数字或字母
90 if (name.matches(regEx) && pwd.matches(regEx)) return true ;
91 else return false ;
92 }
93
94 }
95
4,com.he.pojo里的Account.java,作用是临时存放并传递帐号的各项属性。
1
package
com.he.pojo;
2
3 public class Account {
4 private int id;
5 private String name;
6 private String pwd;
7 private String addtime;
8
9 public int getId() {
10 return id;
11 }
12 public void setId( int id) {
13 this .id = id;
14 }
15
16 public String getName() {
17 return name;
18 }
19 public void setName(String name) {
20 this .name = name;
21 }
22
23 public String getPwd() {
24 return pwd;
25 }
26 public void setPwd(String pwd) {
27 this .pwd = pwd;
28 }
29
30 public String getAddtime() {
31 return addtime;
32 }
33 public void setAddtime(String addtime) {
34 this .addtime = addtime;
35 }
36
37 }
38
2
3 public class Account {
4 private int id;
5 private String name;
6 private String pwd;
7 private String addtime;
8
9 public int getId() {
10 return id;
11 }
12 public void setId( int id) {
13 this .id = id;
14 }
15
16 public String getName() {
17 return name;
18 }
19 public void setName(String name) {
20 this .name = name;
21 }
22
23 public String getPwd() {
24 return pwd;
25 }
26 public void setPwd(String pwd) {
27 this .pwd = pwd;
28 }
29
30 public String getAddtime() {
31 return addtime;
32 }
33 public void setAddtime(String addtime) {
34 this .addtime = addtime;
35 }
36
37 }
38
5.com.he.bean里的makeCertpic.java,作用是生成验证码的图片。
1
package
com.he.bean;
2
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.Graphics;
6 import java.awt.image.BufferedImage;
7 import java.io.IOException;
8 import java.io.OutputStream;
9 import java.util.Random;
10 import javax.imageio.ImageIO;
11
12 /**
13 * @author dzy 生成验证码图片
14 */
15 public class makeCertPic {
16 // 验证码图片中可以出现的字符集,可根据需要修改
17 private char mapTable[] = { ' a ' , ' b ' , ' c ' , ' d ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' ,
18 ' j ' , ' k ' , ' l ' , ' m ' , ' n ' , ' o ' , ' p ' , ' q ' , ' r ' , ' s ' , ' t ' , ' u ' , ' v ' ,
19 ' w ' , ' x ' , ' y ' , ' z ' , ' 0 ' , ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' ,
20 ' 9 ' };
21
22 /**
23 * 功能:生成彩色验证码图片 参数width为生成的图片的宽度,参数height为生成的图片的高度,参数os为页面的输出流
24 */
25 public String getCertPic( int width, int height, OutputStream os) {
26 if (width <= 0 )
27 width = 60 ;
28 if (height <= 0 )
29 height = 20 ;
30 BufferedImage image = new BufferedImage(width, height,
31 BufferedImage.TYPE_INT_RGB);
32 // 获取图形上下文
33 Graphics g = image.getGraphics();
34 // 设定背景色
35 g.setColor( new Color( 0xDCDCDC ));
36 g.fillRect( 0 , 0 , width, height);
37 // 画边框
38 g.setColor(Color.black);
39 g.drawRect( 0 , 0 , width - 1 , height - 1 );
40 // 取随机产生的认证码
41 String strEnsure = "" ;
42 // 4代表4位验证码,如果要生成更多位的认证码,则加大数值
43 for ( int i = 0 ; i < 4 ; ++ i) {
44 strEnsure += mapTable[( int ) (mapTable.length * Math.random())];
45 }
46 // 将认证码显示到图象中,如果要生成更多位的认证码,增加drawString语句
47 g.setColor(Color.black);
48 g.setFont( new Font( " Atlantic Inline " , Font.PLAIN, 18 ));
49 String str = strEnsure.substring( 0 , 1 );
50 g.drawString(str, 8 , 17 );
51 str = strEnsure.substring( 1 , 2 );
52 g.drawString(str, 20 , 15 );
53 str = strEnsure.substring( 2 , 3 );
54 g.drawString(str, 35 , 18 );
55 str = strEnsure.substring( 3 , 4 );
56 g.drawString(str, 45 , 15 );
57 // 随机产生10个干扰点
58 Random rand = new Random();
59 for ( int i = 0 ; i < 10 ; i ++ ) {
60 int x = rand.nextInt(width);
61 int y = rand.nextInt(height);
62 g.drawOval(x, y, 1 , 1 );
63 }
64 // 释放图形上下文
65 g.dispose();
66 try {
67 // 输出图象到页面
68 ImageIO.write(image, " JPEG " , os);
69 } catch (IOException e) {
70 return "" ;
71 }
72 return strEnsure;
73 }
74 }
75
2
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.Graphics;
6 import java.awt.image.BufferedImage;
7 import java.io.IOException;
8 import java.io.OutputStream;
9 import java.util.Random;
10 import javax.imageio.ImageIO;
11
12 /**
13 * @author dzy 生成验证码图片
14 */
15 public class makeCertPic {
16 // 验证码图片中可以出现的字符集,可根据需要修改
17 private char mapTable[] = { ' a ' , ' b ' , ' c ' , ' d ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' ,
18 ' j ' , ' k ' , ' l ' , ' m ' , ' n ' , ' o ' , ' p ' , ' q ' , ' r ' , ' s ' , ' t ' , ' u ' , ' v ' ,
19 ' w ' , ' x ' , ' y ' , ' z ' , ' 0 ' , ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' ,
20 ' 9 ' };
21
22 /**
23 * 功能:生成彩色验证码图片 参数width为生成的图片的宽度,参数height为生成的图片的高度,参数os为页面的输出流
24 */
25 public String getCertPic( int width, int height, OutputStream os) {
26 if (width <= 0 )
27 width = 60 ;
28 if (height <= 0 )
29 height = 20 ;
30 BufferedImage image = new BufferedImage(width, height,
31 BufferedImage.TYPE_INT_RGB);
32 // 获取图形上下文
33 Graphics g = image.getGraphics();
34 // 设定背景色
35 g.setColor( new Color( 0xDCDCDC ));
36 g.fillRect( 0 , 0 , width, height);
37 // 画边框
38 g.setColor(Color.black);
39 g.drawRect( 0 , 0 , width - 1 , height - 1 );
40 // 取随机产生的认证码
41 String strEnsure = "" ;
42 // 4代表4位验证码,如果要生成更多位的认证码,则加大数值
43 for ( int i = 0 ; i < 4 ; ++ i) {
44 strEnsure += mapTable[( int ) (mapTable.length * Math.random())];
45 }
46 // 将认证码显示到图象中,如果要生成更多位的认证码,增加drawString语句
47 g.setColor(Color.black);
48 g.setFont( new Font( " Atlantic Inline " , Font.PLAIN, 18 ));
49 String str = strEnsure.substring( 0 , 1 );
50 g.drawString(str, 8 , 17 );
51 str = strEnsure.substring( 1 , 2 );
52 g.drawString(str, 20 , 15 );
53 str = strEnsure.substring( 2 , 3 );
54 g.drawString(str, 35 , 18 );
55 str = strEnsure.substring( 3 , 4 );
56 g.drawString(str, 45 , 15 );
57 // 随机产生10个干扰点
58 Random rand = new Random();
59 for ( int i = 0 ; i < 10 ; i ++ ) {
60 int x = rand.nextInt(width);
61 int y = rand.nextInt(height);
62 g.drawOval(x, y, 1 , 1 );
63 }
64 // 释放图形上下文
65 g.dispose();
66 try {
67 // 输出图象到页面
68 ImageIO.write(image, " JPEG " , os);
69 } catch (IOException e) {
70 return "" ;
71 }
72 return strEnsure;
73 }
74 }
75
6。com.he.servlet里的LoginServlet.java,作用是验证登录。
1
package
com.he.servlet;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.security.MessageDigest;
6
7 import javax.servlet.ServletException;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import javax.servlet.http.HttpSession;
12
13 import com.he.manager.Manager;
14
15 public class LoginServlet extends HttpServlet {
16 public void doGet(HttpServletRequest request, HttpServletResponse response)
17 throws ServletException, IOException {
18 PrintWriter out = response.getWriter();
19 String name = (String) request.getParameter( " name " );
20 name = name.trim(); // 去掉字符串首尾空格
21 String pwd = (String) request.getParameter( " pwd " );
22 pwd = pwd.trim();
23 boolean Check = Manager.CheckForm(name, pwd); // 验证输入的帐号密码是否符合规则
24 System.out.println(Check);
25 if (Check) {
26 // 将密码转为MD5加密
27 try {
28 // -------生成MessageDigest对象MD-------
29 MessageDigest MD = MessageDigest.getInstance( " MD5 " );
30 // --------传入要计算的字符---------------
31 MD.update(pwd.getBytes( " UTF8 " ));
32 // --------计算信息摘要----------------
33 byte [] pwdMD5Byte = MD.digest();
34 pwd = new String(pwdMD5Byte);
35 } catch (Exception e) {
36 e.printStackTrace();
37 }
38 String certCode = request.getParameter( " certCode " );
39 // 查看输入的帐号密码是否在数据库里有记录
40 boolean tag = Manager.CheckAccount(name, pwd);
41 // 执行输出操作(弹出成功的对话框)
42 response.setCharacterEncoding( " gbk " ); // 解决中文显示问题
43 HttpSession session = request.getSession();
44 if (certCode.equals((String) session.getAttribute( " certCode " ))) {
45 if (tag) {
46 session.setAttribute( " name " , name); // 验证成功的话设置session
47 out
48 .print( " <script language=javascript>alert('Login Succeed!!');window.location.href='SucceedLogin.jsp';</script> " );
49 } else {
50 out
51 .print( " <script language=javascript>alert('account or password error!!');window.location.href='index.jsp';</script> " );
52 }
53 } else {
54 out
55 .print( " <script language=javascript>alert('certCode error!!');window.location.href='index.jsp';</script> " );
56 }
57 } else {
58 out
59 .print( " <script language=javascript>alert('rule error!!');window.location.href='index.jsp';</script> " );
60 }
61 }
62
63 public void doPost(HttpServletRequest request, HttpServletResponse response)
64 throws ServletException, IOException {
65 doGet(request, response);
66 }
67
68 }
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.security.MessageDigest;
6
7 import javax.servlet.ServletException;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import javax.servlet.http.HttpSession;
12
13 import com.he.manager.Manager;
14
15 public class LoginServlet extends HttpServlet {
16 public void doGet(HttpServletRequest request, HttpServletResponse response)
17 throws ServletException, IOException {
18 PrintWriter out = response.getWriter();
19 String name = (String) request.getParameter( " name " );
20 name = name.trim(); // 去掉字符串首尾空格
21 String pwd = (String) request.getParameter( " pwd " );
22 pwd = pwd.trim();
23 boolean Check = Manager.CheckForm(name, pwd); // 验证输入的帐号密码是否符合规则
24 System.out.println(Check);
25 if (Check) {
26 // 将密码转为MD5加密
27 try {
28 // -------生成MessageDigest对象MD-------
29 MessageDigest MD = MessageDigest.getInstance( " MD5 " );
30 // --------传入要计算的字符---------------
31 MD.update(pwd.getBytes( " UTF8 " ));
32 // --------计算信息摘要----------------
33 byte [] pwdMD5Byte = MD.digest();
34 pwd = new String(pwdMD5Byte);
35 } catch (Exception e) {
36 e.printStackTrace();
37 }
38 String certCode = request.getParameter( " certCode " );
39 // 查看输入的帐号密码是否在数据库里有记录
40 boolean tag = Manager.CheckAccount(name, pwd);
41 // 执行输出操作(弹出成功的对话框)
42 response.setCharacterEncoding( " gbk " ); // 解决中文显示问题
43 HttpSession session = request.getSession();
44 if (certCode.equals((String) session.getAttribute( " certCode " ))) {
45 if (tag) {
46 session.setAttribute( " name " , name); // 验证成功的话设置session
47 out
48 .print( " <script language=javascript>alert('Login Succeed!!');window.location.href='SucceedLogin.jsp';</script> " );
49 } else {
50 out
51 .print( " <script language=javascript>alert('account or password error!!');window.location.href='index.jsp';</script> " );
52 }
53 } else {
54 out
55 .print( " <script language=javascript>alert('certCode error!!');window.location.href='index.jsp';</script> " );
56 }
57 } else {
58 out
59 .print( " <script language=javascript>alert('rule error!!');window.location.href='index.jsp';</script> " );
60 }
61 }
62
63 public void doPost(HttpServletRequest request, HttpServletResponse response)
64 throws ServletException, IOException {
65 doGet(request, response);
66 }
67
68 }
7。com.he.servlet里的Registe.java作用是进行注册操作。
1
package
com.he.servlet;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.util.Date;
6 import java.security.MessageDigest;
7 import java.text.SimpleDateFormat;
8
9 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14
15 import com.he.manager.Manager;
16 import com.he.pojo.Account;
17
18 public class RegisteServlet extends HttpServlet {
19 public void doGet(HttpServletRequest request, HttpServletResponse response)
20 throws ServletException, IOException {
21 Date currTime = new Date(); // 添加帐号的时间
22 SimpleDateFormat formatter = new SimpleDateFormat( " yyyy-MM-dd " );
23 String time = new String(formatter.format(currTime).getBytes(
24 " iso-8859-1 " )); // 时间格式化
25 String name = (String) request.getParameter( " name " );
26 name = name.trim(); // 去除字符串首尾空格
27 String pwd = (String) request.getParameter( " pwd " );
28 pwd = pwd.trim();
29 boolean Check = Manager.CheckForm(name, pwd); // 验证输入的帐号密码是否符合规则
30 System.out.println(Check);
31 if (Check) {
32 // 在写入数据库之前将密码转为MD5加密
33 try {
34 // -------生成MessageDigest对象MD-------
35 MessageDigest MD = MessageDigest.getInstance( " MD5 " );
36 // --------传入要计算的字符---------------
37 MD.update(pwd.getBytes( " UTF8 " ));
38 // --------计算信息摘要----------------
39 byte [] pwdMD5Byte = MD.digest();
40 pwd = new String(pwdMD5Byte);
41 } catch (Exception e) {
42 e.printStackTrace();
43 }
44 boolean tag = Manager.HasAccount(name); // 查看数据库里有没相同的用户名记录
45 if (tag) {
46 response.setCharacterEncoding( " gbk " ); // 解决中文显示问题
47 PrintWriter out = response.getWriter();
48 out
49 .print( " <script language=javascript>alert('用户名已被占用');window.location.href='registe.jsp';</script> " );
50 } else {
51 // new 一个Account对象,并将表单传过来的值填充它
52 Account account = new Account();
53 account.setName(request.getParameter( " name " ));
54 account.setPwd(pwd);
55 account.setAddtime(time);
56 // 执行持久化操作,保存到数据库
57 Manager manager = new Manager();
58 manager.addAccount(account);
59 // 执行输出操作(弹出成功的对话框)
60 response.setCharacterEncoding( " gbk " ); // 解决中文显示问题
61 HttpSession session = request.getSession();
62 session.setAttribute( " name " , request.getParameter( " name " ));
63 PrintWriter out = response.getWriter();
64 out
65 .print( " <script language=javascript>alert('注册成功!');window.location.href='SucceedLogin.jsp';</script> " );
66 }
67 } else {
68 response.setCharacterEncoding( " gbk " ); // 解决中文显示问题
69 PrintWriter out = response.getWriter();
70 out
71 .print( " <script language=javascript>alert('帐号或密码必须是四到八位的数字或字母!!');window.location.href='registe.jsp';</script> " );
72 }
73 }
74
75 public void doPost(HttpServletRequest request, HttpServletResponse response)
76 throws ServletException, IOException {
77 doGet(request, response);
78 }
79
80 }
81
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.util.Date;
6 import java.security.MessageDigest;
7 import java.text.SimpleDateFormat;
8
9 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14
15 import com.he.manager.Manager;
16 import com.he.pojo.Account;
17
18 public class RegisteServlet extends HttpServlet {
19 public void doGet(HttpServletRequest request, HttpServletResponse response)
20 throws ServletException, IOException {
21 Date currTime = new Date(); // 添加帐号的时间
22 SimpleDateFormat formatter = new SimpleDateFormat( " yyyy-MM-dd " );
23 String time = new String(formatter.format(currTime).getBytes(
24 " iso-8859-1 " )); // 时间格式化
25 String name = (String) request.getParameter( " name " );
26 name = name.trim(); // 去除字符串首尾空格
27 String pwd = (String) request.getParameter( " pwd " );
28 pwd = pwd.trim();
29 boolean Check = Manager.CheckForm(name, pwd); // 验证输入的帐号密码是否符合规则
30 System.out.println(Check);
31 if (Check) {
32 // 在写入数据库之前将密码转为MD5加密
33 try {
34 // -------生成MessageDigest对象MD-------
35 MessageDigest MD = MessageDigest.getInstance( " MD5 " );
36 // --------传入要计算的字符---------------
37 MD.update(pwd.getBytes( " UTF8 " ));
38 // --------计算信息摘要----------------
39 byte [] pwdMD5Byte = MD.digest();
40 pwd = new String(pwdMD5Byte);
41 } catch (Exception e) {
42 e.printStackTrace();
43 }
44 boolean tag = Manager.HasAccount(name); // 查看数据库里有没相同的用户名记录
45 if (tag) {
46 response.setCharacterEncoding( " gbk " ); // 解决中文显示问题
47 PrintWriter out = response.getWriter();
48 out
49 .print( " <script language=javascript>alert('用户名已被占用');window.location.href='registe.jsp';</script> " );
50 } else {
51 // new 一个Account对象,并将表单传过来的值填充它
52 Account account = new Account();
53 account.setName(request.getParameter( " name " ));
54 account.setPwd(pwd);
55 account.setAddtime(time);
56 // 执行持久化操作,保存到数据库
57 Manager manager = new Manager();
58 manager.addAccount(account);
59 // 执行输出操作(弹出成功的对话框)
60 response.setCharacterEncoding( " gbk " ); // 解决中文显示问题
61 HttpSession session = request.getSession();
62 session.setAttribute( " name " , request.getParameter( " name " ));
63 PrintWriter out = response.getWriter();
64 out
65 .print( " <script language=javascript>alert('注册成功!');window.location.href='SucceedLogin.jsp';</script> " );
66 }
67 } else {
68 response.setCharacterEncoding( " gbk " ); // 解决中文显示问题
69 PrintWriter out = response.getWriter();
70 out
71 .print( " <script language=javascript>alert('帐号或密码必须是四到八位的数字或字母!!');window.location.href='registe.jsp';</script> " );
72 }
73 }
74
75 public void doPost(HttpServletRequest request, HttpServletResponse response)
76 throws ServletException, IOException {
77 doGet(request, response);
78 }
79
80 }
81
8。index.jsp,登录界面。
<%
@ page language
=
"
java
"
import
=
"
java.util.*
"
pageEncoding
=
"
gbk
"
%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + " :// " + request.getServerName() + " : " + request.getServerPort() + path + " / " ;
%>
<! DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " >
< html >
< head >
< base href = " <%=basePath%> " >
< title > My JSP ' index.jsp ' starting page </ title >
< meta http - equiv = " pragma " content = " no-cache " >
< meta http - equiv = " cache-control " content = " no-cache " >
< meta http - equiv = " expires " content = " 0 " >
< meta http - equiv = " keywords " content = " keyword1,keyword2,keyword3 " >
< meta http - equiv = " description " content = " This is my page " >
<!--
< link rel = " stylesheet " type = " text/css " href = " styles.css " >
-->
</ head >
< script language = " JavaScript " >
function check()
{
if ( form.name.value == "" )
{
alert( " \请输入您的用户名!! " )
form.name.focus();
return false ;
}
if ( form.pwd.value == "" )
{
alert( " \请输入您的登陆密码!! " )
form.pwd.focus();
return false ;
}
return true ;
}
</ script >
< body >
< h1 > 用户登录 </ h1 >
< form name = " form " id = " form " onSubmit = " return check() " method = " post " action = " LoginServlet " >
< p > 帐 & nbsp; & nbsp;号: < input type = " text " name = " name " /></ p >
< p > 密 & nbsp; & nbsp;码: < input type = " password " name = " pwd " /></ p >
< P > 验证码: < input type = " text " name = " certCode " />< img src = " makeCertPic.jsp " /></ P >
< p >< input type = " submit " name = " submit " value = " 登录 " >
< input type = " button " onClick = " location='registe.jsp' " value = " 注册 " class = " btn " />
</ p >
</ form >
</ body >
</ html >
<%
String path = request.getContextPath();
String basePath = request.getScheme() + " :// " + request.getServerName() + " : " + request.getServerPort() + path + " / " ;
%>
<! DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " >
< html >
< head >
< base href = " <%=basePath%> " >
< title > My JSP ' index.jsp ' starting page </ title >
< meta http - equiv = " pragma " content = " no-cache " >
< meta http - equiv = " cache-control " content = " no-cache " >
< meta http - equiv = " expires " content = " 0 " >
< meta http - equiv = " keywords " content = " keyword1,keyword2,keyword3 " >
< meta http - equiv = " description " content = " This is my page " >
<!--
< link rel = " stylesheet " type = " text/css " href = " styles.css " >
-->
</ head >
< script language = " JavaScript " >
function check()
{
if ( form.name.value == "" )
{
alert( " \请输入您的用户名!! " )
form.name.focus();
return false ;
}
if ( form.pwd.value == "" )
{
alert( " \请输入您的登陆密码!! " )
form.pwd.focus();
return false ;
}
return true ;
}
</ script >
< body >
< h1 > 用户登录 </ h1 >
< form name = " form " id = " form " onSubmit = " return check() " method = " post " action = " LoginServlet " >
< p > 帐 & nbsp; & nbsp;号: < input type = " text " name = " name " /></ p >
< p > 密 & nbsp; & nbsp;码: < input type = " password " name = " pwd " /></ p >
< P > 验证码: < input type = " text " name = " certCode " />< img src = " makeCertPic.jsp " /></ P >
< p >< input type = " submit " name = " submit " value = " 登录 " >
< input type = " button " onClick = " location='registe.jsp' " value = " 注册 " class = " btn " />
</ p >
</ form >
</ body >
</ html >
9。registe.jsp,注册界面
<%
@ page language
=
"
java
"
import
=
"
java.util.*
"
pageEncoding
=
"
gbk
"
%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + " :// " + request.getServerName() + " : " + request.getServerPort() + path + " / " ;
%>
<! DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " >
< html >
< head >
< base href = " <%=basePath%> " >
< title > 注册 </ title >
<!--
< link rel = " stylesheet " type = " text/css " href = " styles.css " >
-->
</ head >
< script language = " JavaScript " >
function check()
{
if ( form.name.value == "" )
{
alert( " \请输入您的用户名!! " )
form.name.focus();
return false ;
}
if ( form.pwd.value == "" )
{
alert( " \请输入您的登陆密码!! " )
form.pwd.focus();
return false ;
}
if (form.repwd.value == "" )
{
alert( " \请输入您的第二次密码!! " )
form.repwd.focus();
return false ;
}
if (form.pwd.value != form.repwd.value)
{
alert( " \两次输入的密码不一致!! " )
form.repwd.focus();
return false ;
}
return true ;
}
</ script >
< body >
< h1 > 注册 </ h1 >
< form name = " form " id = " form " onSubmit = " return check() " method = " post " action = " RegisteServlet " >
< p > 帐号: < input name = " name " type = " text " /></ p >
< P > 密码: < input name = " pwd " type = " password " /></ P >
< p > 再次输入密码: < input name = " repwd " type = " password " ></ p >
< p >< input type = " submit " value = " 注册 " /> < input type = " reset " value = " 重置 " /></ p >
</ form >
</ body >
</ html >
<%
String path = request.getContextPath();
String basePath = request.getScheme() + " :// " + request.getServerName() + " : " + request.getServerPort() + path + " / " ;
%>
<! DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " >
< html >
< head >
< base href = " <%=basePath%> " >
< title > 注册 </ title >
<!--
< link rel = " stylesheet " type = " text/css " href = " styles.css " >
-->
</ head >
< script language = " JavaScript " >
function check()
{
if ( form.name.value == "" )
{
alert( " \请输入您的用户名!! " )
form.name.focus();
return false ;
}
if ( form.pwd.value == "" )
{
alert( " \请输入您的登陆密码!! " )
form.pwd.focus();
return false ;
}
if (form.repwd.value == "" )
{
alert( " \请输入您的第二次密码!! " )
form.repwd.focus();
return false ;
}
if (form.pwd.value != form.repwd.value)
{
alert( " \两次输入的密码不一致!! " )
form.repwd.focus();
return false ;
}
return true ;
}
</ script >
< body >
< h1 > 注册 </ h1 >
< form name = " form " id = " form " onSubmit = " return check() " method = " post " action = " RegisteServlet " >
< p > 帐号: < input name = " name " type = " text " /></ p >
< P > 密码: < input name = " pwd " type = " password " /></ P >
< p > 再次输入密码: < input name = " repwd " type = " password " ></ p >
< p >< input type = " submit " value = " 注册 " /> < input type = " reset " value = " 重置 " /></ p >
</ form >
</ body >
</ html >
10。makeCertpic.jsp 验证码图片的
<%
@page contentType
=
"
image/jpeg
"
pageEncoding
=
"
gbk
"
%>
< jsp:useBean id = " image " scope = " page " class = " com.he.bean.makeCertPic " />
<%
String str = image.getCertPic( 0 , 0 ,response.getOutputStream());
// 避免getWriter()和responsegetOutputStream()冲突而产生异常
out.clear();
out = pageContext.pushBody();
// CREATE SESSION
session.setAttribute( " certCode " , str);
%>
< jsp:useBean id = " image " scope = " page " class = " com.he.bean.makeCertPic " />
<%
String str = image.getCertPic( 0 , 0 ,response.getOutputStream());
// 避免getWriter()和responsegetOutputStream()冲突而产生异常
out.clear();
out = pageContext.pushBody();
// CREATE SESSION
session.setAttribute( " certCode " , str);
%>
11.SucceedLogin.jsp 登录成功的页面
1
<%
@ page language
=
"
java
"
import
=
"
java.util.*
"
pageEncoding
=
"
gbk
"
%>
2 <% @ include file = " CheckLogin.jsp " %>
3 <%
4 String path = request.getContextPath();
5 String basePath = request.getScheme() + " :// " + request.getServerName() + " : " + request.getServerPort() + path + " / " ;
6 %>
7
8 <! DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " >
9 < html >
10 < head >
11 < base href = " <%=basePath%> " >
12
13 < title > SucceedLogin </ title >
14
15 < meta http - equiv = " pragma " content = " no-cache " >
16 < meta http - equiv = " cache-control " content = " no-cache " >
17 < meta http - equiv = " expires " content = " 0 " >
18 < meta http - equiv = " keywords " content = " keyword1,keyword2,keyword3 " >
19 < meta http - equiv = " description " content = " This is my page " >
20 <!--
21 < link rel = " stylesheet " type = " text/css " href = " styles.css " >
22 -->
23
24 </ head >
25
26 < body >
27 < h1 > 欢迎您 </ h1 >
28 ${sessionScope.name}
29 </ body >
30 </ html >
31
2 <% @ include file = " CheckLogin.jsp " %>
3 <%
4 String path = request.getContextPath();
5 String basePath = request.getScheme() + " :// " + request.getServerName() + " : " + request.getServerPort() + path + " / " ;
6 %>
7
8 <! DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " >
9 < html >
10 < head >
11 < base href = " <%=basePath%> " >
12
13 < title > SucceedLogin </ title >
14
15 < meta http - equiv = " pragma " content = " no-cache " >
16 < meta http - equiv = " cache-control " content = " no-cache " >
17 < meta http - equiv = " expires " content = " 0 " >
18 < meta http - equiv = " keywords " content = " keyword1,keyword2,keyword3 " >
19 < meta http - equiv = " description " content = " This is my page " >
20 <!--
21 < link rel = " stylesheet " type = " text/css " href = " styles.css " >
22 -->
23
24 </ head >
25
26 < body >
27 < h1 > 欢迎您 </ h1 >
28 ${sessionScope.name}
29 </ body >
30 </ html >
31
12。CheckLogin.jsp 进行未登录就进入登录成功的界面的验证
1
2 <%
3 if (session.getAttribute( " name " ) == null
4 || session.getAttribute( " name " ).toString().length() == 0 ) {
5 response.sendRedirect(request.getContextPath() + " /error.jsp " );
6 }
7 %>
2 <%
3 if (session.getAttribute( " name " ) == null
4 || session.getAttribute( " name " ).toString().length() == 0 ) {
5 response.sendRedirect(request.getContextPath() + " /error.jsp " );
6 }
7 %>
13.web.xml文件
<?
xml version="1.0" encoding="UTF-8"
?>
< web-app version ="2.4"
xmlns ="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
< servlet >
< servlet-name > RegisteServlet </ servlet-name >
< servlet-class > com.he.servlet.RegisteServlet </ servlet-class >
</ servlet >
< servlet >
< servlet-name > LoginServlet </ servlet-name >
< servlet-class > com.he.servlet.LoginServlet </ servlet-class >
</ servlet >
< servlet-mapping >
< servlet-name > RegisteServlet </ servlet-name >
< url-pattern > /RegisteServlet </ url-pattern >
</ servlet-mapping >
< servlet-mapping >
< servlet-name > LoginServlet </ servlet-name >
< url-pattern > /LoginServlet </ url-pattern >
</ servlet-mapping >
< welcome-file-list >
< welcome-file > index.jsp </ welcome-file >
</ welcome-file-list >
</ web-app >
< web-app version ="2.4"
xmlns ="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
< servlet >
< servlet-name > RegisteServlet </ servlet-name >
< servlet-class > com.he.servlet.RegisteServlet </ servlet-class >
</ servlet >
< servlet >
< servlet-name > LoginServlet </ servlet-name >
< servlet-class > com.he.servlet.LoginServlet </ servlet-class >
</ servlet >
< servlet-mapping >
< servlet-name > RegisteServlet </ servlet-name >
< url-pattern > /RegisteServlet </ url-pattern >
</ servlet-mapping >
< servlet-mapping >
< servlet-name > LoginServlet </ servlet-name >
< url-pattern > /LoginServlet </ url-pattern >
</ servlet-mapping >
< welcome-file-list >
< welcome-file > index.jsp </ welcome-file >
</ welcome-file-list >
</ web-app >
14.到此,我的注册登录系统基本完成了。新人作品,希望大家批评指正。
此文为原创,如有转载请注明出处http://www.blogjava.net/gdhqs/。如有错误,请大家批评指正,谢谢!