javaweb+jsp+servlet
实体类
package com.ghx.entity;/*** @author :guo* @date :Created in 2024/12/6 10:13* @description:* @modified By:* @version:*/
public class Book {private int id;private String name;private double price;private String publisher;public Book() {}public Book(int id, String name, double price, String publisher) {this.id = id;this.name = name;this.price = price;this.publisher = publisher;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public String getPublisher() {return publisher;}public void setPublisher(String publisher) {this.publisher = publisher;}
}
package com.ghx.entity;/*** @author :guo* @date :Created in 2024/12/3 16:48* @description:* @modified By:* @version:*/
public class User {private int id;private String username;private String password;private String realname;private int age;public User() {}public User(int id, String username, String password, String realname, int age) {this.id = id;this.username = username;this.password = password;this.realname = realname;this.age = age;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getRealname() {return realname;}public void setRealname(String realname) {this.realname = realname;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
dao
package com.ghx.dao;import java.sql.*;/*** @author :guo* @date :Created in 2024/12/2 14:08* @description:* @modified By:* @version:*/
public class BaseDao {Connection conn=null;PreparedStatement ps=null;ResultSet rs=null;String url = "jdbc:mysql://localhost:3306/day06";String username = "root";String password = "123456";String driverName="com.mysql.cj.jdbc.Driver";public int edit(String sql,Object... obj){try {getConn();ps = conn.prepareStatement(sql);for(int i=0;i<obj.length;i++){ps.setObject(i+1,obj[i]);}int i=ps.executeUpdate();return i;} catch (Exception e) {return 0;} finally {closeAll();}}//连接数据库public void getConn() throws Exception{Class.forName(driverName);conn = DriverManager.getConnection(url, username, password);}//关闭资源public void closeAll(){try {if(rs!=null){rs.close();}if(ps!=null){ps.close();}if(conn!=null){conn.close();}} catch (SQLException e) {throw new RuntimeException(e);}}
}
package com.ghx.dao;import com.ghx.entity.Book;
import com.ghx.entity.User;import java.util.ArrayList;
import java.util.List;
/*** @author :guo* @date :Created in 2024/12/6 10:13* @description:* @modified By:* @version:*/
public class BookDao extends BaseDao{public List<Book> findAll() {List<Book> list=new ArrayList<Book>();try {getConn();String sql="select id,name,price,publisher from tbl_book ";ps=conn.prepareStatement(sql);rs=ps.executeQuery();while (rs.next()){Book book=new Book();book.setId(rs.getInt("id"));book.setName(rs.getString("name"));book.setPrice(rs.getDouble("price"));book.setPublisher(rs.getString("publisher"));list.add(book);}} catch (Exception e) {throw new RuntimeException(e);} finally {closeAll();}return list;}//插入public int insert(String name,double price,String publisher){String sql="insert into tbl_book(name,price,publisher) values (?,?,?)";return edit(sql,name,price,publisher);}//回显数据public Book findById(int id){Book book=null;try {getConn();String sql="select id,name,price,publisher from tbl_book where id=?";ps=conn.prepareStatement(sql);ps.setObject(1,id);rs=ps.executeQuery();while (rs.next()){book=new Book();book.setId(rs.getInt("id"));book.setName(rs.getString("name"));book.setPrice(rs.getDouble("price"));book.setPublisher(rs.getString("publisher"));}} catch (Exception e) {throw new RuntimeException(e);} finally {closeAll();}return book;}//修改public int updateBook(String name,double price,String publisher,int id){String sql= "update tbl_book set name=?,price=?,publisher=? where id=?";return edit(sql,name,price,publisher,id);}//删除public int deleteBook(int id){String sql="delete from tbl_book where id=?";return edit(sql,id);}
}
package com.ghx.dao;import com.ghx.entity.User;import java.util.ArrayList;/*** @author :guo* @date :Created in 2024/12/3 16:48* @description:* @modified By:* @version:*/
public class UserDao extends BaseDao{//登录判断public User find(String username,String password){User user=null;try {getConn();String sql="select id,username,password,realname,age from tbl_user where username=? and password=?";ps=conn.prepareStatement(sql);ps.setObject(1,username);ps.setObject(2,password);rs=ps.executeQuery();while (rs.next()){user=new User();int id = rs.getInt("id");String name = rs.getString("username");String pwd = rs.getString("password");String realname = rs.getString("realname");int age = rs.getInt("age");user.setId(id);user.setUsername(name);user.setPassword(pwd);user.setRealname(realname);user.setAge(age);}return user;} catch (Exception e) {throw new RuntimeException(e);} finally {closeAll();}}//注册public int add(String name,String pwd,String rname,String age){String sql="insert into tbl_user values(null,?,?,?,?)";return edit(sql,name,pwd,rname,age);}
}
servlet
package com.ghx.servlet;import com.ghx.dao.BookDao;
import com.ghx.entity.Book;import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;@WebServlet(name = "BookServlet", value = "/BookServlet")
public class BookServlet extends HttpServlet {private BookDao bookDao=new BookDao();@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");String method = request.getParameter("method");if("insert".equals(method)){insertBook(request,response);}else if("getById".equals(method)){getById(request,response);} else if("update".equals(method)){updateById(request,response);}else if("delete".equals(method)){deleteById(request,response);}else {selectAll(request,response);}}private void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{int id = Integer.parseInt(request.getParameter("id"));int i = bookDao.deleteBook(id);if(i>0){response.sendRedirect("/BookServlet");}}//修改private void updateById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{int id = Integer.parseInt(request.getParameter("id"));String name = request.getParameter("name");double price = Double.parseDouble(request.getParameter("price"));String publisher = request.getParameter("publisher");int i = bookDao.updateBook(name, price, publisher, id);if(i>0){response.sendRedirect("/BookServlet");}}//回显数据private void getById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{int id = Integer.parseInt(request.getParameter("id"));Book byId = bookDao.findById(id);request.setAttribute("bookid",byId);request.getRequestDispatcher("/update.jsp").forward(request,response);}//添加private void insertBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{String name = request.getParameter("name");double price = Double.parseDouble(request.getParameter("price"));String publisher = request.getParameter("publisher");int insert = bookDao.insert(name, price, publisher);if(insert>0){response.sendRedirect("/BookServlet");}}//展示全部private void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{List<Book> all = bookDao.findAll();request.setAttribute("book",all);request.getRequestDispatcher("/index.jsp").forward(request,response);}}
package com.ghx.servlet;import com.ghx.dao.UserDao;
import com.ghx.entity.User;import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {private UserDao userDao=new UserDao();@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");String method = request.getParameter("method");if("login".equals(method)){login(request,response);}else if("register".equals(method)){register(request,response);}else if("logout".equals(method)){logout(request,response);}}//退出系统private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{HttpSession session = request.getSession();User user = (User) session.getAttribute("userinfo");session.removeAttribute("userinfo");response.sendRedirect("/login.jsp");}//注册private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{String username = request.getParameter("username");String password = request.getParameter("password");String realname = request.getParameter("realname");String age = request.getParameter("age");int add = userDao.add(username, password, realname, age);if(add>0){response.sendRedirect("/login.jsp?success=1");}else {request.setAttribute("error2","<span style=\"color: red \">注册失败,用户名已存在!</span>");request.getRequestDispatcher("/register.jsp?error2").forward(request,response);}}//登录private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{String username = request.getParameter("username");String password = request.getParameter("password");User user = userDao.find(username, password);if(user!=null){request.getSession().setAttribute("userinfo",user);response.sendRedirect("/BookServlet");}else {request.setAttribute("error","<span style=\"color: red \">用户名或密码错误!</span>");request.getRequestDispatcher("/login.jsp?error").forward(request,response);}}}
页面
login.jsp
<%--Created by IntelliJ IDEA.User: lenovoDate: 2024/12/3Time: 16:40To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>登录</title><style>/* 整体页面背景设置 */body {font-family: Arial, sans-serif;/* background-image: url('背景图片路径');*/background-size: cover;background-repeat: no-repeat;background-position: center;display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;}/* 登录框样式 */.login-box {background-color: rgba(255, 255, 255, 0.8);padding: 40px;border-radius: 10px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);}/* 标题样式 */h2 {text-align: center;margin-bottom: 30px;color: #333;}/* 输入框样式 */input[type="text"],input[type="password"] {width: 100%;padding: 15px;margin-bottom: 20px;border: 1px solid #ccc;border-radius: 5px;font-size: 16px;}/* 登录按钮样式 */input[type="submit"] {width: 100%;padding: 15px;background-color: #007BFF;color: white;border: none;border-radius: 5px;font-size: 16px;cursor: pointer;}input[type="submit"]:hover {background-color: #0056b3;}/* 注册链接样式 */.register-link {text-align: center;margin-top: 15px;}a {color: #007BFF;text-decoration: none;}a:hover {text-decoration: underline;}</style>
</head>
<body>
<div class="login-box"><h2>登录</h2><div></div><form action="/UserServlet?method=login" method="post"><input type="text" placeholder="用户名" name="username"><input type="password" placeholder="密码" name="password"><input type="submit" value="登录"></form><div class="register-link"><a href="/register.jsp">还没有账号?注册</a></div><div>${error}</div>
</div>
</body>
</html>
register.jsp
<%--Created by IntelliJ IDEA.User: lenovoDate: 2024/12/3Time: 16:46To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>注册</title><style>/* 整体页面背景设置 */body {font-family: Arial, sans-serif;background-color: #f4f4f4;display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;}/* 注册框样式 */.register-box {background-color: white;padding: 40px;border-radius: 8px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);width: 400px;}/* 标题样式 */h2 {text-align: center;margin-bottom: 30px;color: #333;}/* 输入框通用样式 */input[type="text"],input[type="password"],input[type="email"],input[type="number"]{width: 100%;padding: 15px;margin-bottom: 20px;border: 1px solid #ccc;border-radius: 5px;font-size: 16px;}/* 注册按钮样式 */input[type="submit"] {width: 100%;padding: 15px;background-color: #007BFF;color: white;border: none;border-radius: 5px;font-size: 16px;cursor: pointer;}input[type="submit"]:hover {background-color: #007BFF;}/* 已有账号登录链接样式 */.login-link {text-align: center;margin-top: 20px;}a {color: #007BFF;text-decoration: none;}a:hover {text-decoration: underline;}</style>
</head>
<body><div class="register-box"><h2>注册新账号</h2><form action="/UserServlet?method=register" method="post"><input type="text" placeholder="用户名" name="username"><input type="password" placeholder="设置密码" name="password"><input type="text" placeholder="真实姓名" name="realname"><input type="number" placeholder="年龄" name="age"><input type="submit" value="注册"></form><div class="login-link"><a href="login.jsp">已有账号?点击登录</a></div>${error2}</div>
</body>
</html>
index.jsp
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.ghx.entity.User" %><%--Created by IntelliJ IDEA.User: lenovoDate: 2024/12/4Time: 9:25To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>Title</title><style>/* 全局样式重置与基础设置 */* {margin: 0;padding: 0;box-sizing: border-box;font-family: Arial, sans-serif;}body {background-color: #f4f9ff;color: #333;line-height: 1.6;}/* 页面头部样式 */header {background-color: #007bff;color: white;text-align: center;padding: 20px 0;box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);}header h1 {margin: 0;}/* 导航栏样式 */nav {background-color: #0056b3;padding: 10px 0;}nav ul {list-style-type: none;display: flex;justify-content: center;align-items: center;}nav ul li {margin: 0 15px;color: white;}nav a {color: white;text-decoration: none;padding: 8px 15px;border-radius: 4px;transition: background-color 0.3s ease;}nav a:hover {background-color: #003d80;}/* 主要内容区域样式 */main {padding: 20px;max-width: 1000px;margin: 20px auto;background-color: white;box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);border-radius: 5px;}main h1 {text-align: center;margin-bottom: 20px;color: #007bff;}/* 表格样式 */table {width: 100%;border-collapse: collapse;margin-bottom: 20px;border: 1px solid #ccc;}table th,table td {border: 1px solid #ccc;padding: 12px;text-align: center;}table th {background-color: #e6f7ff;color: #333;font-weight: bold;}table tr:nth-child(even) {background-color: #f9f9f9;}table tr:hover {background-color: #e9f3ff;cursor: pointer;}/* 操作链接样式 */table td a {color: #007bff;text-decoration: none;margin: 0 5px;padding: 5px 10px;border-radius: 3px;transition: background-color 0.3s ease, color 0.3s ease;}table td a:hover {background-color: #007bff;color: white;}/* 退出按钮样式 */.logout {float: right;margin-right: 20px;color: white;text-decoration: none;padding: 8px 15px;border-radius: 4px;background-color: #dc3545;transition: background-color 0.3s ease;display: flex;align-items: center;}.logout:hover {background-color: #c82333;}.logout i {margin-right: 5px;}/* 修改成功提示样式 */.success-message {text-align: center;color: green;margin-bottom: 20px;font-weight: bold;display: none;}</style>
</head>
<body>
<c:if test="${sessionScope.userinfo==null}"><c:redirect url="login.jsp"></c:redirect>
</c:if><header><h1>书籍信息管理系统</h1>
</header>
<nav><ul><li>欢迎${sessionScope.userinfo.realname}登录</li></ul><ul><li><a href="#">首页</a></li><li><a href="/insert.jsp">添加</a></li><a href="/UserServlet?method=logout" class="logout">退出</a></ul></nav>
<main><table><tr><th>书籍id</th><th>书籍名</th><th>价格</th><th>出版社</th><th>操作</th></tr><c:forEach items="${requestScope.book}" var="b"><tr><td>${b.id}</td><td>${b.name}</td><td>${b.price}</td><td>${b.publisher}</td><td><a href="/BookServlet?method=delete&id=${b.id}" onclick="return confirm('确定要删除该条信息吗?');">删除</a><a href="/BookServlet?method=getById&id=${b.id}">修改</a></td></tr></c:forEach></table>
</main>
</body>
</html>
insert.jsp
<%@ page import="com.ghx.entity.User" %><%--Created by IntelliJ IDEA.User: lenovoDate: 2024/12/4Time: 10:31To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><style>/* 全局样式重置,去除浏览器默认样式差异 */* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: 'Roboto', sans-serif; /* 使用更现代的字体 */background-color: #eef2f7; /* 淡蓝色系背景,营造清新氛围 */display: flex;justify-content: center;align-items: center;min-height: 100vh;}/* 主要内容容器样式 */.main-container {width: 500px; /* 设定合适的宽度 */background-color: white;border-radius: 8px; /* 较大的圆角,更显柔和 */box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 柔和阴影效果 */overflow: hidden; /* 隐藏超出部分,确保圆角效果正常显示 */}/* 标题样式 */h2 {background-color: cornflowerblue; /* 标题栏蓝色背景 */color: white;text-align: center;padding: 15px 0;margin-bottom: 20px;}table {width: 100%;border-collapse: collapse;margin-bottom: 20px;}th, td {border-bottom: 1px solid #e0e0e0; /* 仅底部显示边框,简洁风格 */padding: 12px 20px;text-align: left;}th {font-weight: normal; /* 表头字体不加粗,更显简洁 */color: #777; /* 表头文字灰色,区分数据 */}input[type="text"] {width: 100%;padding: 8px;border: 1px solid #ccc;border-radius: 4px;background-color: #f9f9f9; /* 输入框浅灰色背景,更清晰 */color: #333; /* 输入框文字颜色 */outline: none; /* 去除输入框聚焦时的默认边框 */transition: background-color 0.2s ease; /* 背景色过渡效果 */}input[type="text"]:focus {background-color: white; /* 输入框聚焦时变白,增强交互感 */}input[type="submit"] {display: block;width: 100%;padding: 10px 0;background-color: #2ecc71; /* 绿色提交按钮,更醒目积极 */color: white;border: none;border-radius: 4px;cursor: pointer;font-size: 16px;transition: background-color 0.3s ease; /* 背景色过渡效果 */}input[type="submit"]:hover {background-color: #27ae60; /* 悬停时加深绿色 */}</style>
</head>
<body>
<c:if test="${sessionScope.userinfo==null}"><c:redirect url="login.jsp"></c:redirect>
</c:if><div class="main-container"><h2>书籍信息</h2><form action="/BookServlet?method=insert" method="post"> <!-- 添加表单标签,假设提交到当前页面,实际需修改action属性指向处理逻辑 --><table><tr><th>书籍名:</th><td><input type="text" name="name"></td></tr><tr><th>书籍价格:</th><td><input type="text" name="price"></td></tr><tr><th>出版社:</th><td><input type="text" name="publisher"></td></tr><tr><td colspan="2"><input type="submit" value="确认添加"></td></tr></table></form>
</div></body>
</html>
update.jsp
<%@ page import="com.ghx.entity.User" %><%--Created by IntelliJ IDEA.User: lenovoDate: 2024/12/4Time: 10:31To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><style>/* 全局样式重置,去除浏览器默认样式差异 */* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: 'Roboto', sans-serif; /* 使用更现代的字体 */background-color: #eef2f7; /* 淡蓝色系背景,营造清新氛围 */display: flex;justify-content: center;align-items: center;min-height: 100vh;}/* 主要内容容器样式 */.main-container {width: 500px; /* 设定合适的宽度 */background-color: white;border-radius: 8px; /* 较大的圆角,更显柔和 */box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 柔和阴影效果 */overflow: hidden; /* 隐藏超出部分,确保圆角效果正常显示 */}/* 标题样式 */h2 {background-color: cornflowerblue; /* 标题栏蓝色背景 */color: white;text-align: center;padding: 15px 0;margin-bottom: 20px;}table {width: 100%;border-collapse: collapse;margin-bottom: 20px;}th, td {border-bottom: 1px solid #e0e0e0; /* 仅底部显示边框,简洁风格 */padding: 12px 20px;text-align: left;}th {font-weight: normal; /* 表头字体不加粗,更显简洁 */color: #777; /* 表头文字灰色,区分数据 */}input[type="text"] {width: 100%;padding: 8px;border: 1px solid #ccc;border-radius: 4px;background-color: #f9f9f9; /* 输入框浅灰色背景,更清晰 */color: #333; /* 输入框文字颜色 */outline: none; /* 去除输入框聚焦时的默认边框 */transition: background-color 0.2s ease; /* 背景色过渡效果 */}input[type="text"]:focus {background-color: white; /* 输入框聚焦时变白,增强交互感 */}input[type="submit"] {display: block;width: 100%;padding: 10px 0;background-color: #2ecc71; /* 绿色提交按钮,更醒目积极 */color: white;border: none;border-radius: 4px;cursor: pointer;font-size: 16px;transition: background-color 0.3s ease; /* 背景色过渡效果 */}input[type="submit"]:hover {background-color: #27ae60; /* 悬停时加深绿色 */}</style>
</head>
<body>
<c:if test="${sessionScope.userinfo==null}"><c:redirect url="login.jsp"></c:redirect>
</c:if><div class="main-container"><h2>书籍信息</h2><form action="/BookServlet?method=update" method="post"> <!-- 添加表单标签,假设提交到当前页面,实际需修改action属性指向处理逻辑 --><table><tr><th>书籍id:</th><td><input type="text" value="${bookid.id}" name="id" readonly></td></tr><tr><th>书籍名:</th><td><input type="text" value="${bookid.name}" name="name"></td></tr><tr><th>书籍价格:</th><td><input type="text" value="${bookid.price}" name="price"></td></tr><tr><th>出版社:</th><td><input type="text" value="${bookid.publisher}" name="publisher"></td></tr><tr><td colspan="2"><input type="submit" value="确认添加"></td></tr></table></form>
</div></body>
</html>