功能描述:使用JSP和JavaBean完成用户登录功能
代码结构框架图
DBUtil
package model;
import java.sql.*;
//DBUtil封装对数据库连接操作
//工具类,jdbc中专门用来写公共代码,就比如说连接数据库
public class DBUtil {
//写成静态的,其他的方法不能进行修改
//驱动的位置
private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
//数据库连接URL,不同版本的mysql这里可能有所不同, 其中的demo是你要连接的数据库的名字
private static final String URL = "jdbc:mysql://127.0.0.1:3306/demo?useSSL=false";
//这里的账户和密码,因人而异
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
//获取数据库连接
public static Connection getConnection() throws Exception{
//加载驱动
Class.forName(DRIVER_CLASS);
//获取数据库连接
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
//返回连接
return connection;
}
//关闭数据库连接
public static void closeConnection(Connection connection) throws Exception{
if(connection != null){
connection.close();
}
}
//关闭执行对象Statement
public static void closeStatement(Statement statement) throws Exception{
if(statement != null){
statement.close();
}
}
//关闭执行对象PreparedStatement
public static void closePreparedStatement(PreparedStatement preparedStatement) throws Exception{
if(preparedStatement != null){
preparedStatement.close();
}
}
//关闭结果集
public static void closeResultSet(ResultSet resultSet) throws Exception{
if(resultSet != null){
resultSet.close();
}
}
//测试一下
// public static void main(String[] args) {
// try{
// Connection connection = getConnection();
// closeConnection(connection);
// }catch (Exception e){
// e.printStackTrace();
// }
// }
}
User
package model;
//JavaBean用于封装数据和业务逻辑
public class User {
private int id;
private String username;
private String password;
private String email;
private boolean admin;
private String loginMsg;
public User(){
}