简单的JavaWeb注册登录案例
1.注册页面register.html
register
姓名:
电话:
邮箱:
qq:
2.注册案例实现程序register.java
/**
* 注册案例实现程序
* @author lucky
*
*/
public class register extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
//获取表单提交过来的信息
String username = request.getParameter("username");
String telephone = request.getParameter("telephone");
String email = request.getParameter("email");
String qq = request.getParameter("qq");
//调用database中的insert方法,将新用户添加到数据库中
database db = new database();
try {
db.insert(username, telephone, email, qq);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.登录页面enter.html
Insert title here
用户:
密码:
4.登录案例实现程序enter.java
/**
* 登录案例实现代码
* @author lucky
*
*/
public class enter extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response) {
//获取表单提交的信息
String username = request.getParameter("username");
String qq = request.getParameter("qq");
//标记,i=2:出现错误 i=1:登录成功 i=0:登录失败
int i = 2;
//调用database方法read查询数据库
//用户名密码(qq)匹配则i=1 不匹配则i=0
database db = new database();
try {
i = db.read(username, qq);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i);
}
}
5.数据库操作相关程序database.java
/*
* 数据库操作相关程序
*/
public class database {
/*
* 用户注册,像数据库中添加信息
*/
public void insert(String username,String telephone,String email,String qq) throws Exception {
//连接池
ComboPooledDataSource cp = new ComboPooledDataSource();
Connection conn = cp.getConnection();
String sql = "insert into user(username,telephone,email,qq) values(?,?,?,?);";
//语句预编译执行者
PreparedStatement pt = conn.prepareStatement(sql);
//插入参数
pt.setString(1, username);
pt.setString(2, telephone);
pt.setString(3, email);
pt.setString(4, qq);
//执行sql语句,输出结果
int i = pt.executeUpdate();
System.out.println(i);
}
/*
* 用户登录 向数据库查询用户输入信息是否正确
*/
public int read(String username,String qq) throws Exception {
ComboPooledDataSource cp = new ComboPooledDataSource();
Connection conn = cp.getConnection();
//通过提交的用户名对比查询相应的qq 结果一致则输入正确 不一致则输入错误
String sql = "select qq from user where username = ?;";
//用pwd接受数据库中查询出来的qq信息
String pwd = null;
PreparedStatement pt = conn.prepareStatement(sql);
pt.setString(1, username);
//re接收结果集
ResultSet rs = pt.executeQuery();
//对比qq信息是否一致
while(rs.next()){
pwd = rs.getString("qq");
System.out.println("qq"+pwd);
}
//输出结果
if(pwd.equals(qq)) return 1;
elsereturn 0;
}
}
6.web.xml
registerenter
register
web.register
register
/register
enter
web.enter
enter
/enter
新人学习记录,有问题可以一起探讨。