开发工具及开发环境
Eclipse EE、Mysql、Navicat for MySQL、Tomcat-9.0.60、windows 10系统
WEB系统注册与登录功能模块需求
1.1 注册功能
- 注册时需提供以下信息:
- 用户名 - 长度必须大于等于6位,小于10位- 用户名不能重名- 必选项
- 登录密码 - 必须至少有1个数字、1个大写字母、1个小写字母和其它字符共同组成- 长度必须大于6位,小于12位- 需要用户输入两次相同的密码才能确认注册- 必选项
- 邮件地址 - 用户邮件地址,需要校验邮件格式###@####,后台校验- 邮件地址不能重复- 必选项
- 单位 - 最大长度50位- 可选项- 注册提交后:- 所有信息都合法,则返回显示注册成功字样的页面,内含返回登录界面的链接。- 若有部分信息不合法,则返回显示注册失败字样的页面,内含指明哪条注册信息错误的提醒,同时内含返回重新填写的链接- 注册成功后:系统将自动获得用户的成功注册时间,包括:年月日时分秒
1.2 登录功能
登陆时的过程:
- 输入用户名和密码
- 提交登陆
- 登陆提交后:
- 若有该用户名,密码不正确,则返回包含登录密码错误字样的页面,内含返回重新登录的链接
- 若无该用户名,则返回包含“用户名或密码错误”字样的页面,内含返回重新登录的链接
- 若登陆成功,则返回包含“登录成功”字样的页面,内含返回用户注册信息的链接和退出登录链接
1.3 填写补充信息功能
- 只有登录用户可以填写补充信息
- 补充信息包括
(1)真实姓名,必填,只能包含不含空格的2-4个中文字符,或20个字符以内的英文字符
(2)电话号码,选填,11位数字
(3)出生年份与日期,必填,允许输入格式包括1977-12-14,或1977年12月14日。年份最早不能早于1900年,最晚不能晚于填写当天
1.3 查看注册信息功能
- 只有登录用户才能查看注册信息
- 登录用户可以查看自己的注册详情和自己的补充信息
- 查看注册信息包含所有注册的信息和注册日期信息
- 查看注册信息页面包含退出登录链接
1.4 修改用户信息功能
- 注册用户信息页面提供链接对自己的注册信息进行修改
- 可以对密码和邮箱信息进行修改
- 修改每项信息时提供单独页面
- 修改密码时要求用户输入旧密码、新密码、新密码确认
- 修改信息时进行信息正确性校验
- 如果输入格式错误,修改不成功,则给出错误提示
- 修改成功则提示修改成功信息
1.5 用户退出
- 只有成功登录的用户才能退出
- 退出后不能进行查看注册用户信息功能
1.6 其它功能
- 所有页面的显著位置显示:项目-项目人-当前日期/时间
如:JSP课设-Evanpatchouli℃-2021-6-17/11:07
- 所有功能结果页面都要具备可测试性,及结果页面需要有明确标志,表示功能成功与否。
项目流程结构及源码
1.项目文件结构
2.jar包
3.数据库表结构
基本的表结构如图,各属性由实际要求所定
(用户名主键的同时,将email设置为唯一索引,保证两者都不重复)
项目编写的流程(参考)
一、根据需求,建立数据库和表
使用navicat的sql可视化界面:
1.建立连接
如下图所示,点击“连接”,创建主机名localhost,埠3306的连接(连接名不设置,默认为localhost_3306)
用户名和密码自己设置,测试连接成功即可(我的设置为root, root)
2.建立数据库
如下图所示,右键连接名创建数据库,设置数据库名为usermanager,字符集为UTF8(防止存入中文字符导致乱码)
![](https://img-blog.csdnimg.cn/c1dc69229fc84416812ecf7954a29025.png) ![](https://img-blog.csdnimg.cn/114a0ddc57984b65bb34ea6370495bd0.png)
3.建立表
如下图,点击“创建表”,并建立所需的字段。该系统用数据库存储用户的用户名、密码、邮箱、单位、注册时间、真名、电话和生日这8条信息,所以创建8个字段:username, userpassword, email, unit, registertime, realname, phone, birth。前四个为必填项,设为非空(not null);要求用户名和邮箱不得重复,因为设置用户名username为主键,邮箱email为唯一索引。
二、编写web应用
1.确定应用流程思路
2.编写代码
StringUtil.java:字符串工具类
定义几个字符串方法,在用户操作进行校验时被调度(严谨校验的使用程度高,推荐这样在外定义一个方法以便被多次调用)。
package utils;
public class StringUtil {
public static boolean isEmpty(String str) {
if ("".equals(str) || str == null) {
return true;
} else {
return false;
}
}
public static boolean isNotEmpty(String str) {
if (!"".equals(str) && str != null) {
return true;
} else {
return false;
}
}
public static String nullString(Object object){
if(object==null){
return "";
}else {
return object.toString();
}
}
}
JdbcUtil.java:数据库工具类
包含两个方法,连接数据库和释放;数据库连接方法getConnection()内定义好数据库链接,用户名和密码以及驱动器,并反回创建好的连接;释放,释放conn, resultSet和statment.
package utils;
import java.sql.*;
public class JdbcUtil {
//(1)获取connection
public static Connection getConnection() throws Exception{
String url="jdbc:mysql://localhost:3306/usermanager";
String name="root";
String pwd="root";
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);//连接驱动
Connection conn = DriverManager.getConnection(url,name,pwd);//连接数据库
return conn;
}
//(2)释放资源
public static void release(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
User.java:用户类。用户包含总共8条数据,以此设计用户类和相对应的方法即可。
package domain;
import java.util.*;
public class User {
private String username;
private String password;
private String email;
private String unit;
private String registertime;
private String realname;
private String phone;
private String birth;
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the unit
*/
public String getUnit() {
return unit;
}
/**
* @param unit the unit to set
*/
public void setUnit(String unit) {
this.unit = unit;
}
/**
* @return the registertime
*/
public String getRegistertime() {
return registertime;
}
/**
* @param registertime the registertime to set
*/
public void setRegistertime(String registertime) {
this.registertime = registertime;
}
/**
* @return the realname
*/
public String getRealname() {
return realname;
}
/**
* @param realname the realname to set
*/
public void setRealname(String realname) {
this.realname = realname;
}
/**
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return the birth
*/
public String getBirth() {
return birth;
}
/**
* @param birth the birth to set
*/
public void setBirth(String birth) {
this.birth = birth;
}
@Override
public int hashCode() {
return Objects.hash(birth, email, password, phone, realname, registertime, unit, username);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
return Objects.equals(birth, other.birth) && Objects.equals(email, other.email)
&& Objects.equals(password, other.password) && Objects.equals(phone, other.phone)
&& Objects.equals(realname, other.realname) && Objects.equals(registertime, other.registertime)
&& Objects.equals(unit, other.unit) && Objects.equals(username, other.username);
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", email=" + email + ", unit=" + unit
+ ", registertime=" + registertime + ", realname=" + realname + ", phone=" + phone + ", birth=" + birth
+ "]";
}
}
UserDao.java:用户Dao接口
该接口类包含了对用户最基本的方法:登录、注册、查找、改密和补充,在UserDaoImpl中实现。
package dao;
import domain.User;
public interface UserDao {
//登陆
User login(String username,String password);
//注册
User register(User user);
//查找
boolean select(String username, String email);
//修改信息(密码)
void updateUser(User user);
//补充信息
void addxinxi(User user);
//
}
UserDaoImpl.java:UserDao的具体实现类
UserDaoImpl中建立数据库连接,对用户信息进行增删改查,并将操作结果记录到字符串message中,由*back()*函数接收,以便后续测试时使用。
package dao.impl;
import dao.UserDao;
import domain.User;
import utils.JdbcUtil;
import java.sql.*;
/*
* 用户Dao实现类
*/
public class UserDaoImpl implements UserDao {
String message;
public String Back() {
return message;
}
public User login(String username,String password) {
User user=null;
Connection conn=null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = JdbcUtil.getConnection();
String sql = "select * from user where username = ? and userpassword= ?";
PreparedStatement prpstmt = null;
prpstmt = conn.prepareStatement(sql);
prpstmt.setString(1, username);
prpstmt.setString(2, password);
rs = prpstmt.executeQuery();
if(rs.next()){
user = new User();
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("userpassword"));
user.setEmail(rs.getString("email"));
user.setUnit(rs.getString("unit"));
user.setRegistertime(rs.getString("registertime"));
user.setRealname(rs.getString("realname"));
user.setPhone(rs.getString("phone"));
user.setBirth(rs.getString("birth"));
message="登录成功";
System.out.println(message + user.toString());
}else {
message="用户名或者密码错误";
System.out.println(message);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
JdbcUtil.release(rs, stmt, conn);
}
return user;
}
public User register(User user){
Connection conn = null;
PreparedStatement prpstmt = null;
ResultSet rs = null;
@SuppressWarnings("unused")
int result = 0;
try {
conn = JdbcUtil.getConnection();
String sql = "insert into user(username, userpassword, email, unit, registertime) values (?, ?, ?, ?, ?);";
prpstmt = conn.prepareStatement(sql);
prpstmt.setString(1, user.getUsername());
prpstmt.setString(2, user.getPassword());
prpstmt.setString(3, user.getEmail());
prpstmt.setString(4, user.getUnit());
prpstmt.setString(5, user.getRegistertime());
result = prpstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.release(rs, prpstmt, conn);
}
System.out.println(result);
if(result!=0) {
message="注册成功";
}else {
message="注册失败";
}
return user;
}
public boolean select(String username, String email) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql_1 = "select count(*) from user where username = ?";
String sql_2 = "select count(*) from user where email = ?";
int count = 0;
try {
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql_1);
ps.setString(1, username);
rs = ps.executeQuery();
rs.next();
count = rs.getInt(1);
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtil.release(rs, ps, conn);
}
try {
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql_2);
ps.setString(1, email);
rs = ps.executeQuery();
rs.next();
count += rs.getInt(1);
if(count > 0){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtil.release(rs, ps, conn);
}
return false;
}
public void updateUser(User user) {
Connection conn = null;
PreparedStatement ps = null;
String sql = "update user set userpassword=? where username=?";
int rs = 0;
try {
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, user.getPassword());
ps.setString(2, user.getUsername());
rs=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.release(null, ps, conn);
}
if(rs!=0) {
message=user.getPassword();
}
System.out.println(rs);
}
@Override
public void addxinxi(User user) {
Connection conn = null;
PreparedStatement ps = null;
String sql = "update user set realname=?, phone=?, birth=? where username=?";
@SuppressWarnings("unused")
int rs = 0;
try {
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, user.getRealname());
ps.setString(2, user.getPhone());
ps.setString(3, user.getBirth());
ps.setString(4, user.getUsername());
rs=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.release(null, ps, conn);
}
}
}
UserService.java:用户服务接口,由UserServiceImpl实现
(UserService->UserServiceImpl->UserDao->UserDaoImpl,直接放进UserDao也可以)
package service;
import domain.User;
public interface UserService {
// 新增用户时查重
boolean checkUsername(String username, String email);
// 修改用户信息
void saveUser(User user);
//补充用户信息
void addInfo(User user);
}
UserServiceImpl:(UserService并入UserDao,则UserServiceImpl并入UseerDaoImpl)
package service.impl;
import java.sql.*;
import java.util.List;
import dao.UserDao;
import dao.impl.UserDaoImpl;
import domain.User;
import service.UserService;
import utils.JdbcUtil;
/**
* UserService用户服务实现类
*/
@SuppressWarnings("unused")
public class UserServiceImpl implements UserService{
private UserDao userDao = new UserDaoImpl();
public boolean checkUsername(String username, String email) {
return userDao.select(username, email);
}
@Override
public void saveUser(User user) {
userDao.updateUser(user);
}
@Override
public void addInfo(User user) {
userDao.addxinxi(user);
}
}
系统要求每个页面都实时显示信息和时间,因此准备一个time.jsp,其余jsp可视页面均采用include指令标**记(*<%@ include file="time.jsp" %>)将time.jsp*嵌入到自身页面中。
time.jsp:创建一个div,设置其id为datetime,在script标记中,定义*showtime()函数在该div元素中动态地显示时间信息,并调用自定义check()函数给单位数加上"0";setInterval(showtime(), 1000)*设置显示时间函数每秒运行(刷新实时时间)。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.time.LocalTime" %> <!-- jsp指令标记 -->
<%@ page import="java.time.LocalDate" %> <!-- jsp指令标记 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Show time</title>
</head>
<script>
function showtime(){
nowtime=new Date();
y=nowtime.getFullYear();
mo=nowtime.getMonth()+1;
d=nowtime.getDate();
h=nowtime.getHours();
mi=nowtime.getMinutes();
s=nowtime.getSeconds();
mo=checkTime(mo);
d=checkTime(d);
mi=checkTime(mi);
s=checkTime(s);
document.getElementById("datetime").innerText="JSP课设-Evanpatchouli℃-"+y+"-"+mo+"-"+d+"/"+h+":"+mi+":"+s;
}
setInterval("showtime()", 1000);
function checkTime(i) {
if (i<10){
i="0" + i;
}
return i;
}
</script>
<body >
<div id="datetime" style="font-size:24px;font-weight:bold;text-align:center; padding-left: 90px;" ></div>
</body>
</html>
各个页面都需要进行登录检测,以防未登录,框架如下:不同页面为迎合自己的功能会有略改。
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
<a href="login.jsp" name="login">去登录</a>
<a href="register.jsp" name="register">跳转注册</a>
<%
} else {
%>
<!-- 该页内容 -->
<%}%>
register.jsp:用户注册页,用form表单+servlet提交注册信息。表单action请求RegisterServlet,表单含用户名、密码、邮箱、单位,提供重置*(reset)和注册(submit)按钮,具体格式见下。由于对各个注册信息有长度限制,有三种方法:1.设置好input标记的minlength和maxlength属性;2.在script中定义一个函数,注册框的onclick属性设置成"return check()",在点击注册时被调度,读取输入框并检查内容的合法性;3.提交给servlet后,在servlet*中检验并返回结果。对于长度这样简单的限制采取第1种方法极为方便,而大小写等复杂的格式校验则需要采用后2种方法。
前2种属于前端校验,第3种属于后端校验,前两者用户体验感更好。项目需求中要求信息违法转到失败页面并显示,原则上第3种最符合要求。
第1种: 第2种:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="time.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body style="text-align:left;">
<script type="text/javascript">
function check(){
var flag = 0;//flag为0代表密码没有问题
var Uname=document.getElementById('uname').value;//首先通过文本框的id获取它的值然后进行判断
if(Uname.length<6){//如果输入信息有误,弹出提示框
alert("用户名最短长度为6");
flag = 1;
}
var Upwd=document.getElementById('upwd').value;
var regLower = /^.*[a-z]{1,}.*$/;//包含小写字母
var regUpper = /^.*[A-Z]{1,}.*$/;//包含大写字母
var regSpecial = /^.*[^a-zA-Z0-9]{1,}.*$/;//包含特殊字符
var regNum = /^.*[0-9]{1,}.*$/;//包含数字
//如果密码纯数字、纯小写字母、纯大写字母、纯特殊字符,禁止注册
if(!regLower.test(Upwd) || !regUpper.test(Upwd) || !regSpecial.test(Upwd) || !regNum.test(Upwd)){
alert("密码必须至少有1个数字、1个大写字母、1个小写字母和其它字符共同组成!");
flag = 1;
}
if(flag==0)
return true;
else
return false;
}
</script>
<form action="RegisterServlet" method="post">
<table align="center">
<div style="text-align:center;">
<h2>用户注册</h2>
</div>
<tr>
<td>用 户 名:</td>
<%--<td><input name="username" type="text" size="21" minlength="6" maxlength="9" placeholder="用户名长度6-9位"></td>--%>
<td><input id="uname" name="username" type="text" size="21" maxlength="9" placeholder="用户名长度6-9位"></td>
</tr>
<tr>
<td align="justify">密 码:</td>
<td><input id="upwd" name="password" type="password" size="21" minlength="7" maxlength="11" placeholder="密码长度7-11位"></td>
</tr>
<tr>
<td align="justify">确认密码:</td>
<td><input name="ckpassword" type="password" size="21" minlength="7" maxlength="11" placeholder="密码长度7-11位"></td>
</tr>
<tr>
<td align="justify">E - mail:</td>
<td><input name="email" type="text" size="21" maxlength="21"></td>
</tr>
<tr>
<td align="justify">单 位:</td>
<td><input name="unit" type="text" size="21" maxlength="50" placeholder="填写单位名称"></td>
</tr>
</table>
<table align="center" cellspacing="12">
<tr>
<td align="justify"><input type="submit" name="submit" value="注册" onclick="return check();"></td>
<td align="justify"><input type="reset" name="reset" value="重置"></td>
</tr>
</table>
</form>
<div align="center">
<a href="login.jsp" name="login">跳转登录</a>
</div>
</body>
</html>
RegisterServlet.java:接受register.jsp提交的表单的注册信息,生成注册时间,同时对其他的不合法行为进行检测,如查重、查空等,检验过程中调用了StringUtil中对字符串的方法(不必要)和UserService中的*checkUsername()*进行查重等操作。
检验合法后,创建一个User对象和UserDao对象,注册User,将用户信息存入数据库内(UserDao实现类中实现)。然后在session中创建一个关键字*"usernamePrepared",将注册好的用户名赋给它,用于后续登录时预置用户名,以增强用户体验(不必要),然后跳转到注册成功的页面;如果不合法,在request中创建一个关键字"message"*,存入错误信息,并跳转到注册失败的页面。
package servlet;
import dao.UserDao;
import dao.impl.UserDaoImpl;
import domain.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.StringUtil;
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;
/**
* RegisterServlet实现类
*/
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserService userService = new UserServiceImpl();
/**
* @see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPut(request, response);
}
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String rs = "";
String username = request.getParameter("username");
String password = request.getParameter("password");
String ckpassword = request.getParameter("ckpassword");
String email = request.getParameter("email");
String unit = request.getParameter("unit");
String registertime=formatter.format(date);
System.out.println(registertime);
if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)||StringUtil.isEmpty(ckpassword)||StringUtil.isEmpty(email)||StringUtil.isEmpty(unit)) {
rs = "注册信息填写不完整!";
}
// 两次输入密码是否一致
if (!password.equals(ckpassword)) {
rs = "两次密码输入不一致!";
}
boolean IsUserExist = userService.checkUsername(username,email);
if(IsUserExist==true) {
rs = "账号已存在!";
}
if(StringUtil.isEmpty(rs)) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setUnit(unit);
user.setRegistertime(registertime);
System.out.println(user.getRegistertime());
UserDao userDao = new UserDaoImpl();
userDao.register(user);
System.out.println("注册成功");
session.setAttribute("usernamePrepared", username);
request.getRequestDispatcher("register_success.jsp").forward(request,response);
}else {
System.out.println("注册失败"+rs);
request.setAttribute("message", "注册失败!"+rs);
request.getRequestDispatcher("/register_fail.jsp").forward(request,response);
}
}
}
** register_success.jsp**:注册成功页面
显示注册成功信息;包含2个链接,分别跳转到登录页和注册页。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="time.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册成功</title>
</head>
<body style="text-align:center;">
<h1>注册成功!
<br>
<a href="login.jsp" name="login">跳转登录</a>
<a href="register.jsp" name="register">继续注册</a>
</h1>
</body>
</html>
register_fail.jsp:注册失败页
显示注册失败字样,从RegisterServlet接收并显示失败原因;内含1个链接跳转到注册页。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="time.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册失败</title>
</head>
<body style="text-align:center;">
<h2>注册失败!</h2>
<font color="red" face="bold" size=5>
<%
if(request.getAttribute("message")!= null){
out.print(request.getAttribute("message"));
}
%>
</font>
<br>
<h2><a href="register.jsp" name="register">重新注册</a></h2>
</body>
</html>
Login.jsp:用户登录页
定义Uname(uP, uL)函数作为用户名预置,其值为刚注册的用户名或者刚退出登录的用户名。表单内username文本框,默认值即为*Uname()*的返回值。
(在撰写文档的时候发现一个小BUG,点清空,预置的用户名不消失,一种解决方法是Uname函数中加上一个条件判断:是否点击过清空)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="time.jsp" %>
<%@ page import="domain.User" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登陆</title>
</head>
<body style="text-align:center;">
<%!
public String Uname(String uP,String uL){
if(uL!=null){
return uL;
}else{
return uP;
}
}
%>
<%
Object obj = session.getAttribute("user");
String unameP = (String)session.getAttribute("usernamePrepared");
String unameL = (String)request.getParameter("usernameLogined");
String UName = Uname(unameP,unameL);
System.out.println("unameL:"+unameL);
if(null==obj) {
%>
<h2>登录页面</h2>
<form action="LoginServlet" method="post">
<table align="center">
<tr>
<td>
用户名:</td>
<td style="text-align:center"><input type="text" size="21" name="username" value="<%=UName%>"/></td>
</tr>
<tr>
<td>
密 码:</td>
<td><input type="password" size="21" name="password"/></td>
</tr>
</table>
<table align="center" cellspacing="5">
<tr>
<td><input type="submit" name="submit" value="登录"/></td>
<td><input type="reset" name="reset" value="清空"/></td>
</tr>
</table>
</form>
<a href="register.jsp" name="register">跳转注册</a>
<%
} else {
%>
<%
User u = (User)obj;
%>
用户:<%=u.getUsername() %><br/>您已经登录,无需再登录
<br/><a href="exit.jsp" name="exit">退出登录</a>
<br/><a href="login_success.jsp" name="success">返回</a>
<%}%>
</body>
</html>
LoginServlet.java:
获取登录页提交的信息,查库,登录成功则在session中创建user关键字保存user对象,用以作登录检测;如果登录失败,将错误信息存入request关键字message中,传递给登录失败页。
package servlet;
import dao.UserDao;
import dao.impl.UserDaoImpl;
import domain.User;
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;
/**
* LoginServlet实现类
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 获取前端页面传过来的值
String username = request.getParameter("username");
String password = request.getParameter("password");
// 执行查询数据库逻辑
UserDao userDao = new UserDaoImpl();
User user = userDao.login(username, password);
// 如果根据用户名和密码能查得到值
if (user!= null) {
session.setAttribute("user", user); //登录成功
request.getRequestDispatcher("/login_success.jsp").forward(request,response);
} else { // 用户名或者密码错误执行以下代码
request.setAttribute("message", "用户名或者密码错误");
request.getRequestDispatcher("/defeat.jsp").forward(request,response);
}
}
}
login_success.jsp:登录成功页(内含链接:显示信息、信息补充和退出登录)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="domain.User" %>
<%@ include file="time.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登陆成功</title>
</head>
<body style="text-align:center;">
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
<a href="login.jsp" name="login">去登录</a>
<a href="register.jsp" name="register">跳转注册</a>
<%
} else {
%>
<%--<h2>登录成功!</h2>--%>
<font color="blue" size="5" family="Microsoft JhengHei">
登录成功!<br/>
<%
String username = user.getUsername();
session.setAttribute("user", user);
%>
欢迎您:<%=username %><br/>
<a href="showUserRegisterInfo.jsp" name="show">显示信息</a><br>
<a href="AddInfo.jsp" name="add">信息补充</a><br>
<a href="exit.jsp" name="exit">退出登录</a>
</font><br>
<%}%>
</body>
</html>
defeat.jsp:登录失败页
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="time.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录失败</title>
</head>
<body style="text-align:center;">
<h2>登录失败!</h2>
<font color="red" face="bold" size=5>
<%
if(request.getAttribute("message")!= null){
out.print(request.getAttribute("message"));
}
%>
</font>
<br>
<h2><a href="login.jsp" name="login">重新登录</a></h2>
</body>
</html>
exit.jsp:退出登录
先获取当前登录的用户名,存到预置用户名内,然后销毁session
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="domain.User" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>退出登录</title>
</head>
<body>
<%
Object obj = session.getAttribute("user");
User u = (User)obj;
String unameLogined = (String)u.getUsername();
System.out.println(unameLogined);
session.invalidate();
%>
<jsp:forward page="login.jsp">
<jsp:param value="<%=unameLogined%>" name="usernameLogined" />
</jsp:forward>
</body>
</html>
showUserRegisterInfo.jsp:显示用户信息页(内含修改密码链接)
从session中获取登录的user对象,并读取各用户信息即可,不用额外的连接数据库。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%@page import="domain.User" %>
<%@ include file="time.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>显示用户信息</title>
</head>
<body style="text-align:center;">
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
<a href="login.jsp" name="login">去登录</a>
<a href="register.jsp" name="register">跳转注册</a>
<%
} else {
%>
<div style="text-align:center;">
当前用户:<%=user.getUsername() %>
<a href="exit.jsp" name="exit">退出登录</a>
<a href="login_success.jsp" name="success">返回</a>
</div>
<h1>用户注册信息表</h1>
<table border="1px" align="center">
<tr>
<th>用户名</th>
<th>密码</th>
<th>邮箱</th>
<th>单位</th>
<th>注册时间</th>
</tr>
<tr>
<td><%=user.getUsername()%></td>
<td><%=user.getPassword()%></td>
<td><%=user.getEmail()%></td>
<td><%=user.getUnit()%></td>
<td><%=user.getRegistertime()%></td>
</tr>
</table>
<h1>用户补充信息表</h1>
<table border="1px" align="center">
<tr>
<th>真名</th>
<th>电话</th>
<th>生日</th>
</tr>
<tr>
<td><%=user.getRealname()%></td>
<td><%=user.getPhone()%></td>
<td><%=user.getBirth()%></td>
</tr>
</table>
<br>
<h1><a href="updateInfo.jsp" name="changepwd">修改密码</a></h1>
<%}%>
</body>
</html>
AddInfoServlet.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 javax.servlet.http.HttpSession;
import dao.UserDao;
import dao.impl.UserDaoImpl;
import domain.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.StringUtil;
/**
* AddInfo实现类
*/
@WebServlet("/AddInfoServlet")
public class AddInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao = new UserDaoImpl();
private UserService userService = new UserServiceImpl();
public AddInfoServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
User user = ((User) session.getAttribute("user"));
String realname = request.getParameter("realname");
String phone = request.getParameter("phone");
String birth = request.getParameter("birth");
user.setRealname(realname);
user.setPhone(phone);
user.setBirth(birth);
//request.getAttribute("user");
userService.addInfo(user);
request.setAttribute("AddInfoResult", "补充信息成功!");
request.getRequestDispatcher("/AddInfo.jsp").forward(request, response);
return;
}
}
UpdateInfoServlet.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 dao.impl.UserDaoImpl;
import domain.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.StringUtil;
/**
* UpdateInfoServlet实现类
*/
@WebServlet("/UpdateInfoServlet")
public class UpdateInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao = new UserDaoImpl();
private UserService userService = new UserServiceImpl();
public UpdateInfoServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//修改密码
String username = request.getParameter("username");
String oldPassword = request.getParameter("oldPassword");
String newPassword = request.getParameter("newPassword");
User user = userDao.login(username, oldPassword);
String changePWDResult="";
if(user==null) {
changePWDResult="旧密码错误!";
}
if(StringUtil.isEmpty(oldPassword)||StringUtil.isEmpty(newPassword)) {
changePWDResult="旧密码和新密码不能为空!";
}
if(StringUtil.isEmpty(changePWDResult)) {
user.setPassword(newPassword);
userService.saveUser(user);
changePWDResult="密码修改成功!";
}
request.setAttribute("changePasswordResult", changePWDResult);
request.getRequestDispatcher("/updateInfo.jsp").forward(request, response);
return;
}
}
AddInfo.jsp:信息补充页
同样是form+servlet的方式;script内有一个显示补充结果的函数;补充信息的格式校验我没有做,方法可参考注册时讲到的3种校验,需要用到正则表达式。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ page import="domain.User" %>
<%@ include file="time.jsp" %>
<html>
<head>
<meta charset="UTF-8">
<title>补充信息</title>
<script type="text/javascript">
$(function() {
if ($("#AddInfoResult").length > 0) {
alert($("#AddInfoResult").text());
}
});
</script>
</head>
<body style="text-align:center;">
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
<a href="login.jsp" name="login">去登录</a>
<a href="register.jsp" name="register">跳转注册</a>
<%
} else {
%>
<form action="AddInfoServlet" method="post">
<input type="hidden" name="username" value=<%=user.getUsername() %>>
<div style="text-align:center; padding-right: 10px;">
当前用户:<%=user.getUsername() %>
<a href="exit.jsp" name="exit">退出登录</a>
<a href="login_success.jsp" name="success">返回</a>
</div>
<table border="1px" align="center">
<div align="center">
<h2>补充信息</h2></div>
<tr align="center">
<td align="justify">
真名: <input type="text" name="realname" size=10 maxlength=20/><br/></td>
<td align="justify">
电话: <input type="text" name="phone" size=12 maxlength=16/>(11位手机号)<br/></td><!-- 限长16允许带+ -->
<td align="justify">
生日: <input type="text" name="birth" size=11 maxlength=11/>(格式:1977-12-14或者1977年12月14日)<br/></td>
<td align="justify">
<input type="submit" value="提交" name= "submit">
<input type="reset" value="重置" name="reset"></td>
</tr>
</table>
</form>
<%
Object result = request.getAttribute("AddInfoResult");
if (result != null) {
%>
<br>
<h2><%=(String)result%></h2>
<%
}
%>
<%}%>
</body>
</html>
updateInfo.jsp:修改密码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="domain.User" %>
<%@ include file="time.jsp" %>
<%@ page import="java.util.*" %>
<!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">
<script type="text/javascript" src="js/jquery.js"></script>
<title>修改密码</title>
<script type="text/javascript">
$(function() {
if ($("#changePasswordResult").length > 0) {
alert($("#changePasswordResult").text());
}
});
</script>
</head>
<body style="text-align:center;">
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
<a href="login.jsp" name="login">去登录</a>
<a href="register.jsp" name="register">跳转注册</a>
<%
} else {
%>
<div style="text-align:center">
当前用户:<%=user.getUsername() %>
<a href="exit.jsp" name="exit">退出登录</a>
<a href="login_success.jsp" name="success">返回</a><br>
<h1>修改密码</h1>
</div>
<form action="UpdateInfoServlet" method="post">
<input type="hidden" name="username" value=<%=user.getUsername() %>>
<table align="center">
<tr>
<td>旧密码:</td>
<td><input type="password" id="oldPassword" name="oldPassword"></td>
</tr>
<tr>
<td>新密码:</td>
<td><input type="password" id="newPassword" name="newPassword"></td>
</tr>
</table>
<table align="center" cellspacing="12">
<tr>
<td align="left"><input type="submit" value="提交"></td>
<td align="left"><a href="exit.jsp" name="exit2">退出登陆</a></td>
</tr> </table>
</form>
<%
Object result = request.getAttribute("changePasswordResult");
if (result != null) {
%>
<div style="text-align:center">
<br/>
<h2><%=(String)result%></h2>
</div>
<%
}
%>
<%}%>
</body>
</html>
web.xml:欢迎页和servlet配置映射
将欢迎页设置为登录页;
Servlet 3.0 版本以上,在servlet文件中以*@WebServlet("/LoginServlet")*的形式即可完成配置;在低版本的Servlet中,需要按如下格式配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>UserManager</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UpdateInfoServlet</servlet-name>
<servlet-class>servlet.UpdateInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateInfoServlet</servlet-name>
<url-pattern>/UpdateInfoServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>AddInfoServlet</servlet-name>
<servlet-class>servlet.AddInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddInfoServlet</servlet-name>
<url-pattern>/AddInfoServlet</url-pattern>
</servlet-mapping>
</web-app>
系统功能展示
Demo Vedio of UM System
版权归原作者 Evanpatchouli℃ 所有, 如有侵权,请联系我们删除。