开发环境:

Eclipse3.2

myeclipse5.0

mysql5.0

tomcat6.0


 

 

业务流程:

 

用户访问的第一个网页login.jsp。

输入用户名和密码,如果用户名和密码正确,转到main.jsp页面。

如果登陆失败,转到register.jsp页面。


 

 

数据库设计

/*
SQLyog 企业版 - MySQL GUI v5.02
主机 - 5.0.22-community-nt : 数据库 - user
*********************************************************************
服务器版本 : 5.0.22-community-nt
*/

create database if not exists `user`;

USE `user`;

/*数据表 `userinfo` 的表结构*/

DROP TABLE IF EXISTS `userinfo`;

CREATE TABLE `userinfo` (
  `id` int(11) NOT NULL auto_increment,
  `userName` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

/*数据表 `userinfo` 的数据*/

insert into `userinfo` values

(1,'anzey','anzey'),

(2,'didiao','didiao');

 

 

将以上文件保存为my.sql使用SQLyog 导入即可。


 

视图组件设计。

打开Eclipse,新建一个“Tomcat Project”工程。工程名为“Login”。

在工程“login”新建三个页面,分别为"login.jsp","main.jsp","register.jsp"

内容如下:

login.jsp页面

<%@ page language="java" contentType="text/html; charset=GB2312"
    pageEncoding="GB2312"%>
<html>
    <head>
        <title>login.jsp</title>
        <meta http-equiv="Content-Type" content="text/html; charset=GB2312">
    </head>
    <body>
        <form method="post" action="loginservlet" >
            用户名:
            <input type="text" name="username">
            <br>
            密码:
            <input type="password" name="password">
            <br>
            <input type="submit" name="submit" value="提交">

        </form>
    </body>
</html>

 

main.jsp页面

<%@ page language="java" contentType="text/html; charset=GB2312"
    pageEncoding="gb2312"%>

<html>
    <head>
        <title>main.jsp</title>
        <meta http-equiv="Content-Type" content="text/html; charset=GB2312">
    </head>

    <body>
        <h1>
            <%=session.getAttribute("username")%>
            ,你登陆成功,现已进入主页!
        </h1>
    </body>
</html>

register.jsp页面

<%@ page language="java" contentType="text/html; charset=GB2312"
    pageEncoding="gb2312"%>
<html>
<head>
<title>注册页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
</head>
<body>
<h1>
<%=session.getAttribute("username") %>
你未能成功登陆,请注册你的信息!
</h1>

</body>
</html>

 


 

 

 

控制组件设计

在WEB/INF/src包文件夹中新建三个包"DBcon","Handle","Servlet",分别用于存放数据库连接组件“DBPool.java”,数据库业务处理组件“LoginHandler.java”和"loginservlet.java"。另外在这个目录下还有一个db.properties文件,用于保存数据库驱动名和用户名和密码。

DBPool.java代码如下

package DBcon;

import java.sql.*;
import java.io.*;
import java.util.*;

public class DBPool {
    private static DBPool instance = null;

    // 取得连接
    public static synchronized Connection getConnection() {
        if (instance == null) {
            instance = new DBPool();
        }
        return instance._getConnection();
    }

    private DBPool() {
        super();
    }

    private Connection _getConnection() {

            String sDBDriver = null;
            String sConnection = null;
            String sUser = null;
            String sPassword = null;

            Properties p = new Properties();
            InputStream is = getClass().getResourceAsStream("/db.properties");
            try {
            p.load(is);}catch(Exception Ex)
            {
                System.out.print("加载properties文件失败!\n");
            }

            sDBDriver = p.getProperty("DBDriver", sDBDriver);
            sConnection = p.getProperty("Connection", sConnection);

            sUser = p.getProperty("User", "");
            sPassword = p.getProperty("Password", "");
            Properties pr = new Properties();
            pr.put("user", sUser);
            pr.put("password", sPassword);
            pr.put("characterEncoding", "GB2312");
            pr.put("useUnicode", "TRUE");
            try {
            Class.forName(sDBDriver).newInstance();
            return DriverManager.getConnection(sConnection,pr);
        } catch (Exception Ex) {
            System.out.print("加载驱动失败或者创建数据库连接失败!\n");
            return null;

        }

    }

    public static void dbClose(Connection conn, PreparedStatement ps,
            ResultSet rs) throws SQLException {
        rs.close();
        ps.close();
        conn.close();

    }

}

LoginHandler.java代码如下:

package Handle;
import java.sql.*;
import java.util.*;

import DBcon.DBPool;

public class LoginHandle {
    public LoginHandle()
    {}
    Connection  conn;
    PreparedStatement ps;
    ResultSet rs;
    //检查是否已注册
    public boolean checkLogin(ArrayList arr)
    {//从数据库访问组建DBpool中取得连接
        conn=DBPool.getConnection();
        String name =(String)arr.get(0);
        String password=(String)arr.get(1);
        try
        {  
            String sql="select * from userinfo where username=? and password=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setString(2, password);
            rs=ps.executeQuery();
            if (rs.next())
            {
                DBPool.dbClose(conn,ps,rs);
                return true;
            }else{
                DBPool.dbClose(conn,ps,rs);
                return false;   
            }
        }catch(SQLException e)
        {
            return false;       
        }
    }

}

 

loginservlet.java代码如下

package Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import Handle.LoginHandle;

public class loginservlet extends HttpServlet {

    public loginservlet() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("gb2312");
        response.setCharacterEncoding("gb2312");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 生成一个Arraylist对象,并把用户名和密码的值
        ArrayList arr = new ArrayList();
        arr.add(username);
        arr.add(password);
        // 生成一个session对象
        HttpSession session = request.getSession(true);
        session.removeAttribute("username");
        session.setAttribute("username", username);
        // 调用模型组建loginHandler,检查该用户是否已注册
        LoginHandle login = new LoginHandle();
        boolean mark = login.checkLogin(arr);
        // 如果已注册,进入主页面
        if (mark)
            response.sendRedirect("main.jsp");
        else
            //如果没有注册
            response.sendRedirect("register.jsp");

    }

    public void init() throws ServletException {

    }
}

 

db.properties代码如下:

DBDriver=com.mysql.jdbc.Driver
Connection=jdbc:mysql://localhost:3306/user
User=root       //这个是我的mysql的用户名
Password=anzey              //这个是我的mysql的密码

 

 


 

 

部署和运行程序

在Eclipse中启动Tomcat。在浏览器地址栏中输入http://localhost:8080/Login/login.jsp.

posted on 2008-09-12 18:08  忘记  阅读(691)  评论(0编辑  收藏  举报