Eclipse使用(七)—— 使用Eclipse创建JavaWeb项目并使用JDBC连接数据库实现简
发表时间:2018-1-2
发布人:葵宇科技
浏览次数:53
本项目继承于: Eclipse使用(六)—— 使用Eclipse创建JavaWeb项目
一、创建数据库表(这里使用的是Mysql5.7)
DDL语句如下:
CREATE TABLE `tb_user` (
`u_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户编号',
`u_username` varchar(30) NOT NULL COMMENT '用户名',
`u_password` varchar(30) NOT NULL COMMENT '密码',
PRIMARY KEY (`u_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
请注意:我个表使用了自增主键,所以注册时使用的sql没有u_id的参数,如果没有添加自增主键的,请务必在sql中添加u_id
二、项目需要使用的jar示例
三、编写持久层和业务层代码
项目src目录结构预览:
1、在src目录下创建com.mengfei.entity包,并在包中创建实体类User
package com.mengfei.entity;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private Integer uid;
private String username;
private String password;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
2、在com.mengfei包中创建dao包,并在包中创建类BaseDao
package com.mengfei.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
protected Connection conn;
protected PreparedStatement ps;
protected ResultSet rs;
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
//请注意:如果使用的jdbc版本或mysql数据库版本过高,比如8.0以上版本的,请在url后面加一个时区参数
//如:jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=GMT%2B8
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?useSSL=false", "alex", "123");
//Class.forName("oracle.jdbc.driver.OracleDriver");
//conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "alex", "123");
/**
* com.mysql.jdbc.Driver是创建连接的驱动类,Oracle使用的是oracle.jdbc.driver.OracleDriver
* jdbc:mysql://localhost:3306/demo?useSSL=false是要连接的url地址,Oracle使用的是jdbc:oracle:thin:@localhost:1521:orcl
* localhost代表本地连接,如果使用远程连接则要改成IP地址
* demo是要连接的mysql中数据库的名字,Oracle中用的是实例orcl
* ?useSSL=false是参数,不写也能连接,Oracle中不需要
* alex是要连接的用户名
* 123是用户的密码
*/
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public void closeDB(ResultSet rs, PreparedStatement ps, Connection conn) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 测试是否连接上数据库
public static void main(String[] args) {
BaseDao dao = new BaseDao();
System.out.println(dao.getConnection());
}
}
3、在com.mengfei.dao包中创建接口UserDao
package com.mengfei.dao;
import com.mengfei.entity.User;
public interface UserDao {
/**
* 用户注册
* @param user
* @return
*/
Integer register(User user);
/**
* 用户登陆
* @param user
* @return
*/
User login(User user);
}
4、在com.mengfei.dao包中创建impl包,并在包中创建类UserDaoImpl,该类继承BaseDao,实现UserDao
package com.mengfei.dao.impl;
import java.sql.SQLException;
import com.mengfei.dao.BaseDao;
import com.mengfei.dao.UserDao;
import com.mengfei.entity.User;
public class UserDaoImpl extends BaseDao implements UserDao {
@Override
public Integer register(User user) {
int row = 0;
conn = getConnection();
String sql = "insert into tb_user(u_username,u_password) values(?,?)";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
row = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeDB(rs, ps, conn);
}
return row;
}
@Override
public User login(User user) {
User u=null;
conn=getConnection();
String sql="select * from tb_user where u_username=? and u_password=?";
try {
ps=conn.prepareStatement(sql);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
rs = ps.executeQuery();
while(rs.next()){
u=new User();
u.setUid(rs.getInt(1));
u.setUsername(rs.getString(2));
u.setPassword(rs.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
closeDB(rs, ps, conn);
}
return u;
}
}
5、在com.mengfei包中创建biz包,并在包中创建接口UserBiz
package com.mengfei.biz;
import com.mengfei.entity.User;
public interface UserBiz {
/**
* 用户注册
* @param username
* @param password
* @return
*/
Boolean register(String username, String password);
/**
* 用户登陆
* @param username
* @param password
* @return
*/
User login(String username, String password);
}
6、在com.mengfei.biz包中创建impl包,并在包中创建类UserBizImpl实现UserBiz
package com.mengfei.biz.impl;
import com.mengfei.biz.UserBiz;
import com.mengfei.dao.UserDao;
import com.mengfei.dao.impl.UserDaoImpl;
import com.mengfei.entity.User;
public class UserBizImpl implements UserBiz {
private UserDao userDao = new UserDaoImpl();
@Override
public Boolean register(String username, String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
Integer result = userDao.register(user);
if (result > 0) {
return true;
}
return false;
}
@Override
public User login(String username, String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
User u = userDao.login(user);
return u;
}
}
7、在com.mengfei包中创建servlet包,并在包中创建UserServlet
package com.mengfei.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mengfei.biz.UserBiz;
import com.mengfei.biz.impl.UserBizImpl;
import com.mengfei.entity.User;
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
UserBiz userBiz=new UserBizImpl();
String username = request.getParameter("username");
String password = request.getParameter("password");
String operate = request.getParameter("operate");
if(null == username || null == password || null == operate) {
response.sendRedirect("index.jsp");
}
switch(operate) {
case "register" :
Boolean b = userBiz.register(username, password);
if(b) {
request.getRequestDispatcher("success.jsp").forward(request, response);
}else {
response.sendRedirect("index.jsp");
}
break;
case "login" :
User user = userBiz.login(username, password);
if(null!=user) {
request.setAttribute("username", user.getUsername());
request.getRequestDispatcher("success.jsp").forward(request, response);
}else {
response.sendRedirect("index.jsp");
}
break;
default:
response.sendRedirect("index.jsp");
break;
}
}
}
四、编写表现层代码(web.xml文件暂时不用管它)
1、在WebContent目录中创建js目录,将jquery-3.2.1.js文件放进去
请注意:如果jquery版本不一致的要记得修改版本号
2、编写index.jsp(放在WebContext目录下)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="js/jquery-3.2.1.js"></script>
</head>
<body>
<form id="form" action="UserServlet" method="post"><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:if test="${empty username}">
注册成功!
</c:if>
<c:if test="${!empty username}">
登陆成功!欢迎 ${username} !
</c:if>
</body>
</html>
五、部署测试
1、右键点击本地server将项目添加到Tomcat中
2、启动Tomcat,在浏览器中输入localhost:8080/JDBCJavaWebDemo/index.jsp,显示如下图:
OK,到这里就可以自己进行注册和登陆测试啦