需求:有一个首页,首页中有登录和注册 1. 点击注册进入注册页面。成功注册后,在页面中显示 “恭喜您,注册成功,页面内将在5秒后跳转到个人主页,点击这里立即跳转” 。进入个人主页后显示当前的时间。
程序员文章站
2022-05-06 13:19:12
...
1.项目所需的jar包
- 导包:c3p0包、dbut ils包、servlet包,c3p0依赖包以及c3p0文件配置。
- 创建一个数据库day0914,并创建一个表user用于数据的存储。
- 数据库相关的包和类JdbcUtils。
2. 项目总览
3. 对外提供连接池对象
package com.fy.utils;
//1. 对外提供连接池对象
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
public class JdbcUtils {
//创建连接池对象,与数据库建立连接,并返回
private static DataSource ds = new ComboPooledDataSource("myc3p0");
//对外提供创建的连接池ds
public static DataSource getDataSource(){
return ds;
}
}
4. 实体类
package com.fy.domain;
import java.text.SimpleDateFormat;
import java.util.Date;
//2. 实体类
public class User {
private int id;
private String username;
private String password;
private Date lastTime;
//无参构造函数
public User() {
super();
}
//全参构造函数
public User(int id, String username, String password, Date lastTime) {
super();
this.id = id;
this.username = username;
this.password = password;
this.lastTime = lastTime;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 Date getLastTime() {
return lastTime;
}
public void setLastTime(Date lastTime) {
this.lastTime = lastTime;
}
public String getRegister() throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(lastTime);
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", lastTime=" + lastTime + "]";
}
}
5. 定义接口,完成登录注册功能
package com.fy.dao;
//3. 定义接口一个:UserDao,完成登录注册功能
import com.fy.domain.User;
//创建接口
public interface UserDao {
//接口中定义用户登录方法
User login(User u) throws Exception;
//接口中定义用户注册方法,返回int值
int register(User u) throws Exception;
//接口中定义用户的注册登录时间方法,通过重写方法,进行时间的更新
void updateLastTime(User u,String lastTime) throws Exception;
}
6. 重写接口中的方法,功能实现
package com.fy.service;
import com.fy.dao.UserDao;
import com.fy.domain.User;
import com.fy.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
//4. 重写接口中的方法,功能实现
public class UserService implements UserDao {
@Override
public User login(User u) throws Exception{
//建立连接池
QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
//编写SQL语句,
String sql = "select id,username,password,last_time as lastTime from user where username = ? and password = ?";
//获得数据库中的数据
return qr.query(sql,new BeanHandler<User>(User.class),u.getUsername(),u.getPassword());
}
@Override
public int register(User u) throws Exception{
QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
//在数据库中插入数据
String sql = "insert into user values (null,?,?,?)";
//对象qr将用户名、密码和注册信息在到数据库中更新
return qr.update(sql,u.getUsername(),u.getPassword(),u.getRegister());
}
@Override
public void updateLastTime(User u, String lastTime) throws Exception {
QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
//更新时间
String sql = "update user set last_time = ? where username = ?";
qr.update(sql,lastTime,u.getUsername());
}
}
7. 前端首页
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/9/14
Time: 19:57
To change this template use File | Settings | File Templates.
--%>
<%--
5. 首页
<%= request.getContextPath()%>:
页面间的跳转
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>首页</h1>
<a href="<%= request.getContextPath()%>/register.jsp">请注册</a>
<a href="<%= request.getContextPath()%>/login.jsp">请登录</a>
</body>
</html>
8. 前端登录页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/9/15
Time: 13:48
To change this template use File | Settings | File Templates.
--%>
<%--
6. 登录页面
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录页面</h1>
<form action="<%= request.getContextPath()%>/login" method="post">
<input type="text" name="user"> <span style="color:red"><%= request.getAttribute("login_error") == null ? "" : request.getAttribute("login_error")%></span>
<br>
<input type="password" name="pwd">
<br>
<input type="submit" value="登录">
<br>
</form>
</body>
</html>
9. 前端注册页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/9/15
Time: 13:51
To change this template use File | Settings | File Templates.
--%>
<%--
7. 注册页面
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>注册页面</h1>
<form action="<%= request.getContextPath()%>/register" method="post">
<input type="text" name="user"><br>
<input type="password" name="pwd"><br>
<input type="submit" value="注册"><br>
</form>
</body>
</html>
10. 创建服务器,获取用户提交的数据
package com.fy.servlet;
import com.fy.domain.User;
import com.fy.service.UserService;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
//8. 创建服务器,获取用户提交的数据
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//修改编码格式
request.setCharacterEncoding("utf-8");
//获取用户提交的数据
UserService service = new UserService();
//单独获取username , password,并将用户名和密码封装成一个对象
String username = request.getParameter("user");
String password = request.getParameter("pwd");
//创建用户对象u
User u = new User(0, username, password, new Date());
int row = 0;
try {
row = service.register(u);
} catch (Exception e) {
e.printStackTrace();
}
if(row != 0){
//user对象初始化
User user = null;
try {
user = service.login(u);
} catch (Exception e) {
e.printStackTrace();
}
HttpSession session = request.getSession();
session.setAttribute("user", user);
session.setAttribute("tag", "register");
response.sendRedirect(request.getContextPath()+"/success.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
11. 前端注册成功后的跳转页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/9/15
Time: 13:52
To change this template use File | Settings | File Templates.
--%>
<%--
9. 注册成功后的跳转页面
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script type="text/javascript">
//页面加载时,进行倒数
onload = function(){
//获得倒数的动作
var sp = document.getElementById("sp");
var count = 5;
setInterval(function(){
//设置值
sp.innerText = --count;
if(count == 1){
location.href = "<%= request.getContextPath()%>/home.jsp";
}
},1000);
}
</script>
</head>
<body>
恭喜您,注册成功,将在<span id="sp">5</span>秒后跳转到个人主页,点击<a href="<%= request.getContextPath()%>/home.jsp">这里</a>立即跳转
</body>
</html>
12. 前端个人主页
<%@ page import="com.fy.domain.User" %>
<%@ page import="com.sun.xml.internal.messaging.saaj.soap.ver1_1.Header1_1Impl" %><%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/9/15
Time: 13:41
To change this template use File | Settings | File Templates.
--%>
<%--
10. 个人主页
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
User u = (User)session.getAttribute("user");
if (u == null) {
request.setAttribute("login_error", "您还未登录,请先登录");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
%>
<h1>个人主页</h1>
欢迎您,
<c:if test="${ tag == 'register' }">
<%= ((User)session.getAttribute("user")).getUsername() %>,这是您的首次登录
</c:if>
<c:if test="${ tag == 'login' }">
<%= ((User)session.getAttribute("user")).getUsername() %>,您上次登录的时间是:<%= ((User)session.getAttribute("user")).getLastTime() %>
</c:if>
<br>
退出登录
</body>
</html>
13. 创建login服务器,将获取的用户名和密码确定用户是否存在,判断是否登录成功
package com.fy.servlet;
import com.fy.domain.User;
import com.fy.service.UserService;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
//11. 创建login服务器,将获取的用户名和密码确定用户是否存在,判断是否登录成功
/**
* 做法:
* 1. 先拿着用户名去查对应的时间,查不到就结束,查得到就获取这个时间(老时间)【开启事物】
* 2. 再设置现在的时间(新时间),再拿着用户名和密码去登录
* 3. 登录失败【回滚事务】结束,成功【提交事务】就跳转到主页
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
UserService service = new UserService();
String username = request.getParameter("user");
String password = request.getParameter("pwd");
User u = new User(0, username, password, null);
User user = null;
try {
user = service.login(u);
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
}
HttpSession session = request.getSession();
if(user != null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String lastTime = sdf.format(new Date());
try {
service.updateLastTime(user, lastTime);
session.setAttribute("user", user);
session.setAttribute("tag", "login");
response.sendRedirect(request.getContextPath()+"/home.jsp");
} catch (Exception e) {
e.printStackTrace();
}
}else{
request.setAttribute("login_error", "用户名或者密码有误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
14. 项目成果展示
(1)首页展示
(2)注册页面
注册成功,显示5秒后跳转(个人主页)
点击【这里】跳转到个人主页,并且显示当前的时间
将用户注册信息存储到数据库
(3)登录页面
登录成功
登录成功,数据库登录时间更新
用户名或者密码错误