目录
开发工具及开发环境
WEB系统注册与登录功能模块需求
1.1 注册功能
1.2 登录功能
登陆时的过程:
1.3 填写补充信息功能
1.3 查看注册信息功能
1.4 修改用户信息功能
1.5 用户退出
1.6 其它功能
项目流程结构及源码
项目编写的流程(参考)
系统功能展示
Eclipse EE、Mysql、Navicat for MySQL、Tomcat-9.0.60、windows 10系统
(1)真实姓名,必填,只能包含不含空格的2-4个中文字符,或20个字符以内的英文字符
(2)电话号码,选填,11位数字
(3)出生年份与日期,必填,允许输入格式包括1977-12-14,或1977年12月14日。年份最早不能早于1900年,最晚不能晚于填写当天
如:JSP课设-Evanpatchouli℃-2021-6-17/11:07
1.项目文件结构
2.jar包
3.数据库表结构
基本的表结构如图,各属性由实际要求所定
(用户名主键的同时,将email设置为唯一索引,保证两者都不重复)
一、根据需求,建立数据库和表
使用navicat的sql可视化界面:
1.建立连接
如下图所示,点击“连接”,创建主机名localhost,埠3306的连接(连接名不设置,默认为localhost_3306)
用户名和密码自己设置,测试连接成功即可(我的设置为root, root)
2.建立数据库
如下图所示,右键连接名创建数据库,设置数据库名为usermanager,字符集为UTF8(防止存入中文字符导致乱码)
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" %>
<%@ page import="java.time.LocalDate" %>
Show time
各个页面都需要进行登录检测,以防未登录,框架如下:不同页面为迎合自己的功能会有略改。
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
去登录
跳转注册
<%
} 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" %>
用户注册
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" %>
注册成功
注册成功!
跳转登录
继续注册
register_fail.jsp:注册失败页
显示注册失败字样,从RegisterServlet接收并显示失败原因;内含1个链接跳转到注册页。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="time.jsp" %>
注册失败
注册失败!
<%
if(request.getAttribute("message")!= null){
out.print(request.getAttribute("message"));
}
%>
重新注册
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" %>
用户登陆
<%!
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) {
%>
登录页面
跳转注册
<%
} else {
%>
<%
User u = (User)obj;
%>
用户:<%=u.getUsername() %>
您已经登录,无需再登录
退出登录
返回
<%}%>
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" %>
登陆成功
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
去登录
跳转注册
<%
} else {
%>
<%--登录成功!
--%>
登录成功!
<%
String username = user.getUsername();
session.setAttribute("user", user);
%>
欢迎您:<%=username %>
显示信息
信息补充
退出登录
<%}%>
defeat.jsp:登录失败页
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="time.jsp" %>
登录失败
登录失败!
<%
if(request.getAttribute("message")!= null){
out.print(request.getAttribute("message"));
}
%>
重新登录
exit.jsp:退出登录
先获取当前登录的用户名,存到预置用户名内,然后销毁session
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="domain.User" %>
退出登录
<%
Object obj = session.getAttribute("user");
User u = (User)obj;
String unameLogined = (String)u.getUsername();
System.out.println(unameLogined);
session.invalidate();
%>
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" %>
显示用户信息
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
去登录
跳转注册
<%
} else {
%>
用户注册信息表
用户名
密码
邮箱
单位
注册时间
<%=user.getUsername()%>
<%=user.getPassword()%>
<%=user.getEmail()%>
<%=user.getUnit()%>
<%=user.getRegistertime()%>
用户补充信息表
真名
电话
生日
<%=user.getRealname()%>
<%=user.getPhone()%>
<%=user.getBirth()%>
修改密码
<%}%>
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"%>
<%@ page import="domain.User" %>
<%@ include file="time.jsp" %>
补充信息
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
去登录
跳转注册
<%
} else {
%>
<%
Object result = request.getAttribute("AddInfoResult");
if (result != null) {
%>
<%=(String)result%>
<%
}
%>
<%}%>
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.*" %>
修改密码
<%
Object obj = session.getAttribute("user");
User user = (User)obj;
if(null==obj) {
%>
您尚未登陆,请登录!
去登录
跳转注册
<%
} else {
%>
<%
Object result = request.getAttribute("changePasswordResult");
if (result != null) {
%>
<%=(String)result%>
<%
}
%>
<%}%>
web.xml:欢迎页和servlet配置映射
将欢迎页设置为登录页;
Servlet 3.0 版本以上,在servlet文件中以@WebServlet("/LoginServlet")的形式即可完成配置;在低版本的Servlet中,需要按如下格式配置web.xml文件
UserManager
login.jsp
LoginServlet
servlet.LoginServlet
LoginServlet
/LoginServlet
RegisterServlet
servlet.RegisterServlet
RegisterServlet
/RegisterServlet
UpdateInfoServlet
servlet.UpdateInfoServlet
UpdateInfoServlet
/UpdateInfoServlet
AddInfoServlet
servlet.AddInfoServlet
AddInfoServlet
/AddInfoServlet
Demo Vedio of UM System