该项目为简单的注册登录功能,采用mysql数据库,DBUtils链接
该项目已上传至github,点此下载
需要用到的jar包文件如下:
c3p0-0.9.1.2.jar
commons-beanutils-1.8.3.jar
commons-dbutils-1.4.jar
commons-logging-1.1.1.jar
mysql-connector-java-5.1.39-bin.jar
整个项目的使用过程是:运行tomcat,在浏览器中输入:http://localhost/WEB_TEST/
进入到主页,点击注册,注册成功之后,会直接跳转到登录页面,输入刚刚注册的账户和密码,如果正确,将会再次回到主页,如果失败,会在登录页面显示错误信息。
DBUtils封装成了工具类DataSourceUtils.java
package cn.itclass.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DataSourceUtils {
private static DataSource dataSource = new ComboPooledDataSource();
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
// 直接可以获取一个连接池
public static DataSource getDataSource() {
return dataSource;
}
// 获取连接对象
public static Connection getConnection() throws SQLException {
Connection con = tl.get();
if (con == null) {
con = dataSource.getConnection();
tl.set(con);
}
return con;
}
// 开启事务
public static void startTransaction() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.setAutoCommit(false);
}
}
// 事务回滚
public static void rollback() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.rollback();
}
}
// 提交并且 关闭资源及从ThreadLocall中释放
public static void commitAndRelease() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.commit(); // 事务提交
con.close();// 关闭资源
tl.remove();// 从线程绑定中移除
}
}
// 关闭资源方法
public static void closeConnection() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.close();
}
}
public static void closeStatement(Statement st) throws SQLException {
if (st != null) {
st.close();
}
}
public static void closeResultSet(ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
}
}
数据库相关配置在\login and regist ServletDemo\src\c3p0-config.xml文件中进行修改
<c3p0-config>
<default-config>
<property name="user">rootproperty>
<property name="password">123456property>
<property name="driverClass">com.mysql.jdbc.Driverproperty>
<property name="jdbcUrl">jdbc:mysql:///web15property>
default-config>
c3p0-config>
数据库名为:web15
表名:user
创建表的语句:
CREATE TABLE `user` (
`uid` varchar(32) NOT NULL,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
`email` varchar(30) DEFAULT NULL,
`telephone` varchar(20) DEFAULT NULL,
`birthday` varchar(20) DEFAULT NULL,
`sex` varchar(10) DEFAULT NULL,
`state` int(11) DEFAULT NULL,
`code` varchar(64) DEFAULT NULL,
PRIMARY KEY (`uid`)
)
两个JSP页面,一个html主页,代码如下:
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
<form action="/WEB_TEST/Login" method="post">
<%=request.getAttribute("loginInfo") == null ? "" : request.getAttribute("loginInfo")%>
<br /> <label>用户名:label> <input type="text" name="username"
placeholder="请输入用户名" /><br /> <label>密码:label> <input type="text"
name="password" placeholder="请输入密码" /><br /> <input type="submit"
value="登录" name="submit" />
form>
body>
html>
register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
<form action="/WEB_TEST/Login" method="post">
<label>用户名label>
<input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名"><br />
<label >密码label>
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="请输入密码"><br />
<label for="confirmpwd" class="col-sm-2 control-label">确认密码label>
<input type="password" class="form-control" id="confirmpwd" placeholder="请输入确认密码"><br />
<label for="inputEmail3" class="col-sm-2 control-label">Emaillabel>
<input type="email" class="form-control" id="inputEmail3" name="email" placeholder="Email"><br />
<label for="usercaption" class="col-sm-2 control-label">姓名label>
<input type="text" class="form-control" id="usercaption" name="name" placeholder="请输入姓名"><br />
<label for="inlineRadio1" class="col-sm-2 control-label">性别label>
<label class="radio-inline"> <input type="radio" name="sex" id="inlineRadio1" value="male">男label>
<label class="radio-inline"> <input type="radio" name="sex" id="inlineRadio2" value="female">女label><br />
<input type="submit" width="100" value="注册" name="submit">
form>
body>
html>
index.html
<html>
<head>
<meta charset="UTF-8">
<title>首页title>
head>
<body>
<h1>我是主页h1>
<a href="/WEB_TEST/login.jsp">登录a>
<a href="/WEB_TEST/register.jsp">注册a>
body>
html>
接下来是Register.java和Login.java
Register.java:
package cn.itclass.register;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import cn.itclass.utils.DataSourceUtils;
public class Register extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1、获取数据
// String uesername = request.getParameter("username");
// String password = request.getParameter("password");
// 2、将散装的数据封装到javaBean中
// User user = new User();
// user.setUsername(uesername);太麻烦,使用BeanUtils
// 设置编码,只适合post方式
request.setCharacterEncoding("UTF-8");
// get方式的乱码解决办法,post同样适用 以下三行为get提交方式的防乱码
// 但是一般来说,注册不会用到get方式提交,所以我们采用上面的方法,更加简便
//String uesername = request.getParameter("username");
// 先用ISO8859-1编码,然后在使用UTF8解码
//uesername = new String(uesername.getBytes("ISO8859-1"),"UTF-8");
// 使用BeanUtils进行自动映射封装
// 工作原理:将map中的数据,根据key与实体的属性的对应关系封装
// 只要key的名字与实体的属性的名字一样,就自动封装到实体中
Map<String, String[]> parameterMap = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user, parameterMap);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
// 现在这个位置,user对象已经封装好了
// 需要手动封装uid---uuid,随机的不重复的字符串,32位,java生成后是36位
// 这个地方是给主键uid赋值,数据库可以用自增长,但是在正式项目中,很少会用到自增长,基本都是采用uuid的方式进行赋值。
user.setUid(UUID.randomUUID().toString());
// 3、将参数传给一个业务操作方法
try {
regist(user);
} catch (SQLException e) {
e.printStackTrace();
}
// 到此处认为注册成功,跳转到登录页面----转发或者重定向
// request.getRequestDispatcher("/WEB15/LoginConfig.jsp").forward(request, response);转发不会改变地址
// 如果用户刷新,就会重新刷新register,增加服务器负担,而且会出问题,重定向更合适
// response.sendRedirect("/WEB_TEST/login.jsp");//如果之后改了项目名,就会出问题
response.sendRedirect(request.getContextPath() + "/login.jsp");//用getContextPath()动态获取地址
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
// 注册的方法
public void regist(User user) throws SQLException {
// 操作数据库
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)";
runner.update(sql, user.getUid(), user.getUsername(), user.getPassword(), user.getName(), user.getEmail(), null,
user.getBirthday(), user.getSex(), null, null);
}
}
Login.java:
package cn.itclass.login;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import cn.itclass.register.User;
import cn.itclass.utils.DataSourceUtils;
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 0、谨慎起见,进行编码设置
request.setCharacterEncoding("UTF-8");
// 1、获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username);
System.out.println(password);
// 2、调用一个业务方法,进行用户查询
User login = null;
try {
login = login(username, password);
} catch (SQLException e) {
e.printStackTrace();
}
if (login != null) {
// 用户名和密码正确
// 跳转到网站首页
response.sendRedirect(request.getContextPath());
} else {
// 用户名或密码错误
// 跳回当前页面,输出错误信息
request.setAttribute("loginInfo", "用户名或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
// 用户查询
public User login(String username, String password) throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username=? and password=?";
User user = runner.query(sql, new BeanHandler<User>(User.class), username, password);
return user;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
因为用到了BeanUtils进行自动映射封装,所以还需要一个User类,对我们的数据进行一个包装:
package cn.itclass.register;
public class User {
private String uid;
private String username;
private String password;
private String name;
private String email;
private String sex;
private String birthday;
public String getUid() {
return uid;
}
public void setUid(String 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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", name=" + name + ", email="
+ email + ", sex=" + sex + ", birthday=" + birthday + "]";
}
}