✅作者简介:热爱国学的Java后端开发者,修心和技术同步精进。
🍎个人主页:Java Fans的博客
🍊个人信条:不迁怒,不贰过。小知识,大智慧。
💞当前专栏:Java案例分享专栏
✨特色专栏:国学周更-心性养成之路
🥭本文内容:图书管理系统【Servlet+HTML综合应用】
更多内容点击👇
ValidateCode验证码的使用详解(初学看完都会用)
【本文目录】
- ⛳️ 项目需求
- ⛳️ 覆盖知识
- ⛳️ 开发思路
- ⛳️ 开发步骤
- 【1】项目配置
- 【2】JDBC+Apache方法操作数据库
- 【3】HTML+CSS+JS 实现页面编写
- 1、用户注册
- 2、用户登录
- ⛳️ 项目源码分享
⛳️ 项目需求
- 首先输入用户名和密码登陆系统,如若登录错误,调到注册界面注册用户,再跳转到登录界面去登陆,登陆成功后显示所有图书信息。
- 登陆成功后,显示数据库存在的所有图书信息,已经添加图书,删除图书和修改图书的相关操作按钮。
- 添加图书:进入增加图书的界面,会跳转到新的界面,添加图书界面,此界面可以添加新的图书,填写完毕后,提交数据,则跳转到显示所有图书的界面中去。
- 修改图书:跟添加图书的逻辑差不多,唯一不同的是,修改图书会把你当下选择的图书信息带入到新跳转的修改图书的界面中去,去修改部分数据后提交数据,然后返回到显示所有图书的界面中。
- 删除图书:点击删除按钮,会提示是否确定删除,点击确定则删除本界面中的当前数据,并从所有数据中删除这一条数据。
⛳️ 覆盖知识
- java部分:程序基本概念、数据类型、流程控制、顺序、选择 、循环、跳转语句、变量、类、方法、实用类、JDBC、三层架构Druid连接池、Apache的DBUtils使用、Servlet等。
- 数据库部分:创建表、增删改查语句的书写等。
- 前端部分:HTML、CSS、jQuery、JavaScript等。
⛳️ 开发思路
- 明确需求
- 编码顺序
- 添加项目需要使用的各种jar包
- HTML 页面表单的编写
- Apache方法的DBUtils编写
- 实体类的数据初始化(添加私有变量、有参/无参构造、get/set方法、toString() 方法重写)
- 完成 用户和图书 的数据表创建
- 完成 用户和图书 三层架构的搭建(dao层接口和实现类的编写、service层接口和实现类的编写、view层的Servlet类的编写)
- 测试
⛳️ 开发步骤
【1】项目配置
1、用IDEA创建项目,File—>New—>Project,选择默认的new project即可,创建一个项目名称,点击Create完成创建。
2、然后鼠标右击项目Add Framework support,选择Web Application来添加Web框架;
3、在web目录下的WEB-INF上右单击,新建一个Directory目录,命名为lib;
然后把项目需要的jar包放在lib中:
IDEA创建Java web项目的详细步骤可以参考我的一篇博文:IDEA创建Java Web项目
【2】JDBC+Apache方法操作数据库
1、创建database.properties文件,用来配置注册驱动和数据库连接对象的相关数据。
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/idea_database
username=root
password=huanghuang
initialSize=10
maxActive=30
maxIdle=5
maxWait=3000
2、创建数据表:
user 表
CREATE TABLE `user` (
`uname` varchar(20) NOT NULL,
`upassword` varchar(20) NOT NULL
)
book 表
CREATE DATABASE IF NOT EXISTS `java221804`;
CREATE TABLE IF NOT EXISTS book(
`name` VARCHAR(20),
`state` INT,
`date` INT,
`count` INT
);
3、创建工具目录,存放工具类
DBUtils.java
package utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class DBUtils {
private static DruidDataSource druidDataSource;
static {
Properties properties = new Properties();
try {
InputStream is = DBUtils.class
.getResourceAsStream("/database.properties");
properties.load(is);
druidDataSource = (DruidDataSource) DruidDataSourceFactory
.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return druidDataSource;
}
}
4、创建实体类
User类
package cn.lqgx.entity;
public class User {
private String uname;
private String upassword;
public User() {
}
public User(String uname, String upassword) {
this.uname = uname;
this.upassword = upassword;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpassword() {
return upassword;
}
public void setUpassword(String upassword) {
this.upassword = upassword;
}
@Override
public String toString() {
return "User{" + "uname='" + uname + '\'' + ", upassword='" + upassword + '\'' + '}';
}
}
Book类
package entity;
import java.util.Date;
public class Student {
private int sid;
private String sname;
private int sage;
private String ssex;
private String saddress;
private String sphoneNum;
public Student() {
super();
}
public Student(int sid, String sname, int sage, String ssex, String saddress, String sphoneNum) {
this.sid = sid;
this.sname = sname;
this.sage = sage;
this.ssex = ssex;
this.saddress = saddress;
this.sphoneNum = sphoneNum;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getSage() {
return sage;
}
public void setSage(int sage) {
this.sage = sage;
}
public String getSsex() {
return ssex;
}
public void setSsex(String ssex) {
this.ssex = ssex;
}
public String getSaddress() {
return saddress;
}
public void setSaddress(String saddress) {
this.saddress = saddress;
}
public String getSphoneNum() {
return sphoneNum;
}
public void setSphoneNum(String sphoneNum) {
this.sphoneNum = sphoneNum;
}
@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", sname='" + sname + '\'' +
", sage=" + sage +
", ssex='" + ssex + '\'' +
", saddress='" + saddress + '\'' +
", sphoneNum='" + sphoneNum + '\'' +
'}';
}
}
5、创建数据访问层DAO层的接口
UserDao接口
package cn.lqgx.dao;
import cn.lqgx.entity.User;
import java.util.List;
public interface UserDao {
//增
int insert(User user);
//删
int delete(User user);
//改
int update(User user);
//查一个
User selectOne(User user);
//查全部
List<User> selectAll();
}
BookDao接口
package cn.lqgx.dao;
import cn.lqgx.entity.Book;
import java.util.List;
public interface BookDao {
//增
int insert(Book book);
//删
int delete(int bid);
//改
int update(Book book);
//查一个
Book selectById(int bid);
Book selectByIsbn(String isbn);
//查全部
List<Book> selectAll();
}
6、创建数据访问层DAO层接口的实现类
UserDaoImpl实现类
package cn.lqgx.dao.Impl;
import cn.lqgx.dao.UserDao;
import cn.lqgx.entity.User;
import cn.lqgx.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class UserDaoImpl implements UserDao {
QueryRunner queryRunner=new QueryRunner(DBUtils.getDataSource());
@Override
public int insert(User user) {
String sql="INSERT INTO `user`(`uname`,`upassword`) VALUES(?,?);";
Object[] args={user.getUname(),user.getUpassword()};
try {
return queryRunner.update(sql,args);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int delete(User user) {
String sql = "delete from user where uname=? and upassword=?;";
Object[] args={user.getUname(),user.getUpassword()};
try {
return queryRunner.update(sql, args);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int update(User user) {
String sql="update `user` set `upassword`=? where uname=?;";
Object[] args={user.getUpassword(),user.getUname()};
try {
return queryRunner.update(sql,args);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public User selectOne(User user) {
String sql = "select * from user where uname=? and upassword=?;";
Object[] args={user.getUname(),user.getUpassword()};
try {
return queryRunner.query(sql, new BeanHandler<User>(
User.class), args);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public List<User> selectAll() {
String sql = "select * from user;";
try {
return queryRunner.query(sql, new BeanListHandler<User>(
User.class));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
BookDaoImpl实现类
package cn.lqgx.dao.Impl;
import cn.lqgx.dao.BookDao;
import cn.lqgx.entity.Book;
import cn.lqgx.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class BookDaoImpl implements BookDao {
QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
@Override
public int insert(Book book) {
String sql = "INSERT INTO `book`(`isbn`,`name`,`author`,`press`,`price`,`classification`) VALUES(?,?,?,?,?,?);";
Object[] args = {book.getIsbn(), book.getName(), book.getAuthor(),
book.getPress(), book.getPrice(), book.getClassification()};
try {
return queryRunner.update(sql, args);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int delete(int bid) {
String sql = "delete from book where bid=?;";
try {
return queryRunner.update(sql, bid);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int update(Book book) {
String sql = "update `book` set `isbn`=?,`name`=?,`author`=?,`press`=?,`price`=?,`classification`=? where bid=?;";
Object[] args = {book.getIsbn(), book.getName(), book.getAuthor(),
book.getPress(), book.getPrice(), book.getClassification(), book.getBid()};
try {
return queryRunner.update(sql, args);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public Book selectById(int bid) {
String sql = "select * from book where bid=?;";
try {
return queryRunner.query(sql, new BeanHandler<Book>(
Book.class), bid);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public Book selectByIsbn(String isbn) {
String sql = "select * from book where isbn=?;";
try {
return queryRunner.query(sql, new BeanHandler<Book>(
Book.class), isbn);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public List<Book> selectAll() {
String sql = "select * from book;";
try {
return queryRunner.query(sql, new BeanListHandler<Book>(
Book.class));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
7、创建服务层Service层的接口
UserService接口
package cn.lqgx.service;
import cn.lqgx.entity.User;
import java.util.List;
public interface UserService {
//增
int addPUser(User user);
//删
int delPUser(User user);
//改
int updatePUser(User user);
//查一个
User selectPUser(User user);
//查全部
List<User> selectAllPUsers();
}
BookService接口
package cn.lqgx.service;
import cn.lqgx.entity.Book;
import java.util.List;
public interface BookService {
//增
int insertBook(Book book);
//删
int deleteBook(int bid);
//改
int updateBook(Book book);
//查一个
Book selectBookById(int bid);
Book selectBookByIsbn(String isbn);
//查全部
List<Book> selectAllBooks();
}
8、创建服务层Service层接口的实现类
UserServiceImpl实现类
package cn.lqgx.service.Impl;
import cn.lqgx.dao.Impl.UserDaoImpl;
import cn.lqgx.dao.UserDao;
import cn.lqgx.entity.User;
import cn.lqgx.service.UserService;
import java.util.List;
public class UserServiceImpl implements UserService {
UserDao pUserDao=new UserDaoImpl();
@Override
public int addPUser(User user) {
return pUserDao.insert(user);
}
@Override
public int delPUser(User user) {
return pUserDao.delete(user);
}
@Override
public int updatePUser(User user) {
return pUserDao.update(user);
}
@Override
public User selectPUser(User user) {
return pUserDao.selectOne(user);
}
@Override
public List<User> selectAllPUsers() {
return pUserDao.selectAll();
}
}
BookServiceImpl实现类
package cn.lqgx.service.Impl;
import cn.lqgx.dao.BookDao;
import cn.lqgx.dao.Impl.BookDaoImpl;
import cn.lqgx.entity.Book;
import cn.lqgx.service.BookService;
import java.util.List;
public class BookServiceImpl implements BookService {
BookDao bookDao=new BookDaoImpl();
@Override
public int insertBook(Book book) {
return bookDao.insert(book);
}
@Override
public int deleteBook(int bid) {
return bookDao.delete(bid);
}
@Override
public int updateBook(Book book) {
return bookDao.update(book);
}
@Override
public Book selectBookById(int bid) {
return bookDao.selectById(bid);
}
@Override
public Book selectBookByIsbn(String isbn) {
return bookDao.selectByIsbn(isbn);
}
@Override
public List<Book> selectAllBooks() {
return bookDao.selectAll();
}
}
9、视图层的测试类
1)ServletLogin用户登录类
package cn.lqgx.Servlet;
import cn.lqgx.entity.User;
import cn.lqgx.service.Impl.UserServiceImpl;
import cn.lqgx.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "ServletLogin", value = "/ServletLogin")
public class ServletLogin extends HttpServlet {
UserService pUserService=new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//通过response输出在控制台
PrintWriter printWriter =response.getWriter();
String pUserName= request.getParameter("pUserName");
String pUserPassword= request.getParameter("pUserPassword");
User pUserNew=new User(pUserName,pUserPassword);
User pUser=pUserService.selectPUser(pUserNew);
if(pUser!=null){
response.sendRedirect("ServletShow");
}else{
// printWriter.println("<h2>姓名或者学号错误,无法登录</h2>");
response.sendRedirect("/Books/userRegister.html");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
运行效果:
2)ServletRegister用户注册类
package cn.lqgx.Servlet;
import cn.lqgx.entity.User;
import cn.lqgx.service.Impl.UserServiceImpl;
import cn.lqgx.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "ServletRegister", value = "/ServletRegister")
public class ServletRegister extends HttpServlet {
UserService pUserService=new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//通过response输出在控制台
PrintWriter printWriter =response.getWriter();
String pUserName= request.getParameter("pUserName");
String pUserPassword= request.getParameter("pUserPassword");
User pUserNew=new User(pUserName,pUserPassword);
User pUser=pUserService.selectPUser(pUserNew);
if(pUser==null){
int num=pUserService.addPUser(pUserNew);
if(num>0){
response.sendRedirect("/Books/userLogin.html");
}
}else{
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
运行效果:
3)登陆成功后跳转到ServletShow界面
package cn.lqgx.Servlet;
import cn.lqgx.entity.Book;
import cn.lqgx.service.BookService;
import cn.lqgx.service.Impl.BookServiceImpl;
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 java.io.IOException;
import java.util.List;
@WebServlet(name = "ServletShow", value = "/ServletShow")
public class ServletShow extends HttpServlet {
BookService bookService=new BookServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Book> bookList = bookService.selectAllBooks();
request.setAttribute("allInfos",bookList);
request.getRequestDispatcher("/ServletShowAll").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
运行效果:
4)删除图书信息的测试类
package cn.lqgx.Servlet;
import cn.lqgx.service.BookService;
import cn.lqgx.service.Impl.BookServiceImpl;
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 java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "ServletDel", value = "/ServletDel")
public class ServletDel extends HttpServlet {
BookService bookService=new BookServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//通过response输出在控制台
PrintWriter printWriter =response.getWriter();
int bid= Integer.parseInt(request.getParameter("bid"));
//删除
int num =bookService.deleteBook(bid);
if(num>0){
//重新显示所有信息
// ShowAll.ShowAllEmployee(request, response);
response.sendRedirect("ServletShow");
}else {
// printWriter.println("<h1>删除失败!</h1>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
运行效果:
5)修改图书信息的测试类
package cn.lqgx.Servlet;
import cn.lqgx.entity.Book;
import cn.lqgx.service.BookService;
import cn.lqgx.service.Impl.BookServiceImpl;
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 java.io.IOException;
@WebServlet(name = "ServletUpdate", value = "/ServletUpdate")
public class ServletUpdate extends HttpServlet {
BookService bookService=new BookServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int bid= Integer.parseInt(request.getParameter("bid"));
Book book =bookService.selectBookById(bid);
request.setAttribute("product",book);
request.getRequestDispatcher("/ServletUpdateHtml").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package cn.lqgx.Servlet;
import cn.lqgx.entity.Book;
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 java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "ServletUpdateHtml", value = "/ServletUpdateHtml")
public class ServletUpdateHtml extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
Book book=(Book)request.getAttribute("product");
//通过response输出在控制台
PrintWriter printWriter =response.getWriter();
printWriter.println("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>商品修改</title>");
printWriter.println("<link rel=\"stylesheet\"href=\"css/insert.css\">");
printWriter.println("</head>");
printWriter.println("<body><div><h2>商品修改</h2>");
printWriter.println("<form action='ServletUpdateTrue' method='post'>");
printWriter.println("<p>图书编号:<input type=\"text\" name=\"bid\" value='"+book.getBid()+"'/></p>");
printWriter.println("<p>国际标准书号:<input type=\"text\" name=\"isbn\" value='"+book.getIsbn()+"'/></p>");
printWriter.println("<p>书名:<input type=\"text\" name=\"name\" value='"+book.getName()+"'/></p>");
printWriter.println("<p>作者:<input type=\"text\" name=\"author\" value='"+book.getAuthor()+"'/></p>");
printWriter.println("<p>出版社:<input type=\"text\" name=\"press\" value='"+book.getPress()+"'/></p>");
printWriter.println("<p>价格:<input type=\"text\" name=\"price\" value='"+book.getPrice()+"'/></p>");
printWriter.println("<p>分类:<input type=\"text\" name=\"classification\" value='"+book.getClassification()+"'/></p>");
printWriter.println("<p class=\"pBtn\"><input class=\"inputBtn\" type=\"submit\" value=\"确 定\"/>" +
"<a href='/Books/ServletShow'>返 回</a></p>");
printWriter.println("</form>");
printWriter.println("</div></body></html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
运行效果
6)增加学生的测试类
package cn.lqgx.Servlet;
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 java.io.IOException;
@WebServlet(name = "ServletInsert", value = "/ServletInsert")
public class
ServletInsert extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("insert.html");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package cn.lqgx.Servlet;
import cn.lqgx.entity.Book;
import cn.lqgx.service.BookService;
import cn.lqgx.service.Impl.BookServiceImpl;
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 java.io.IOException;
@WebServlet(name = "ServletInsertTrue", value = "/ServletInsertTrue")
public class ServletInsertTrue extends HttpServlet {
BookService bookService=new BookServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//通过response输出在控制台
String isbn= request.getParameter("isbn");
String name= request.getParameter("name");
String author= request.getParameter("author");
String press= request.getParameter("press");
double price= Double.parseDouble(request.getParameter("price"));
String classification= request.getParameter("classification");
Book book=bookService.selectBookByIsbn(isbn);
// System.out.println(product);
if(book==null) {
Book bookNew=new Book(isbn,name,author,press,price,classification);
//先查询要添加的数据是否存在数据库中
int num =bookService.insertBook(bookNew);
// System.out.println(productNew+""+num);
if(num>0){
//重新显示所有信息
response.sendRedirect("ServletShow");
}else {
// printWriter.println("<h1>修改失败!</h1>");
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
运行效果:
【3】HTML+CSS+JS 实现页面编写
对应java中操作图书及用户信息的各个测试类中,我们在各个类中写了@WebServlet 注解的形式,将Servlet测试类与HTML页面实了现数据的交互。
1、用户注册
1)新用户注册页面HTML编写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册界面</title>
<link rel="stylesheet" href="css/login.css">
<script src="js/jQuery-3.6.1.js"></script>
<script src="js/login.js"></script>
</head>
<body>
<div>
<h2>欢迎注册</h2>
<form action="ServletRegister" method="post">
<p>用户名:<input type="text" name="pUserName"/><span></span></p>
<p>密 码:<input type="password" name="pUserPassword"/><span></span></p>
<p><input class="btnInput" type="submit" value="确定注册"/></p>
</form>
</div>
</body>
</html>
2)新用户注册的CSS样式
body{
background-image: url("../img/2.gif");
/*background-repeat: round;*/
background-size: cover;
}
div{
/*border: 1px solid #F00;*/
border-radius: 50px;
width: 500px;
margin: 50px auto;
padding: 20px;
background-image: url("../img/3.gif");
background-repeat: round;
color: yellow;
}
form{
margin-left: 50px;
}
input{
width: 120px;
border-color: #ccc;
outline: none;
}
.btnInput{
margin-left: 42%;
margin-bottom: -20px;
padding: 3px;
width: 100px;
background: rgba(0,0,255,30%);
color: yellow;
font-weight: bold;
}
span{
margin-left: 10px;
color: #ccc;
font-size: 15px;
color: rgba(173,255,47,40%);
}
3)新用户注册的JS文件
从下图结构中可知,需要添加一个jQuery,我这边网上下载的jQuery-3.6.1.js,添加到js目录中,然后创建一个newstu.js文件。
newstu.js文件
$(function() {
//姓名框获得焦点,给出提示,中文组成,长度为2-4位
$('input').eq(0).focus(function() {
//给其后面的span标签插入账号的提示信息
$('span').eq(0).text('中文组成,长度为2-4位')
$('input').eq(0).css('border-color', '#00f');
$('span').eq(0).css('color', '#ccc');
});
//姓名框失去焦点
$('input').eq(0).blur(function() {
$('input').eq(0).css('border-color', '#CCC');
//定义姓名内容的正则表达式
var patter0 = /[\u4e00-\u9fa5]/g;
//获取你在姓名框中输入的内容是否为空
var result2 = $('input').eq(0).val();
//对内容进行非空判断
if (result2.length == 0) {
$('span').eq(0).text('姓名不能为空');
$('span').eq(0).css('color', '#f00');
} else if (result2.length < 2 || result2.length > 4) {
$('span').eq(0).text('姓名长度为2-4位');
$('span').eq(0).css('color', '#f00');
} else if (!patter0.test(result2)) { //当你输入的内容是非法字符的时候,给出内容组成不合法提示
$('span').eq(0).text('姓名只能由中文组成');
$('span').eq(0).css('color', '#f00');
} else {
show(0);
}
});
//给密码标签注册获得焦点事件
$('input').eq(1).focus(function() {
//给其后面的span标签插入学号的提示信息
$('span').eq(1).text('密码由数字组成,长度6位')
$('input').eq(1).css('border-color', '#00f');
$('span').eq(1).css('color', '#ccc');
});
//给密码标签注册失去焦点事件
$('input').eq(1).blur(function() {
$('input').eq(1).css('border-color', '#CCC');
//定义密码内容的正则表达式
var patter = /[^0-9]/g;
//获取你在密码框中输入的内容是否为空
var result1 = $('input').eq(1).val();
//对密码内容进行非空判断
if (result1.length == 0) {
$('span').eq(1).text('密码不能为空');
$('span').eq(1).css('color', '#f00');
} else if (result1.length !=6) {
$('span').eq(1).text('密码长度为6位');
$('span').eq(1).css('color', '#f00');
} else if (patter.test(result1)) { //当你输入的密码内容是非法字符的时候,给出内容组成不合法提示
$('span').eq(1).text('密码只能由数字组成');
$('span').eq(1).css('color', '#f00');
} else {
show(1);
}
});
//正确显示样式方法
function show(num) {
$('span').eq(num).text('✔');
$('span').eq(num).css('color', '#5FDDA4');
};
});
2、用户登录
1)用户登录页面HTML编写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆界面</title>
<link rel="stylesheet" href="css/login.css">
<script src="js/jQuery-3.6.1.js"></script>
<script src="js/login.js"></script>
</head>
<body>
<div>
<h2>欢迎登陆</h2>
<form action="ServletLogin" method="post">
<p>用户名:<input type="text" name="pUserName"/></p>
<p>密 码:<input type="password" name="pUserPassword"/></p>
<p><input class="btnInput" type="submit" value="登 陆"/></p>
</form>
</div>
</body>
</html>
2)用户登录页面CSS编写
body{
background-image: url("../img/2.gif");
/*background-repeat: round;*/
background-size: cover;
}
div{
/*border: 1px solid #F00;*/
border-radius: 50px;
width: 500px;
margin: 50px auto;
padding: 20px;
background-image: url("../img/3.gif");
background-repeat: round;
color: yellow;
}
form{
margin-left: 50px;
}
input{
width: 120px;
border-color: #ccc;
outline: none;
}
.btnInput{
margin-left: 42%;
margin-bottom: -20px;
padding: 3px;
width: 100px;
background: rgba(0,0,255,30%);
color: yellow;
font-weight: bold;
}
span{
margin-left: 10px;
color: #ccc;
font-size: 15px;
color: rgba(173,255,47,40%);
}
3)用户登录页面JS编写和注册的一样
⛳️ 项目源码分享
链接:https://download.csdn.net/download/hh867308122/87338282
码文不易,本篇文章就介绍到这里,如果想要学习更多Java系列知识,点击关注博主,博主带你零基础学习Java知识。与此同时,对于日常生活有困扰的朋友,欢迎阅读我的第四栏目:《国学周更—心性养成之路》,学习技术的同时,我们也注重了心性的养成。