javaWeb项目介绍:
- 1、没有使用maven
- 2、使用注解加文件配置xml(只配置了错误页面)方式
- 3、只是用一个index.jsp页面配合js来完成整个项目,
- 4、使用原生js、axios方式请求数据
- 5、项目不完善,只适合javaWeb初级项目,可以练练手
- 6、…
项目gif图片
零、Tomcat服务器
1、下载和注意事项
- 可以在官网下载,但是速度太慢了👉官网
- 推荐使用镜像网站下载👉镜像网站
- 请注意各个版本对应的jdk版本
- 注意:
- 1 若版本为10.1.x则jdk最低为11,否则tomcat启动不了
- 2 要解压在没有中文字符的文件夹中
2、文件夹介绍
- bin文件夹 👉可执行文件
- conf文件夹👉全局配置文件
- lib文件夹👉依赖的jar包
- logs文件夹👉存放tomcat运行日志
- temp文件夹👉临时文件夹
- webapps文件夹👉放项目之地
- work 文件夹👉
一、 数据库
1、新建数据库weblibrary
create database weblibrary charset utf8;
use weblibrary;
2、创建用户表lbuser
# 用户表
create table if not exists lbUser(
id int primary key auto_increment,#编号
uid varchar(30) unique not null default '',#账号
uname varchar(50) default '',#用户名
upwd varchar(32) not null default '',#密码:md5加密
uage int default 18,#年龄
uphone char(11) default '', #电话
uquestion varchar(50) default '',#密保问题
uanwser varchar(50) default ''#密保答案
) charset utf8;
3、创建图书表books
create table books(
id int primary key auto_increment,#编号
bname varchar(50) not null default '',#书名
bwriter varchar(30) not null default '',#书作者
btype varchar(30)not null default '',#书的类型
bcomny varchar(30) not null default '',#书的出版社
bnum int default 0,#书的数量
bstate int default 0, #书的状态:0还有库存,1,已借完
bbnum int default 0#被借的次数,可用来统计书的排行榜
);
insert into weblibrary.books (id, bname, bwriter, btype, bcomny, bnum, bstate, bbnum)
values (1, '小王子', '埃克苏佩里', '童话', '光明出版社', 8, 0, 6),
(2, '天路历程', '约翰班杨', '文学', '光明出版社', 10, 0, 13),
(3, '活着', '余华', '文学', '光明出版社', 8, 0, 6),
(4, '岛上书店', '加泽文', '文学', '光明出版社', 10, 0, 0),
(5, '吞噬星空', '我吃西红柿', '小说', '阅文集团', 10, 0, 21),
(6, '平凡的世界', '路遥', '文学', '光明出版社', 10, 0, 0),
(7, '雨有时横着走', '郭怀宽', '诗歌', '光明出版社', 10, 0, 10),
(8, '百年孤独', '加西亚马尔科', '小说', '光明出版社', 10, 0, 0),
(9, '三体', '刘慈欣', '小说', '光明出版社', 1, 0, 54),
(10, '斗罗大陆', '唐家三少', '小说', '阅文集团', 0, 0, 79);
4、创建用户借阅表borrhistory
create table borrhistory(
id int primary key auto_increment,#编号
uid varchar(11),#用户编号
bid int not null ,#书的唯一编号
bname varchar(30) not null default '',#书名
bwriter varchar(30) not null default '',#作者
btype varchar(30) not null default '',#类型
btime datetime,#借阅时间
rtime datetime,#归还时间
bstate int default 0#状态:0在读,1归还
);
二、开始建javaWeb项目
0、导入jar包:在WEB-INF下的lib包中导入相应的jar包
1、包的目录
2、在utils包中创建
a、创建db.properties
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/weblibrary?serverTimeZone=Asia/ShangHai
#?????
username=root
#??
password=123456
#?????
initialSize=10
# ??????
maxActive=100
# ??????
maxWait=3000
b、创建JDBCDruid.java
public class JDBCDruid {
private static DataSource ds=null;
//初始化数据
static {
try {
Properties p=new Properties();
p.load(new InputStreamReader(JDBCDruid.class.getClassLoader().getResourceAsStream("com/liu/libraryOS/utils/db.properties")));
ds= DruidDataSourceFactory.createDataSource(p);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取connection连接
* @return
*/
public static Connection getConn(){
try {
return ds.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 关闭方法
* @param rs
* @param st
* @param conn
*/
public static void getClose(ResultSet rs, Statement st,Connection conn){
try {
if (rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
3、在pojo包中创建
a、创建Books.java类
public class Books implements Serializable {
/**
* 书的唯一编号
*/
private Integer id;
/**
* 书的名字
*/
private String bname;
/**
* 书的作者
*/
private String bwriter;
/**
* 书的类型
*/
private String btype;
/**
* 出版社
*/
private String bcomny;
/**
* 在库的数量
*/
private Integer bnum;
/**
* 书的状态:0有库存,1已借完
*/
private Integer bstate;
/**
* 被借的次数:可用来统计排行榜
*/
private Integer bbnum;
public Books() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public String getBwriter() {
return bwriter;
}
public void setBwriter(String bwriter) {
this.bwriter = bwriter;
}
public String getBtype() {
return btype;
}
public void setBtype(String btype) {
this.btype = btype;
}
public String getBcomny() {
return bcomny;
}
public void setBcomny(String bcomny) {
this.bcomny = bcomny;
}
public Integer getBnum() {
return bnum;
}
public void setBnum(Integer bnum) {
this.bnum = bnum;
}
public Integer getBstate() {
return bstate;
}
public void setBstate(Integer bstate) {
this.bstate = bstate;
}
public Integer getBbnum() {
return bbnum;
}
public void setBbnum(Integer bbnum) {
this.bbnum = bbnum;
}
}
b、创建借阅历史类BorrHistory.java
public class BorrHistory implements Serializable {
/**
* 编号
*/
private Integer id;
/**
* 用户账号
*/
private String uid;
/**
* 书的唯一编号
*/
private Integer bid;
/**
* 书名
*/
private String bname;
/**
* 作者
*/
private String bwriter;
private String btype;
/**
* 借阅时间
*/
private String btime;
/**
* 归还时间
*/
private String rtime;
/**
* 状态:0:在读,1:已还
*/
private String bstate;
public BorrHistory() {
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getBid() {
return bid;
}
public void setBid(Integer bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public String getBwriter() {
return bwriter;
}
public void setBwriter(String bwriter) {
this.bwriter = bwriter;
}
public String getBtype() {
return btype;
}
public void setBtype(String btype) {
this.btype = btype;
}
public String getBtime() {
return btime;
}
public void setBtime(String btime) {
this.btime = btime;
}
public String getRtime() {
return rtime;
}
public void setRtime(String rtime) {
this.rtime = rtime;
}
public String getBstate() {
return bstate;
}
public void setBstate(String bstate) {
this.bstate = bstate;
}
}
c、创建用户类LbUser
public class LbUser implements Serializable {
/**
* 用户编号:自增长
*/
private Integer id;
/**
* 账号:手机号注册
*/
private String uid;
/**
* 昵称
*/
private String uname;
/**
* 年龄
*/
private int uage;
/**
* 密保问题
*/
private String uquestion;
/**
* 密保答案
*/
private String uanwser;
/**
* 注册时间
*/
private String udate;
public LbUser() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getUage() {
return uage;
}
public void setUage(int uage) {
this.uage = uage;
}
public String getUquestion() {
return uquestion;
}
public void setUquestion(String uquestion) {
this.uquestion = uquestion;
}
public String getUanwser() {
return uanwser;
}
public void setUanwser(String uanwser) {
this.uanwser = uanwser;
}
public String getUdate() {
return udate;
}
public void setUdate(String udate) {
this.udate = udate;
}
}
4、在dao包中创建
a、创建父类BasicDao.java
public class BasicDao<T> {
private QueryRunner qr = new QueryRunner();
private Connection conn = null;
/**
* 根据sql获取所有符合的数据
*
* @param sql
* @param clazz
* @param obj
* @return
*/
public List<T> getAllData(String sql, Class<T> clazz, Object... obj) {
try {
conn = JDBCDruid.getConn();
return qr.query(conn, sql, new BeanListHandler<>(clazz), obj);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCDruid.getClose(null, null, conn);
}
}
/**
* 获取单个数据
*
* @param sql
* @param clazz
* @param obj
* @return
*/
public T getOneData(String sql, Class<T> clazz, Object... obj) {
try {
conn = JDBCDruid.getConn();
return qr.query(conn, sql, new BeanHandler<>(clazz), obj);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCDruid.getClose(null, null, conn);
}
}
/**
* 单个dml操作
*
* @param sql
* @param obj
* @return
*/
public boolean update(String sql, Object... obj) {
int num = 0;
try {
conn = JDBCDruid.getConn();
//开启事务
conn.setAutoCommit(false);
num = qr.update(conn, sql, obj);
//没发生异常则提交
conn.commit();
} catch (SQLException e) {
//发生异常回滚
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
throw new RuntimeException(e);
} finally {
JDBCDruid.getClose(null, null, conn);
}
return num>0;
}
//---------以下是同时进行多条dml操作时使用-----------
/**
* 1、开启事务,适用于多级操作(同时修改借阅记录,书的状态等)
*
* @return connection
*/
public Connection startTransaction() {
try {
conn = JDBCDruid.getConn();
conn.setAutoCommit(false);
return conn;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 3、数据回滚
*
* @param conn
*/
public void rollBack(Connection conn) {
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
b、创建BooksDao.java
public class BooksDao extends BasicDao<Books>{
}
c、创建BorrHistory.java
public class BorrHistoryDao extends BasicDao<BorrHistory>{
}
d、创建LbUser.java
public class LbUserDao extends BasicDao<LbUser>{
}
5、在service包下创建
a、创建BookService.java
public class BooksService {
private BooksDao bd = new BooksDao();
private String sql = "";
/**
* 获取所有图书信息
*
* @return
*/
public List<Books> getAllBook() {
sql = "select*from books where bnum>0";
return bd.getAllData(sql, Books.class);
}
/**
* 获取排行前五的书籍,根据被借的次数
*
* @return
*/
public List<Books> paiHangBook() {
sql = "select*from books where bbnum>0 order by bbnum desc limit 0,5";
return bd.getAllData(sql, Books.class);
}
/**
* 获取已被借完的书籍
*
* @return
*/
public List<Books> alreadyOverBook() {
sql = "select*from books where bnum<1 ";
return bd.getAllData(sql, Books.class);
}
/**
* 根据id得到数据
*
* @param bid
* @return
*/
public Books queryById(String bid) {
sql = "select*from books where id=?";
return bd.getOneData(sql, Books.class, bid);
}
}
b、创建BorrHistoryService
public class BorrHistoryService {
private BorrHistoryDao bd = new BorrHistoryDao();
private BooksService bs = new BooksService();
private String sql = "";
/**
* 获取所有符合条件的记录
*
* @return
*/
public List<BorrHistory> getAllData(String uid) {
sql = "select * from borrhistory where uid=?";
return bd.getAllData(sql, BorrHistory.class, uid);
}
/**
* 根据账号查询编号为id的书籍且没归还记录
*
* @return
*/
public BorrHistory queryByBidCo(String count, String bid) {
sql = "select*from borrhistory where uid=? and bid=? and bstate=0";
return bd.getOneData(sql, BorrHistory.class, count, bid);
}
/**
* 添加借阅记录
*
* @param count
* @param bid
* @return
*/
public boolean borrowBook(String count, String bid) {
Connection conn = bd.startTransaction();
QueryRunner qr = new QueryRunner();
int num = 0;
try {
//修改书籍数量语句
sql = "update books set bnum=(bnum-1) where id=?";
num = qr.update(conn, sql, bid);
if (num > 0) {
//添加记录
Books b = bs.queryById(bid);
sql = "insert into borrhistory(uid,bid,bname,bwriter,btype,btime) values (?,?,?,?,?,now())";
num = qr.update(conn, sql, count, bid, b.getBname(), b.getBwriter(), b.getBtype());
//模拟错误
// num=1/0;
//提交事务
conn.commit();
}
} catch (SQLException e) {
bd.rollBack(conn);
e.printStackTrace();
} finally {
JDBCDruid.getClose(null, null, conn);
}
return num > 0;
}
/**
* 书籍归还:修改借阅记录:状态、日期;books:数量加1,被借次数加1
*
* @param count
* @param bid
* @return
*/
public boolean updateBorrHistory(String count, String bid) {
Connection conn = bd.startTransaction();
QueryRunner qr = new QueryRunner();
int num = 0;
try {
//修改借阅状态
sql = "update borrhistory set bstate=1,rtime=now() where uid=? and bid=? and bstate=0";
num = qr.update(conn, sql, count, bid);
if (num > 0) {
//修改欧克
//修改图书的数量以及被借的次数
sql = "update books set bnum=(bnum+1),bbnum=(bbnum+1) where id=?";
num = qr.update(conn, sql, bid);
if (num > 0) {
conn.commit();
}
}
} catch (SQLException e) {
bd.rollBack(conn);
e.printStackTrace();
} finally {
JDBCDruid.getClose(null,null,conn);
}
return num>0;
}
}
c、创建LbUserService.java
public class LbUserService {
private LbUserDao ld=new LbUserDao();
private String sql="";
/**
* 根据账号密码查询
* @param count
* @param pwd
* @return
*/
public LbUser logInByPD(String count,String pwd){
sql="select * from lbuser where uid=? and upwd=md5(?)";
return ld.getOneData(sql,LbUser.class,count,pwd);
}
/**
* 根据账号查询是否存在
* @param count
* @return
*/
public LbUser queryByCount(String count){
sql="select * from lbuser where uid=?";
return ld.getOneData(sql,LbUser.class,count);
}
/**
* 修改用户信息
* @param count
* @param name
* @param age
* @return
*/
public boolean updatePerson(String count,String name,int age){
sql="update lbuser set uname=?,uage=? where uid=?";
return ld.update(sql,name,age,count);
}
/**
* 添加用户
* @param count
* @param name
* @param pwd
* @param ques
* @param anw
* @param date
* @return
*/
public boolean addPerson(String count,String name,String pwd,String ques,String anw,String date){
sql="insert into lbuser(uid,uname,upwd,uquestion,uanwser,udate) values(?,?,md5(?),?,?,?)";
return ld.update(sql,count,name,pwd,ques,anw,date);
}
/**
* 找回密码时:根据账号、密保问题及答案
* @return
*/
public LbUser queryOfFindPwd(String count,String ques,String anw){
sql="select *from lbuser where uid=? and uquestion=? and uanwser=?";
return ld.getOneData(sql,LbUser.class,count,ques,anw);
}
/**
* 找回密码时:根据账号修改密码
* @return
*/
public boolean updateOfFindPwd(String count,String pwd){
sql="update lbuser set upwd=MD5(?) where uid=?";
return ld.update(sql,pwd,count);
}
}
6、在servlet包下创建
a、创建GetBooksServlet.java(首页:数据展示)
@WebServlet("/getBooks")
public class GetBooksServlet extends HttpServlet {
private BooksService bs=new BooksService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("currPage",1);
resp.setContentType("text/html;charset=utf8");
PrintWriter w = resp.getWriter();
HashMap<String, Object> hs = new HashMap<>();
//判断session中是否存在,不存在再从数据库取
List<Books> liubooks =(List<Books>) session.getAttribute("liubooks");
if(liubooks==null || liubooks.size()<1){
liubooks=bs.getAllBook();
session.setAttribute("liubooks",liubooks);
}
hs.put("code",200);
hs.put("msg","ok");
hs.put("data",liubooks);
String rs = JSONObject.toJSONString(hs);
w.write(rs);
w.close();
}
}
b、创建PaiHangServlet.java(图书排行)
@WebServlet("/paiHang")
public class PaiHangServlet extends HttpServlet {
private BooksService bs=new BooksService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
//有效时间1小时
session.setMaxInactiveInterval(1000*60*60);
session.setAttribute("currPage",2);
resp.setContentType("text/html;charset=utf8");
PrintWriter w = resp.getWriter();
HashMap<String, Object> hs = new HashMap<>();
List<Books> books =(List<Books>) session.getAttribute("paihang");
if(books==null ||books.size()<1){
books = bs.paiHangBook();
session.setAttribute("paihang",books);
}
hs.put("code",200);
hs.put("msg","ok");
hs.put("data",books);
String rs = JSONObject.toJSONString(hs);
w.write(rs);
w.close();
}
}
c、创建AlreadyOvServlet .java(已借完的书籍)
@WebServlet("/yiJieWan")
public class AlreadyOvServlet extends HttpServlet {
private BooksService bs=new BooksService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("currPage",3);
resp.setContentType("text/html;charset=utf8");
PrintWriter w = resp.getWriter();
HashMap<String, Object> hs = new HashMap<>();
List<Books> books =(List<Books>) session.getAttribute("yijiewan");
if(books==null){
books = bs.alreadyOverBook();
session.setAttribute("yijiewan",books);
}
hs.put("code",200);
hs.put("msg","ok");
hs.put("data",books);
String rs = JSONObject.toJSONString(hs);
w.write(rs);
w.close();
}
}
d、创建GetBorrowHistoryServlet .java(个人借阅历史,需要先登录)
@WebServlet("/getHistory")
public class GetBorrowHistoryServlet extends HttpServlet {
private BorrHistoryService bs=new BorrHistoryService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf8");
HttpSession session = req.getSession();
HashMap<String, Object> hs = new HashMap<>();
session.setAttribute("currPage",4);
PrintWriter w = resp.getWriter();
//这里先判断是否存在session,没有在操作数据库
//判断用户是否登录
LbUser user = (LbUser) session.getAttribute("userInf");
if(user==null){
//没登陆
hs.put("msg","notLogIn");
}else{//登录了
//查
List<BorrHistory> allData =(List<BorrHistory>) session.getAttribute("borrowhis"+user.getUid());
if(allData==null){
allData = bs.getAllData(user.getUid());
session.setAttribute("borrowhis"+user.getUid(),allData);
}
if(allData.size()==0){
hs.put("msg","kong");
}else{
hs.put("msg","ok");
hs.put("data",allData);
}
}
hs.put("code","200");
String s = JSONObject.toJSONString(hs);
w.write(s);
w.close();
}
}
e、创建LogInServlet .java(登录)
@WebServlet("/logIn")
public class LogInServlet extends HttpServlet {
private LbUserService ls=new LbUserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf8");
req.setCharacterEncoding("utf8");
PrintWriter w = resp.getWriter();
HttpSession session = req.getSession();
//设置最大时间24小时后失效
session.setMaxInactiveInterval(1000*60*60*24);
//设置当前页
session.setAttribute("currPage",5);
//获取前台发来的数据
String uid = req.getParameter("uid");
if(uid==null||"".equals(uid)){
setErr("手机号不能为空!",w);
return;
}else if(uid.length()!=11){
setErr("请输入11位的手机号!",w);
return;
}
//判断账号是否存在
LbUser isCun = ls.queryByCount(uid);
if(isCun==null){
setErr("errCount",w);
return;
}
String upwd = req.getParameter("upwd");
if(upwd==null||"".equals(upwd)){
setErr("密码不能为空!",w);
return;
}else if(upwd.length()<6||upwd.length()>18){
setErr("密码最少6位最多18位",w);
return;
}
//判断
LbUser user = ls.logInByPD(uid, upwd);
if(user==null){
setErr("errPwd",w);
return;
}
//存在时
setSuccess(user,w);
//添加session
session.setAttribute("userInf",user);
}
/**
* 用来返回成功信息
* @param user
* @param w
*/
private void setSuccess(LbUser user,PrintWriter w){
setResult(user,"ok",w);
}
/**
* 用来设置错误信息
* @param msg
* @param w
*/
private void setErr(String msg,PrintWriter w){
setResult(null,msg,w);
}
/**
* 用来返回信息的父类
* @param user
* @param msg
* @param w
*/
private void setResult( LbUser user, String msg, PrintWriter w){
HashMap<String, Object> hs = new HashMap<>();
hs.put("code","200");
hs.put("msg",msg);
hs.put("data",user);
String rs = JSONObject.toJSONString(hs);
w.write(rs);
w.close();
}
}
f、创建RegisterServlet .java(注册)
@WebServlet("/registerPerson")
public class RegisterServlet extends HttpServlet {
private LbUserService ls=new LbUserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf8");
HttpSession session = req.getSession();
HashMap<String, Object> hs = new HashMap<>();
session.setAttribute("currPage",5);
PrintWriter w = resp.getWriter();
//时间转换
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//获取前台传来的数据
String uid = req.getParameter("uid");
String upwd = req.getParameter("upwd");
String uname = req.getParameter("uname");
String uquestion = req.getParameter("uquestion");
String uanwser = req.getParameter("uanwser");
//先判断账号是否已经存在
LbUser us = ls.queryByCount(uid);
if(us!=null){
hs.put("msg","isAlready");
}else{
boolean b = ls.addPerson(uid, uname, upwd, uquestion, uanwser, sdf.format(new Date()));
if(!b){
hs.put("msg","addErr");
}else{
hs.put("msg","ok");
}
}
hs.put("code","200");
String s = JSONObject.toJSONString(hs);
w.write(s);
w.close();
}
}
g、创建UserInfoServlet .Java(个人中心)
@WebServlet("/userInfo")
public class UserInfoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf8");
HashMap<String, Object> hs = new HashMap<>();
PrintWriter w = resp.getWriter();
HttpSession session = req.getSession();
session.setAttribute("currPage",5);
LbUser use = (LbUser) session.getAttribute("userInf");
if(use==null){
hs.put("msg","kong");
}else{
hs.put("msg","ok");
}
hs.put("code",200);
hs.put("data",use);
String rs = JSONObject.toJSONString(hs);
w.write(rs);
w.close();
}
}
h、创建UpdateUser .java(修改)
@WebServlet("/updateInfo")
public class UpdateUser extends HttpServlet {
private LbUserService ls=new LbUserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf8");
req.setCharacterEncoding("utf8");
PrintWriter w = resp.getWriter();
HashMap<String, Object> hs = new HashMap<>();
HttpSession session = req.getSession();
//设置当前页
session.setAttribute("currPage",5);
String count = req.getParameter("count");
String name = req.getParameter("name");
String age = req.getParameter("age");
// String ques = req.getParameter("question");
// String ans = req.getParameter("answer");
//判断
//设置当前页
session.setAttribute("currPage",5);
boolean rs = ls.updatePerson(count, name, Integer.parseInt(age));
if(rs){
LbUser user = ls.queryByCount(count);
//ok
hs.put("msg","ok");
hs.put("data",user);
//更新session中的用户
session.setAttribute("userInf",user);
}else{
hs.put("msg"," errUpdate");
}
hs.put("code","200");
String s = JSONObject.toJSONString(hs);
w.write(s);
w.close();
}
}
i、创建FindPwdServlet.java(找回密码)
@WebServlet("/findPwd")
public class FindPwdServlet extends HttpServlet {
private LbUserService ls=new LbUserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf8");
HttpSession session = req.getSession();
HashMap<String, Object> hs = new HashMap<>();
session.setAttribute("currPage",5);
PrintWriter w = resp.getWriter();
//获取前台传来的数据
String uid = req.getParameter("uid");
String upwd = req.getParameter("upwd");
String uquestion = req.getParameter("uquestion");
String uanwser = req.getParameter("uanwser");
//判断账号是否存在
LbUser user = ls.queryByCount(uid);
if(user==null){
hs.put("msg","isNotCun");
}else{
//账号存在
//根据账号、密保以及答案查询
user= ls.queryOfFindPwd(uid,uquestion,uanwser);
if(user==null){
hs.put("msg","QOAIsErr");
}else{
//都正确
//修改密码
boolean b = ls.updateOfFindPwd(uid, upwd);
if(!b){
hs.put("msg","findErr");
}else{
hs.put("msg","ok");
}
}
}
hs.put("code","200");
String s = JSONObject.toJSONString(hs);
w.write(s);
w.close();
}
}
j、创建ReturnBookServlet.java(还书)
@WebServlet("/returnBook")
public class ReturnBookServlet extends HttpServlet {
private BorrHistoryService bs=new BorrHistoryService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("currPage",4);
resp.setContentType("text/html;charset=utf8");
PrintWriter w = resp.getWriter();
HashMap<String, Object> hs = new HashMap<>();
String bid = req.getParameter("bid");
//先判断用户是否已经登录
LbUser user =(LbUser) session.getAttribute("userInf");
if(user==null){
//提示没有登陆
hs.put("msg","isNotLogIn");
}else{
//查询此书是否借阅过且没归还
BorrHistory bht = bs.queryByBidCo(user.getUid(), bid);
if(bht==null){
//说明当前书籍不需要归还或已经归还
hs.put("msg","notHistory");
}else{
//说明可归还
boolean b = bs.updateBorrHistory(user.getUid(), bid);
if(!b){
//归还失败
hs.put("msg","returnErr");
}else{
hs.put("msg","ok");
//更新图书数据
session.removeAttribute("liubooks");
//更新当前用户借阅记录
session.removeAttribute("borrowhis"+user.getUid());
//更新排行
session.removeAttribute("paihang");
//更新已借完session
session.removeAttribute("yijiewan");
}
}
}
hs.put("code","200");
String s = JSONObject.toJSONString(hs);
w.write(s);
w.close();
}
}
k、创建GetBorrowHistoryServlet.java (个人借阅历史)
@WebServlet("/getHistory")
public class GetBorrowHistoryServlet extends HttpServlet {
private BorrHistoryService bs=new BorrHistoryService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf8");
HttpSession session = req.getSession();
HashMap<String, Object> hs = new HashMap<>();
session.setAttribute("currPage",4);
PrintWriter w = resp.getWriter();
//这里先判断是否存在session,没有在操作数据库
//判断用户是否登录
LbUser user = (LbUser) session.getAttribute("userInf");
if(user==null){
//没登陆
hs.put("msg","notLogIn");
}else{//登录了
//查
List<BorrHistory> allData =(List<BorrHistory>) session.getAttribute("borrowhis"+user.getUid());
if(allData==null){
allData = bs.getAllData(user.getUid());
session.setAttribute("borrowhis"+user.getUid(),allData);
}
if(allData.size()==0){
hs.put("msg","kong");
}else{
hs.put("msg","ok");
hs.put("data",allData);
}
}
hs.put("code","200");
String s = JSONObject.toJSONString(hs);
w.write(s);
w.close();
}
}
l、创建GoOutServlet .java(退出)
@WebServlet("/goOut")
public class GoOutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf8");
HttpSession session = req.getSession();
HashMap<String, Object> hs = new HashMap<>();
session.setAttribute("currPage",5);
PrintWriter w = resp.getWriter();
//先判断用户是否已经登陆
LbUser user = (LbUser) session.getAttribute("userInf");
if(user!=null){
hs.put("msg","ok");
session.removeAttribute("userInf");
}else{
hs.put("msg","notLogIn");
}
hs.put("code","200");
String s = JSONObject.toJSONString(hs);
w.write(s);
w.close();
}
}
7、在web包下的static包创建
a、创建css包,包下创建index.css
* {
padding: 0;
margin: 0;
}
body {
min-width: 1200px;
height: 800px;
}
#liu {
width: 70%;
height: 70%;
margin: 20px auto auto auto;
font-size: 18px;
}
#liu-head {
width: 100%;
height: 50px;
background-color: #ead2ae;
color: blueviolet;
font-size: 18px;
font-weight: bold;
border-radius: 10px;
}
#liu-head ul {
text-align: center;
width: 100%;
list-style: none;
display: inline-block;
line-height: 45px;
margin: 2px auto;
}
#liu-head ul li {
cursor: pointer;
margin-left: 10px;
border: #ed00ff 1px solid;
border-radius: 15px;
/*background-color: yellow;*/
text-align: center;
width: 20%;
float: left;
}
#liu-head ul li:last-child {
width: 10%;
border-radius: 10px 40px;
}
#liu-head ul li:hover {
background-color: #dc8ef1;
}
#liu-middle {
width: 100%;
height: 85%;
margin: 10px auto;
border: black 1px solid;
border-radius: 10px;
background-color: #ead2ae;
/*background-color: rebeccapurple;*/
}
#biao {
margin: 2px auto;
width: 98%;
text-align: center;
border-collapse: collapse;
border-spacing: 0px;
}
#biao-head{
background-color: #00a290;
}
#biao tr {
border: #000000 1px solid;
line-height: 40px;
}
#biao-body tr:hover {
background-color: #c4ffde;
cursor: pointer;
}
#biao-body input {
margin: 2px auto;
line-height: 40px;
width: 60px;
border: yellow 1px solid;
border-radius: 5px;
font-size: 18px;
color: #af4ed8;
background-color: transparent;
cursor: pointer;
}
#biao-body input:hover {
font-size: 17px;
}
/*个人中心*/
#user-info {
width: 85%;
height: 85%;
/*background-color: #1bc4fb;*/
margin: 30px auto;
position: relative;
text-align: center;
}
#user-info b {
color: red;
margin: 0;
padding: 0;
}
#uinfo {
width: 90%;
height: 90%;
/*background-color: #0ae29e;*/
position: absolute;
margin: 10px auto;
left: 5%;
text-align: center;
font-size: 25px;
}
#uinfo input {
color: #b118f1;
width: 50%;
height: 35px;
text-align: center;
font-size: 25px;
margin: 5px auto;
outline: none;
border: #5a9237 2px solid;
background-color: transparent;
border-radius: 5px;
cursor: pointer;
}
#uinfo #count { /*个人中心第一个input框*/
color: #c27ede;
}
#uinfo span {
color: #975403;
font-weight: bold;
}
#uinfo button {
width: 30%;
background-color: transparent;
line-height: 40px;
font-size: 20px;
border: #ff8901 1px solid;
display: inline-block;
float: right;
margin-right: 3%;
border-radius: 50px 20px;
color: #036d2e;
cursor: pointer;
margin-top: 5px;
}
#uinfo button:last-child {
width: 15%;
float: left;
margin-left: 10px;
color: #db9090;
}
/*登陆css*/
#login-div {
width: 35%;
height: 60%;
border: #ac6b00 2px dashed;
border-radius: 5px;
/*background-color: #0ae29e;*/
margin: 50px auto;
position: relative;
}
#login-div span {
display: inline-block;
font-size: 18px;
color: red;
width: 100%;
height: 20px;
line-height: 20px;
text-align: center;
}
#login-div input {
width: 90%;
height: 40px;
color: #e13cd7;
font-size: 25px;
text-align: center;
margin: 5px 10px;
border-radius: 20px;
border: #158579 2px dotted;
background-color: transparent;
outline: none;
}
#login-div #login-dl {
width: 90%;
height: 40px;
margin-top: 30px;
margin-left: 10px;
border-radius: 20px;
border: #e77070 1px solid;
background-color: transparent;
font-size: 24px;
line-height: 40px;
color: #067221;
}
#login-div #login-bottom {
width: 95%;
height: 30px;
border: #f323f3 1px dotted;
/*background-color: transparent;*/
position: absolute;
border-radius: 15px 3px;
font-size: 14px;
font-style: italic;
margin: auto 2%;
color: #9f4e02;
bottom: 5px;
}
#login-div #login-bottom ul {
list-style: none;
width: 100%;
height: 100%;
}
#login-div #login-bottom ul li {
width: 50%;
text-align: center;
height: 100%;
line-height: 30px;
display: inline-block;
}
#login-div #login-bottom ul li a {
width: 100%;
height: 100%;
/*background-color: #0ae29e;*/
text-decoration: none;
cursor: pointer;
}
/*注册css*/
#register-div {
width: 50%;
height: 70%;
/*background-color: #1bc4fb;*/
margin: 5% auto;
border: #176f00 2px dotted;
border-radius: 50px 10px;
}
#register-div span {
display: inline-block;
width: 80%;
font-size: 18px;
height: 25px;
line-height: 25px;
text-align: center;
color: #f80000;
/*background-color: yellow;*/
margin: auto 8%;
}
#register-div input {
display: inline-block;
width: 80%;
height: 30px;
text-align: center;
font-size: 20px;
margin: 5px 8%;
border: #9b0058 1px dotted;
background-color: transparent;
outline: none;
border-radius: 10px;
color: #b118f1;
}
#register-div select {
color: #b118f1;
display: inline-block;
width: 80%;
height: 30px;
text-align: center;
font-size: 20px;
margin: 5px 8%;
border: #9b0058 1px dotted;
background-color: transparent;
outline: none;
border-radius: 10px;
}
#register-div button {
color: #0280ce;
display: inline-block;
width: 60%;
height: 30px;
text-align: center;
font-size: 20px;
margin: 5% 18% 4% 18%;
border: #00489b 2px dotted;
background-color: transparent;
outline: none;
border-radius: 10px;
line-height: 25px;
cursor: pointer;
}
#register-div a {
display: inline-block;
width: 25%;
height: 20px;
font-size: 14px;
font-style: italic;
/*background-color: red;*/
margin: auto 5px;
color: #278d02;
}
/*找密码css*/
#findPwd-div {
width: 50%;
height: 70%;
/*background-color: #1bc4fb;*/
margin: 5% auto;
border: #176f00 2px dotted;
border-radius: 50px 10px;
}
#findPwd-div span {
display: inline-block;
width: 80%;
font-size: 18px;
height: 25px;
line-height: 25px;
text-align: center;
color: #f80000;
/*background-color: yellow;*/
margin: auto 8%;
}
#findPwd-div input {
display: inline-block;
width: 80%;
height: 30px;
text-align: center;
font-size: 20px;
margin: 5px 8%;
border: #9b0058 1px dotted;
background-color: transparent;
outline: none;
border-radius: 10px;
color: #b118f1;
}
#findPwd-div select {
color: #b118f1;
display: inline-block;
width: 80%;
height: 30px;
text-align: center;
font-size: 20px;
margin: 5px 8%;
border: #9b0058 1px dotted;
background-color: transparent;
outline: none;
border-radius: 10px;
}
#findPwd-div button {
color: #0280ce;
display: inline-block;
width: 60%;
height: 30px;
text-align: center;
font-size: 20px;
margin: 5% 18% 4% 18%;
border: #00489b 2px dotted;
background-color: transparent;
outline: none;
border-radius: 10px;
line-height: 25px;
cursor: pointer;
}
#findPwd-div a {
display: inline-block;
width: 25%;
height: 20px;
font-size: 14px;
font-style: italic;
/*background-color: red;*/
margin: auto 5px;
color: #278d02;
}
b、创建err包,包下创建
- 404.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>404-迷失方向了</title>
</head>
<body>
<h1 id="one" style="text-align: center">怎么回事,灯怎么熄灭了,害得我迷失了方向</h1>
<script type="text/javascript">
let one = document.getElementById("one");
let str=one.innerText;
let tim=5;
setInterval(function () {
one.innerText=str+"("+tim+")";
if(tim==0){
location.href="../..";
}
tim--;
},1000);
</script>
</body>
</html>
- 500.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>500-出现bug了</title>
</head>
<body>
<h1 id="one" style="text-align: center">这是怎么了,为什么我从座位上掉下来了?</h1>
<script type="text/javascript">
let one = document.getElementById("one");
let str=one.innerText;
let tim=5;
setInterval(function () {
one.innerText=str+"("+tim+")";
if(tim==0){
location.href="../..";
}
tim--;
},1000);
</script>
</body>
</html>
8、在web包下的WEB_INF包创建
a、创建lib包,此包放jar包
b、修在web.xml文件中 添加
<error-page>
<error-code>404</error-code>
<location>/static/err/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/static/err/500.jsp</location>
</error-page>
9、在web包下的index.jsp(一切操作都在这里面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>楠小弟自助图书馆</title>
</head>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="static/css/index.css">
<body>
<div id="liu">
<!--头部-->
<div id="liu-head">
<ul>
<li id="head-1">自助图书系统</li>
<li id="head-2">图书排行榜</li>
<li id="head-3">暂空缺书籍</li>
<li id="head-4">借阅记录</li>
<li id="head-5">登录</li>
</ul>
</div>
<!--中间-->
<div id="liu-middle">
</div>
</div>
<script type="text/javascript" charset="UTF-8">
//第一部分:标题头
//let lhead = document.getElementById("liu-head");
let head1 = document.getElementById("head-1");
let head2 = document.getElementById("head-2");
let head3 = document.getElementById("head-3");
let head4 = document.getElementById("head-4");
let head5 = document.getElementById("head-5");
//第二部分中间div
let middleBody = document.getElementById("liu-middle");
//第一页:展示数据
function showOne() {
//表格
middleBody.innerHTML = '<table id="biao"><thead id="biao-head"></thead><tbody id="biao-body"></tbody></table>';
//第二部分:表格头部thead
let bhead = document.getElementById("biao-head");
//第二部分:表格身体tbody
let bbody = document.getElementById("biao-body")
//表头
bhead.innerHTML = "<tr><td>书名</td><td>作者</td><td>类型</td><td>出版社</td><td>库存</td><td>状态</td><td>操作</td></tr>";
//请求数据
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/getBooks',
params: {}
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
alert('获取数据失败!');
bbody.innerHTML = "<b style='font-size: 20px;color: red;text-align: center'>图书资源获取失败,请联系楠小弟!</b>"
return
}
//这里获取到了
//添加数据
let htm = "";
for (let i = 0; i < d.data.length; i++) {
let t = d.data[i];
htm += ("<tr><td>"
+ t.bname + "</td><td>" + t.bwriter
+ "</td><td>" + t.btype
+ "</td><td>" + t.bcomny
+ "</td><td>" + t.bnum
+ "</td><td>" + (t.bstate == 0 ? "可借阅" : "已借完")
+ "</td><td><input type='button' id='sjieyue' οnclick='sjieY("+t.id+")' title='" + t.id + "' value='借阅'></td></tr>");
}
bbody.innerHTML = htm;
});
}
//第一页,借阅功能
function sjieY(id) {
let jy = document.getElementById("sjieyue");
let b = confirm("确定借阅此书吗?");
if(!b){
return;
}
//确认
axios({
method:'post',
url:'http://localhost:8080${pageContext.request.contextPath}/borrowBook',
params:{
bid:id
}
}).then(function (rs) {
let d=rs.data
if(d.code!='200'){
alert("借书时,请求异常");
return;
}
if(d.msg=='isNotLogIn'){
alert("请登陆后再来借阅!");
return;
}else if(d.msg=='isNotReturn'){
alert("上次借的这本书还没有归还哦!");
return;
}else if(d.msg=='jieYueErr'){
alert("借阅失败啦,请联系工作人员!");
return;
}else if(d.msg=='ok'){
alert("借阅成功,看完别忘记归还哦!");
showOne();
return;
}
});
}
//第二页:图书排行
function paiHTwo() {
//表格
middleBody.innerHTML = '<table id="biao"><thead id="biao-head"></thead><tbody id="biao-body"></tbody></table>';
//第二部分:表格头部thead
let bhead = document.getElementById("biao-head");
//第二部分:表格身体tbody
let bbody = document.getElementById("biao-body")
//编写表头
bhead.innerHTML = "<tr><td>排名</td><td>书名</td><td>作者</td><td>类型</td><td>状态</td><td>被借次数</td></tr>";
//请求数据
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/paiHang',
params: {}
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
alert("数据获取失败!")
return;
}
//下面是获取到了数据
//不为空
let htm = "";
for (let i = 0; i < d.data.length; i++) {
let t = d.data[i];
htm += "<tr><td>" + (i + 1) + "</td><td>" + t.bname
+ "</td><td>" + t.bwriter + "</td><td>"
+ t.btype + "</td><td>"
+ (t.bnum >= 1 ? "可借阅" : "已借完")
+ "</td><td>" + t.bbnum + "</td></tr>";
}
//判断是否为空
if (d.data.length == 0) {
htm = "<tr style='color: red;font-style: italic;'><td></td><td></td><td>店铺刚开张,</td><td>暂未产生数据,</td><td>请稍后再来!</td><td></td></tr>";
}
bbody.innerHTML = htm;
});
}
//第三页:已借完的书籍
function kongQThree() {
//表格
middleBody.innerHTML = '<table id="biao"><thead id="biao-head"></thead><tbody id="biao-body"></tbody></table>';
//第二部分:表格头部thead
let bhead = document.getElementById("biao-head");
//第二部分:表格身体tbody
let bbody = document.getElementById("biao-body")
bhead.innerHTML = "<tr><td>书名</td><td>作者</td><td>类型</td><td>出版社</td><td>库存</td><td>状态</td></tr>";
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/yiJieWan'
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
alert("拉取数据失败!")
bbody.innerHTML = "<b style='font-size: 20px;color: red;text-align: center'>数据拉取失败,请联系楠小弟!</b>"
return;
}
//下面是获取到了数据
let htm = "";
for (let i = 0; i < d.data.length; i++) {
let t = d.data[i];
htm += "<tr><td>" + t.bname + "</td><td>" + t.bwriter
+ "</td><td>" + t.btype + "</td><td>" + t.bcomny
+ "</td><td>" + t.bnum + "</td><td>" + (t.bnum >=1 ? "可借阅" : "已借完")
+ "</td></tr>";
}
//判断是否为空
if (d.data.length == 0) {
htm = "<tr style='color: red;font-style: italic;'><td></td><td></td><td>所有图书,</td><td>都可正常</td><td>借阅观看哦!</td><td></td></tr>";
}
bbody.innerHTML = htm;
});
}
//第四页:借阅记录
function jieYueHistory() {
//表格
middleBody.innerHTML = '<table id="biao"><thead id="biao-head"></thead><tbody id="biao-body"></tbody></table>';
//第二部分:表格头部thead
let bhead = document.getElementById("biao-head");
//第二部分:表格身体tbody
let bbody = document.getElementById("biao-body")
//表头
bhead.innerHTML = "<tr><td>书名</td><td>作者</td><td>类型</td><td>借阅时间</td><td>归还时间</td><td>书籍状态</td><td>操作</td></tr>";
//请求数据
//请求数据
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/getHistory',
params: {}
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
alert('获取历史记录数据失败!');
return
}
let htm = "";
if(d.msg=='notLogIn'){
htm = "<tr style='color: red;font-style: italic;'><td></td><td></td><td>你还没有登陆,</td><td>请登陆后,</td><td>再来查看!</td><td></td></tr>";
bbody.innerHTML = htm;
alert("请登录后在来查看!");
return;
}
if (d.msg == 'kong') {
htm = "<tr style='color: red;font-style: italic;'><td></td><td></td><td>你还未借阅,</td><td>借阅的历史,</td><td>将在此展示!</td><td></td></tr>";
bbody.innerHTML = htm;
return;
}
//这里获取到了
//添加数据
for (let i = 0; i < d.data.length; i++) {
let t = d.data[i];
htm += ("<tr><td>"
+ t.bname + "</td><td>" + t.bwriter
+ "</td><td>" + t.btype
+ "</td><td title='"+t.btime+"'>" + t.btime.substring(0,10)
+ "</td><td title='"+(t.rtime==null?"-":t.rtime)+"'>" + (t.rtime==null?"-":t.rtime.substring(0,10))
+ "</td><td>" + (t.bstate == 0 ? "在读" : "已归还")
+ "</td><td><input type='button' οnclick='returnBook(" + t.bid + ")' title='" + t.bstate + "' value='"+(t.bstate == 0 ? "归还" : "已归还")+"'></td></tr>");
}
bbody.innerHTML = htm;
let inp = bbody.getElementsByTagName("input");
for (let e of inp) {
if(e.title>0){
e.disabled=true;
}else{
e.disabled=false;
}
}
});
}
//图书归还
function returnBook(bid) {
let b = confirm("确认要归还当前的书籍吗?");
if(!b){
return;
}
axios({
method:'post',
url:'http://localhost:8080${pageContext.request.contextPath}/returnBook',
params:{
bid:bid
}
}).then(function (rs) {
let d=rs.data;
if(d.code!='200'){
alert("归还书籍时,请求异常!");
return;
}
if(d.msg=='isNotLogIn'){
alert("请登陆后再来操作!");
return;
}else if(d.msg=='notHistory'){
alert("当前书籍已经归还了!");
return;
}else if(d.msg=='returnErr'){
alert("还书失败了!!");
return;
}else if(d.msg=='ok'){
alert("还书成功!!")
jieYueHistory();
}
});
}
//第五页:个人中心
function personZone(per) {
if (per == null) {
return;
}
//获取用户姓名并展示出来
let na = per.uname;
if (na.length > 3) {
na = na.substring(0, 3) + "...";
}
head5.innerText = na;
let htm = '<div id="user-info"><b id="up-msg"></b><div id="uinfo">' +
'<span>账&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:</span><input id="count" type="text" readonly value=' + per.uid + '><br>' +
'<span>昵&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;称:</span><input id="uname" type="text" name="uname" value=' + per.uname + '><br>' +
'<span>年&nbsp;&nbsp;&nbsp; 龄:</span><input id="uage" type="number" name="uage" value=' + per.uage + '><br>' +
'<span>密保问题:</span><input type="text" readonly maxlength="50" id="question" name="question" value=' + per.uquestion + '><br>' +
'<span>密保答案:</span><input οnclick="showAnw()" type="password" readonly name="answer" id="answer" value=' + per.uanwser + '><br>' +
'<span>注册时间:</span><input type="text" readonly name="udate" id="udate" value=' + per.udate + '><br>' +
'<button οnclick="updatePerson()">修改当前信息</button><button οnclick="goOut()">退出登录</button>' +
'</div></div>';
middleBody.innerHTML = htm;
}
//登陆页面
function logining() {
let htm = '<div id="login-div">' + '<span id="login-msg"></span>' +
'<input id="login-count" οnkeyup="this.value=this.value.replace(/[^0-9]/g,'')" placeholder="手机号" type="text" maxlength="11"><br>' +
'<input id="login-pwd" placeholder="密码" maxlength="18" type="password" name="pwd"><br>' +
'<button οnclick="login_dl()" id="login-dl">登录</button><br>' +
'<div id="login-bottom"><ul><li><a οnclick="findPwd()">找回密码</a></li><li><a οnclick="registering()">注册账号</a></li></ul></div></div>';
middleBody.innerHTML = htm;
}
//点击登录时的数据交互
function login_dl() {
//提示信息
let lg_msg = document.getElementById("login-msg");
//账号
let lg_count = document.getElementById("login-count");
//密码
let lg_pwd = document.getElementById("login-pwd");
//登录按钮
let lg_dl = document.getElementById("login-dl");
//判断
if (lg_count.value.length != 11) {
lg_msg.innerText = "请输入有效的11位手机号";
showTime(lg_msg)
return;
}
if (lg_pwd.value.length < 6 || lg_pwd.value.length > 18) {
lg_msg.innerText = "密码最少6位最大18位";
showTime(lg_msg)
return;
}
//向后端发送数据,判断是否存在
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/logIn',
params: {
"uid": lg_count.value,
"upwd": lg_pwd.value
}
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
lg_msg.innerText = "登录时,请求数据异常!";
showTime(lg_msg)
return;
}
if (d.msg == 'errCount') {
lg_msg.innerText = "账号不存在,请检查!";
showTime(lg_msg)
return;
} else if (d.msg == 'errPwd') {
lg_msg.innerText = "密码不匹配!";
showTime(lg_msg)
return;
} else if (d.msg == 'ok') {
personZone(d.data);
} else {
lg_msg.innerText = d.msg;
showTime(lg_msg)
return;
}
});
}
//注册页面
function registering() {
let htm = '<div id="register-div"><span id="register-msg"></span>' +
'<input id="register-count" type="text" maxlength="11" οnkeyup="this.value=this.value.replace(/[^0-9]/g,'')" placeholder="请输入手机号"><br>' +
'<input id="register-name" type="text" maxlength="20" placeholder="起个响亮的名字"><br>' +
'<input id="register-pwd" type="password" maxlength="18" placeholder="请输入密码"><br>' +
'<select id="register-question"><option>你最喜欢的书籍</option><option>你最喜欢的游戏</option><option>你最喜欢的歌曲</option><option>你最喜欢的运动</option></select><br>' +
'<input id="register-anwser" type="text" maxlength="18" placeholder="密保答案"><br>' +
'<button οnclick="register_ok()">确认注册</button><br>' +
'<a href="javascript:void(0);" οnclick="logining()">已有账号?去登陆</a></div>';
middleBody.innerHTML = htm;
}
//注册页面数据交互
function register_ok() {
//获取注册页面的提示信息标签id
let reg_msg = document.getElementById("register-msg");
//获取需要的标签的值
let reg_count = document.getElementById("register-count").value;
let reg_name = document.getElementById("register-name").value;
let reg_pwd = document.getElementById("register-pwd").value;
let reg_ques = document.getElementById("register-question").value;
let reg_anw = document.getElementById("register-anwser").value;
//判断
if(reg_count.length!=11){
reg_msg.innerText="*请输入有效的11位手机号"
showTime(reg_msg);
return;
}else if(reg_name.length<1 || reg_name.length>20){
reg_msg.innerText="*昵称至少1个至多20个"
showTime(reg_msg);
return;
}else if(reg_pwd.length<6||reg_pwd.length>18){
reg_msg.innerText="*密码至少6位至多18位"
showTime(reg_msg);
return;
}else if(reg_ques.length<3||reg_ques.length>30){
reg_msg.innerText="*密保问题长度至少3位至多30位"
showTime(reg_msg);
return;
}else if(reg_anw.length<1 ||reg_anw.length>18){
reg_msg.innerText="*密保答案长度至少1位至多18位"
showTime(reg_msg);
return;
}
//询问用户是否注册
let isQ = confirm("确认注册吗?");
if(!isQ){
return;
}
//确认注册
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/registerPerson',
params: {
"uid": reg_count,
"upwd": reg_pwd,
"uname":reg_name,
"uquestion":reg_ques,
"uanwser":reg_anw
}
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
reg_msg.innerText = "注册时,请求数据异常!";
showTime(reg_msg)
return;
}
if (d.msg == 'isAlready') {
reg_msg.innerText = "当前账号已存在,可试着找回密码!";
showTime(reg_msg)
return;
} else if (d.msg == 'addErr') {
reg_msg.innerText = "注册失败啦!";
showTime(reg_msg)
return;
} else if (d.msg == 'ok') {
alert("注册成功,将跳转到登陆页面!");
logining();
} else {
reg_msg.innerText = d.msg;
showTime(reg_msg)
return;
}
});
}
//修改数据交互
function updatePerson() {
//提示信息
let up_msg = document.getElementById("up-msg");
let ucount = document.getElementById("count");
let uname = document.getElementById("uname");
let uage = document.getElementById("uage");
// let uquestion = document.getElementById("question");
// let uanswer = document.getElementById("answer");
//判断
if (uname.value.length < 1 || uname.value.length > 18) {
up_msg.innerText = "昵称最少一个最大18个字符";
showTime(up_msg);
return;
}
if (uage.value < 1 || uage.value > 100) {
up_msg.innerText = "请输入有效的年龄";
showTime(up_msg);
return;
}
// if (uquestion.value.length < 1 || uquestion.value.length > 25) {
// up_msg.innerText = "密保问题长度至少1个之多25个字符!";
// showTime(up_msg);
// return;
// }
// if (uanswer.value.length < 1 || uanswer.value.length > 25) {
// up_msg.innerText = "密保答案长度至少1个之多25个字符!";
// showTime(up_msg);
// return;
// }
//询问用户是否修改
let b = confirm("确认修改吗?");
if (!b) {
return;
}
//确认修改
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/updateInfo',
params: {
count: ucount.value,
name: uname.value,
age: uage.value
// question: uquestion.value,
// answer: uanswer.value
}
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
up_msg.innerText = "修改时,请求失败!";
showTime(up_msg);
return;
}
if (d.msg == 'errUpdate') {
up_msg.innerText = "修改失败啦!";
showTime(up_msg);
return;
} else if (d.msg == 'ok') {
alert("修改成功!");
personZone(d.data);
}
});
}
//找回密码数据交互
function findPwd_ok() {
//获取标签
let find_msg = document.getElementById("findPwd-msg");
let find_count = document.getElementById("findPwd-count").value;
let find_ques = document.getElementById("findPwd-question").value;
let find_anw = document.getElementById("findPwd-anwser").value;
let find_pwd = document.getElementById("findPwd-pwd").value;
//判断
if(find_count.length!=11){
find_msg.innerText="请输入有效的11位手机号!";
showTime(find_msg);
return;
}else if(find_ques.length<3||find_ques.length>18){
find_msg.innerText="密保问题长度至少3至多18位!";
showTime(find_msg);
return;
}else if(find_anw.length<1||find_anw.length>18){
find_msg.innerText="密保答案长度至少1至多18位!";
showTime(find_msg);
return;
}else if(find_pwd.length<6||find_pwd.length>18){
find_msg.innerText="密码长度至少6至多18位!";
showTime(find_msg);
return;
}
let b = confirm("确认尝试找回密码吗?");
if(!b){
return;
}
//确认修改
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/findPwd',
params: {
'uid': find_count,
'uquestion': find_ques,
'uanwser': find_anw,
'upwd': find_pwd
}
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
find_msg.innerText = "修改时,请求失败!";
showTime(find_msg);
return;
}
if (d.msg == 'isNotCun') {
find_msg.innerText = "当前账号不存在!";
showTime(find_msg);
return;
} else if (d.msg == 'QOAIsErr') {
find_msg.innerText = "密保问题与密保答案不一致!";
showTime(find_msg);
return;
}else if (d.msg == 'findErr') {
find_msg.innerText = "密码找回失败!";
showTime(find_msg);
return;
}else if (d.msg == 'ok') {
alert("密码更改成功,将跳到登陆页面!");
logining();
}
});
}
//找回密码页面
function findPwd() {
let htm = '<div id="findPwd-div"><span id="findPwd-msg"></span>' +
'<input id="findPwd-count" type="text" maxlength="11" οnkeyup="this.value=this.value.replace(/[^0-9]/g,'')" placeholder="请输入手机号"><br>' +
'<select id="findPwd-question"><option>你最喜欢的书籍</option><option>你最喜欢的游戏</option><option>你最喜欢的歌曲</option><option>你最喜欢的运动</option></select><br>' +
'<input id="findPwd-anwser" type="text" maxlength="18" placeholder="密保答案"><br>' +
'<input id="findPwd-pwd" type="password" maxlength="18" placeholder="请输入新密码"><br>' +
'<button οnclick="findPwd_ok()">尝试更改</button><br>' +
'<a href="javascript:void(0);" οnclick="logining()">返回登陆?</a></div>';
middleBody.innerHTML = htm;
}
//退出登录
function goOut(){
let isT = confirm("确认退出当前账号吗?");
if(!isT){
return;
}
//确认
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/goOut',
params: {
}
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
alert("退出登录时,请求失败!");
return;
}
//更改登录标签
head5.innerText="登录";
//跳到登陆页面
logining();
});
}
//第一页页点击事件
head1.onclick = function () {
//设置点击后停放的位置
head1.style.backgroundColor='#dc8ef1';
head2.style.backgroundColor='transparent';
head3.style.backgroundColor='transparent';
head4.style.backgroundColor='transparent';
head5.style.backgroundColor='transparent';
showOne();
}
//第二页点击事件
head2.onclick = function () {
head1.style.backgroundColor='transparent';
head2.style.backgroundColor='#dc8ef1';
head3.style.backgroundColor='transparent';
head4.style.backgroundColor='transparent';
head5.style.backgroundColor='transparent';
paiHTwo();
}
//第三页点击事件
head3.onclick = function () {
head1.style.backgroundColor='transparent';
head2.style.backgroundColor='transparent';
head3.style.backgroundColor='#dc8ef1';
head4.style.backgroundColor='transparent';
head5.style.backgroundColor='transparent';
kongQThree();
}
//第四页点击事件
head4.onclick=function () {
head1.style.backgroundColor='transparent';
head2.style.backgroundColor='transparent';
head3.style.backgroundColor='transparent';
head4.style.backgroundColor='#dc8ef1';
head5.style.backgroundColor='transparent';
jieYueHistory();
}
//第五页点击事件
head5.onclick = function () {
head1.style.backgroundColor='transparent';
head2.style.backgroundColor='transparent';
head3.style.backgroundColor='transparent';
head4.style.backgroundColor='transparent';
head5.style.backgroundColor='#dc8ef1';
//先判断是否已经登录
axios({
method: 'post',
url: 'http://localhost:8080${pageContext.request.contextPath}/userInfo',
params: {}
}).then(function (rs) {
let d = rs.data;
if (d.code != '200') {
alert("登陆这里请求异常!!")
return;
}
if (d.msg == 'kong') {
console.log("还没有登陆,正在进入登陆页面");
logining();
return;
} else if (d.msg == 'ok') {
personZone(d.data);
}
});
}
//当用户不为空时设置用户名
head5.innerText = '${userInf==null?"登录":userInf.uname}';
//用来倒计时5s显示提示信息
function showTime(t) {
//5s
let tim = 5;
//获取原有的内容
let i = t.innerText;
//设置定时器
let ditime = setInterval(dit, 1000);
//判断
function dit() {
if (tim == 0) {
clearInterval(ditime);
tim = 5;
t.innerHTML = "";
} else {
t.innerText = i + '(' + tim + ')';
tim--;
}
}
}
//用户中心:用来查看密保答案
function showAnw() {
let anw = document.getElementById("answer");
let tim=3;
anw.type="text";
setInterval(function () {
if(tim<=0){
anw.type="password";
}
tim--;
},1000)
}
//初始化数据:刷新时定位
let curr = ${currPage==null?0:currPage};
console.log("curr=null:" + curr == null);
if (curr == 0) {
//显示首页
head1.click();
}
//不为null时
if (curr == 1) {
head1.click();
} else if (curr == 2) {
head2.click();
} else if (curr == 3) {
head3.click();
} else if (curr == 4) {
head4.click();
} else if (curr == 5) {
head5.click();
}
</script>
</body>
</html>
三、页面展示
1、首页功能
2、图书排行
3、已被借完的书籍
4、借阅记录,需要登陆
5、登陆页面
6、注册页面
7、找回密码页面
8、登陆后信息展示页面
9、登陆后的 借阅记录功能
源码下载
原文地址:https://blog.csdn.net/qq_45066822/article/details/129671496
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_50066.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。