JSP+Servlet+JavaBean简单程序例子——用户名密码登陆,摘自《Tomcat&JavaWeb 技术手册》,亲测可用。

系统:Fedora19

IDE环境:MyEclipse10

1、建立Web Project,命名为Login_test。创建userLogn表:

create table userLogin(

user_name varchar(10) not null,

user_pwd varchar(10) not null,

constraint user_pk primary key (user_name)

);

 

2、添加 JavaBean文件,创建新类UserLoginBean,java

package login;
import java.sql.*;

public class UserLoginBean {
    private Connection con;   //数据库连接
    private ResultSet rs;     //结果集
    private Statement stmt;  
    private static final String DRIVER_NAME="com.mysql.jdbc.Driver";
    private static final String URL_STR="jdbc:mysql://localhost/test";
    //构造函数
    public UserLoginBean(){
        try{//加载驱动程序
            Class.forName(DRIVER_NAME);
            //获取数据库连接
            con=DriverManager.getConnection(URL_STR, "root", "jiangshan");    //自己的用户名和密码        
        }
        catch(SQLException se){
            se.printStackTrace();
        }
        catch(ClassNotFoundException cnfe){
            cnfe.printStackTrace();
        }
    }
    
    //业务方法
    public boolean login(String userName,String password)
    {
        boolean b = false;
        try{
            stmt=con.createStatement();
            String sql="SELECT user_pwd FROM userLogin Where user_name='"+userName+"'";
            rs=stmt.executeQuery(sql);
            while(rs.next()){
                String pwd= rs.getString(1);
                if(pwd.equals(password)){
                    b=true;
                }
            }
        }catch(SQLException se){
            se.printStackTrace();
            b=false;
        }finally{
            this.close(con,rs,stmt);   //下面定义close方法
        }
        return b;
    }
    //close方法用于关闭相应资源
    public void close(Connection con,ResultSet rs,Statement stmt){
        try{
            if(con!=null){
                con.close();
            }
            if(rs!=null){
                rs.close();
            }
            if(stmt!=null){
                stmt.close();
            }
        }
        catch(SQLException se){
            se.printStackTrace();
        }
    }
}
UserLoginBean.java

相关文章: