项目概况:
dao包:放数据库操作类UserDao.java;entity包:放实体类User.java;servlet包:放各项功能Servlet;util包:放一些工具类,工具类里有常用的方法。以及dbinfo.properties配置文件以键值对形式存放配置信息,方便后续维护。
数据库设计
users表,因为是练习的,所以这里就简单设计几个字段吧
实现用户注册
首先,写好数据库工具类DBUtils.java和用户实体类User.java,以及数据库操作类UserDao.java。由于UserDao类代码太多,所以按功能分开展示,重复的就不再展示了。
DBUtils:
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
/**
* 数据库连接工具类
*/
public class DBUtils {
private static String url;//数据库连接URL
private static String username;//数据库登录用户
private static String password;//数据库登录
private static String driverclass;//数据库驱动类
static{
//从properties文件获取数据库连接信息,这样便于维护和安全。
ResourceBundle rb = ResourceBundle.getBundle("dbinfo");
driverclass = rb.getString("driverclass");
url = rb.getString("url");
username = rb.getString("username");
password = rb.getString("password");
try {
Class.forName(driverclass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接方法
* @return Connection连接对象
* @throws Exception
*/
public static Connection getConnection() throws Exception {
return DriverManager.getConnection(url, username, password);
}
/**
* 完善的释放资源方法
* --若没有结果集,rs传递null即可。
* @param rs 结果集,ResultSet对象
* @param ps 执行SQL语句的PreparedStatement对象,使用父类Statement接收
* @param conn Connection连接对象
*/
public static void closeAll(ResultSet rs,Statement stmt,Connection conn) {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs=null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt=null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
User:
package entity;
/**
* 用户对象类(实体类)
*/
public class User {
//用户ID
private int userId ;
//用户名
private String userName;
//用户账号
private String userAccount;
//用户密码
private String userPassword;
//用户状态,在用户列表显示与否,用于删除用户,起到缓冲备份作用
private String userDisplay;
//记录删除时间,用于管理已删除用户
private String userDeleteTime = null;//默认为空
//get和set方法省略
}
下面就是JSP注册页面,userregister.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户注册界面</title>
<script language="javascript" type="text/javascript">
function check() {
if (document.form1.userName.value==""){
alert("请输入用户名!");
return false;
}
if (document.form1.userAccount.value==""){
alert("请输入用户账号!");
return false;
}
if (document.form1.userPassword.value==""){
alert("请输入用户密码");
return false;
}
if (document.form1.userPassword1.value==""){
alert("请输入确认密码!");
return false;
}
if (document.form1.userPassword.value!=document.form1.userPassword1.value){
alert("对不起!确认密码不等于登录密码");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form1" action="/UserManage/UserRegisterServlet" method="post">
<table align="center" border="1" style="border-collapse:collapse;">
<tr>
<td colspan="2" align="center">用户注册</td>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td>用户账户:</td>
<td><input type="text" name="userAccount"></td>
</tr>
<tr>
<td>用户密码:</td>
<td><input type="password" name="userPassword"></td>
</tr>
<tr>
<td>确认密码:</td>
<td><input type="password" name="userPassword1"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="确认添加" onclick="return check()">
<!-- <input type="submit" value="注册"> -->
</td>
</tr>
</table>
<table align="center">
<tr>
<td colspan="2"><font>
<%//显示信息
String msg = (String) request.getAttribute("msg");
if(msg!=null){
out.print(msg);
}
%>
</font></td>
</tr>
</table>
</form>
</body>
</html>
注册Servlet,UserRegisterServlet.java
package 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 dao.UserDao;
import entity.User;
/**
* 用户注册功能Servlet
*/
@WebServlet("/UserRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
req.getSession();
//获取用户表单数据
String userName = req.getParameter("userName");
String userAccount = req.getParameter("userAccount");
String userPassword = req.getParameter("userPassword");
//实例化用户对象
User user = new User();
user.setUserName(userName);
user.setUserAccount(userAccount);
user.setUserPassword(userPassword);
//添加用户
UserDao ud = new UserDao();
String status = ud.insertUser(user);
if(status.equals("OK")){
//跳转到登录界面
//String path = resp.encodeURL("userlogin.jsp");
//req.getRequestDispatcher(path).forward(req, resp);
String url = resp.encodeRedirectURL(req.getContextPath()+"/userlogin.jsp");
resp.sendRedirect(url);
}else{
String msg = "注册失败,2秒后刷新。";
req.setAttribute("msg", msg);
String path = resp.encodeURL(req.getContextPath()+"/userregister.jsp");
resp.setHeader("refresh", "2;url="+path);
}
}
}
数据库操作–添加用户方法:
/**
* 实现添加用户功能
* @param user 从表单获取的用户对象
* @return
*/
public String insertUser(User user) {
//连接数据库
Connection conn = null;
PreparedStatement ps = null;
//将用户数据写入数据库
try {
conn = DBUtils.getConnection();//获取连接对象Connection
String sql = "INSERT INTO users VALUES(NULL,?,?,?,'on',NULL)";
ps = conn.prepareStatement(sql);//格式化sql语句
//为?赋值
ps.setString(1, user.getUserName());
ps.setString(2, user.getUserAccount());
ps.setString(3, user.getUserPassword());
ps.executeUpdate();
return "OK";
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
//释放资源
DBUtils.closeAll(null, ps, conn);
}
return null;
}
©著作权归作者所有:来自51CTO博客作者龙舞飞飞的原创作品。