建好web工程,导入Tomcat包 在src下建好包 在web工程目录下的WIN-INf目录的lib目录导入如下包
mysql-connector-java是用来连接数据库的
在web中准备好如下html文件
login.html是登录页面 login_success.html是登陆成功跳转页面 regist.html是注册页面 regist_success.html是注册成功的跳转页面
1.首先配置在src目录下配置jdbc,
配置代码
username=root
password=123456
url=jdbc:mysql://localhost:3306/book
diverClassName=com.mysql.cj.jdbc.Driver
initialSize=5
maxActive=10
2.连接数据库,以及测试,
在JdbcUtils目录下写代码,以及测试
package com.atguigu.utils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcUtils {
private static DruidDataSource dataSource;
static {
Properties properties = new Properties();
InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
properties.load(inputStream);
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
// System.out.println(dataSource.getConnection());
DruidPooledConnection connection = dataSource.getConnection();
// System.out.println(connection);//com.mysql.cj.jdbc.ConnectionImpl@dd8ba08
} catch (Exception e) {
e.printStackTrace();
}
}
//main方法作为为一个测试
public static void main(String[] args) {
System.out.println("yes");
}
public static Connection getConnection() {
//如果返回null,说明获取连接失败
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn){
if (conn != null){
try{
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3.在dao.impl目录下编写BaseDao.java类 主要功能:操作数据库
package com.atguigu.dao.impl;
import com.atguigu.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class BaseDao {
//使用DbUtils操作数据库
private QueryRunner queryRunner = new QueryRunner();
/**
* update() 方法用来执行:Insert\Update\Delete语句
*
* @return 如果返回-1,说明执行失败<br/>返回其他表示影响的行数
*/
public int update(String sql, Object... args) {
Connection connection = JdbcUtils.getConnection();
try {
return queryRunner.update(connection,sql,args);
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.close(connection);
}
//如果返回-1,说明执行失败
return -1;
}
/*
* param type 返回对象的类型
* param sql 执行的sql语句
* args sql 对应的参数值
* param<T> 返回的类型的泛型
* */
public <T> T queryForOne(Class<T> type, String sql,Object...args){
Connection con = JdbcUtils.getConnection();
try {
return queryRunner.query(con, sql, new BeanHandler<T>(type), args);
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtils.close(con);
}
return null;
}
//查询返回列表
public <T> List <T> queryForList(Class<T> type, String sql, Object...args){
Connection con = JdbcUtils.getConnection();
try {
return (List<T>) queryRunner.query(con, sql, new BeanHandler<T>(type), args);
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtils.close(con);
}
return null;
}
//查询返回单个值
public Object queryForSingleValue(String sql,Object...args){
Connection conn = JdbcUtils.getConnection();
try {
queryRunner.query(conn,sql,new ScalarHandler(),args);
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.close(conn);
}
return null;
}
}
4.在dao.impl目录下定义一个接口UserDao,,再通过类对其功能具体化 主要功能:查询用户信息
public interface UserDao {
/*
* 根据用户名查询用户信息
* @param username 用户名
* @ return 如果返回null,就说明没有这个用户名
* */
public User queryUsername(String username);
/*
* 根据用户名查询用户信息
* @param username 用户名
* @param password 密码
* @ return 如果返回null,就说明用户名或密码错误
*
* */
public User queryByUsernameAndPassword(String username,String password);
/*
* 保存用户信息
* param user
* return -1,表示操作失败,
* */
public int saveUser(User user);
}
在service.impl目录下定义一个UserServiceimpl类来实现UserService接口 接口的主要功能:实现注册,以及登录验证
public interface UserService {
/*
* 注册用户
* @param user
*
* */
public void registUser(User user);
/*
* 登录
*@param user
*@return 如果返回null,说明登陆失败,返回有值,登陆成功
*
*
* */
public User login(User user);
/*
* 检查 用户名是否可用
* @param username
* @return 返回true表示用户名已经存在,返回false表示用户名可用
*
* */
public boolean existsUsername(String username);
}
LoginServlet代码实现登录功能
//调用UserService,验证账号和密码是否正确
//调用UserService,验证账号和密码是否正确
UserService userService = new UserServiceimpl();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("login访问成功");
String username = req.getParameter("username");
String password = req.getParameter("password");
User loginUser = userService.login(new User(null,username,password,null));
if(loginUser != null){
System.out.println("用户名登陆成功");
//登陆成功,跳到用户页面
req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
}else{
System.out.println("用户名或密码错误");
req.setAttribute("msg","用户名或密码错误");
req.setAttribute("username",username);
//登陆失败,跳回登录页面
req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
}
}
RegistServlet类实现注册功能
//调用UserService,为了验证是否用户名已经存在
UserService userService = new UserServiceimpl();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取请求参数
System.out.println("RegistServlet访问成功");
String username = req.getParameter("username");
String password = req.getParameter("password");
String repwd = req.getParameter("repwd");
String email = req.getParameter("email");
String code = req.getParameter("code");
//2.检查 验证码是否正确 === 写死,验证码为 abcde
if ("abcde".equalsIgnoreCase(code)) {
//3.检查 用户名是否可用
if (userService.existsUsername(username)) {
// 不可用
// 跳回注册页面
System.out.println("用户名" + username + "已存在");
req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
} else {
// 可用,
// 调用Service保存到数据库中
//跳转到注册页面regist_seccess.html
System.out.println("用户名可用");
userService.registUser(new User(null,username,password,email));
req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
}
} else {
//不正确
// 跳回注册页面
System.out.println("验证【" + code + "】码错误,");
req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
}
}