使用Servlet+JSP实现学生管理系统
Posted SmallCuteMonkey
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Servlet+JSP实现学生管理系统相关的知识,希望对你有一定的参考价值。
文章目录
- 使用Servlet+JSP实现学生管理系统
- eg1: 使用servlet来实现登录功能
- eg2: 使用servlet来实现登录功能
- eg3: 使用Servlet实现注册功能
- eg4: 使用Servlet实现查询所有学生信息功能
- eg5: 实现在首页展示当前用户名功能,退出系统功能,展示当前服务器总在线人数功能
- eg6: 使用Servlet实现添加、删除和修改学生信息功能
- eg7: 使用Servlet实现学生信息的分页展示
- eg8: 使用Servlet实现学生头像的上传功能
- eg9: 实现在项目中添加安全过滤器,用户未经登录不能访问系统,通过Filter统一实现设置字符编码
- **eg10:通过Listener来实现统计在线人数功能:**
- eg10: 使用jquery+ajax实现添加用户时自动检查用户名是否已存在,并给予相应提示功能
- eg11:实现首页上左右布局:
- eg12:实现正则验证:
- eg13: 使用cookie完成记住密码功能和异步登录功能
- eg14: 批量删除功能
- eg15: 模糊查询和区间查询功能
- eg16: 实现往数据库中批量导入100条数据
- eg17: 实现通过Echarts图表实现相同地域的学生个数的饼状图显示
- eg18: 连表查询一对一查询所有
- eg19: 实现角色权限管理
- eg20: 使用maven创建工程
使用Servlet+JSP实现学生管理系统
eg1: 使用servlet来实现登录功能
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录页面</h1>
<!--前端访问后台资源 不加/-->
<form action="login" method="post">
用户名: <input type="text" name="username"><br/>
密码: <input type="password" name="password"><br/>
爱好: <input type="checkbox" name="love" value="1">学习
<input type="checkbox" name="love" value="2">篮球
<input type="checkbox" name="love" value="3">游戏<br/>
<input type="submit" value="登录">
</form>
</body>
</html>
LoginServlet:
package com.jishou.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 = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post请求。。。。。");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get请求。。。。");
}
}
登录逻辑里面取前台用户输入的参数:
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//登录的处理逻辑
//1. 取前台表单的参数 request
/*
public String getParameter(String name) 返回指定name对应的参数的值
public String[] getParameterValues(String name) 返回指定name对应的一组参数值,返回值是数组
public Enumeration getParameterNames() 返回所有客户请求的参数名
*/
//2. 登录处理
//参数名必须和前台表单name属性值一致
request.setCharacterEncoding("utf-8");//设置请求编码 放在第一行
String username = request.getParameter("username");//取用户名
String password = request.getParameter("password");//取密码
String[] loves = request.getParameterValues("love");//取爱好
System.out.println("用户名: "+username+" 密码:"+password);
if(loves!=null&&loves.length>0){
for(String love: loves){
System.out.println("爱好: "+love);
}
}
//3. 产生响应 成功或者失败
//通过response响应对象输出内容到浏览器里面
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");//说明以html方式来响应
PrintWriter out = response.getWriter();//获取字符输出流
out.println("用户名是:"+username+"密码是: "+password);
out.flush();//刷新流
out.close();//关闭流
}
}
url访问:
http://localhost:8080/servlet02_2_war_exploded/login.html
eg2: 使用servlet来实现登录功能
1.创建数据库表 mysql
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-45U3jrnY-1629530327479)(img\\user.png)]
2.创建web project
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oQN1wbt1-1629530327483)(img\\stuManage.png)]
3. 在web目录下创建登录页面 login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录页面</h1>
<!--前端访问后台资源 不加/-->
<form action="login" method="post">
用户名: <input type="text" name="username"><br/>
密码: <input type="password" name="password"><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
4.编写实体类User
package com.jishou.pojo;
public class User {
private int id;
private String username;
private String password;
public User() {
}
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\\'' +
", password='" + password + '\\'' +
'}';
}
}
5.编写数据访问层 UserDao接口 和 接口实现类
导入mysql依赖,复制到web–web-inf下的lib目录底下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-U9JW1JRK-1629530327484)(img\\mysql.png)]
注意: web项目中mysql依赖包必须复制到web-inf下面的lib目录里面
吧mysql依赖引入到该工程里面
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4zKaEPkC-1629530327486)(img\\yilai1.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GFb4IRZD-1629530327488)(img\\yilai2.png)]
数据库连接工具类 DBUtil
package com.jishou.util;
import java.sql.*;
public class DBUtil {
private static String driverClassName="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf8";
private static String username="root";
private static String password="123456";
static{
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs){
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}catch (SQLException e){
e.printStackTrace();
}
}
public static void close(Connection conn, PreparedStatement pstmt){
try {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}catch (SQLException e){
e.printStackTrace();
}
}
}
UserDao
package com.jishou.dao;
import com.jishou.pojo.User;
public interface UserDao {
public User queryOneUser(User user) ;
public int insertUser(User user);
}
UserDaoImpl
package com.jishou.dao;
import com.jishou.pojo.User;
import com.jishou.util.DBUtil;
import java.sql.*;
public class UserDaoImpl implements UserDao{
/*@Override
public User queryOneUser(User user) throws SQLException, ClassNotFoundException {
//1.加载驱动 建厂
String driverClassName="com.mysql.jdbc.Driver";
String url="jdbc://mysql:localhost:3306/test?characterEncoding=utf8";
String username="root";
String password="123456";
String sql="select * from user where username=? and password=?";
User u=null;
Class.forName(driverClassName);
//2.获取连接 修路
Connection conn = DriverManager.getConnection(url, username, password);
//3.创建PreparedStatement 造车
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,user.getUsername());
pstmt.setString(2,user.getPassword());
//4.执行操作 拉货
ResultSet rs = pstmt.executeQuery();
//5.处理结果集 查询会有结果集 增删改 没有 处理货物
if(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String pass = rs.getString(3);
u=new User(id,name,pass);
}
//6. 关闭资源 路 砸了 货物 毁了 车 砸了
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
return u;
}*/
public User queryOneUser(User user) {
//1.加载驱动 建厂
String sql="select * from user where username=? and password=?";
User u=null;
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
//2.获取连接 修路
conn= DBUtil.getConnection();
//3.创建PreparedStatement 造车
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
//4.执行操作 拉货
rs = pstmt.executeQuery();
//5.处理结果集 查询会有结果集 增删改 没有 处理货物
if (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
String pass = rs.getString(3);
u = new User(id, name, pass);
}
}catch (SQLException e){
e.printStackTrace();
}
//6. 关闭资源 路 砸了 货物 毁了 车 砸了
DBUtil.close(conn,pstmt,rs);
return u;
}
@Override
public int insertUser(User user) {
return 0;
}
}
6.编写service层接口和实现类
UserService
package com.jishou.service;
import com.jishou.pojo.User;
public interface UserService {
//登录
public User login(User user);
//注册
public boolean register(User user);
}
UserServiceImpl
package com.jishou.service;
import com.jishou.dao.UserDao;
import com.jishou.dao.UserDaoImpl;
import com.jishou.pojo.User;
public class UserServiceImpl implements UserService{
private UserDao userDao=new UserDaoImpl();
@Override
public User login(User user) {
return userDao.queryOneUser(user);
}
@Override
public boolean register(User user) {
return false;
}
}
7.编写Servlet的登录实现逻辑
LoginServlet
package com.jishou.servlet;
import com.jishou.pojo.User;
import com.jishou.service.UserService;
import com.jishou.service.UserServiceImpl;
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 = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 取参数
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
User qtUser=new User(username,password);
//连数据库查询
User htUser = userService.login(qtUser);
//响应
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//判断是否登录成功
if(htUser!=null){
out.println("<h1>登录成功</h1>");
}else{
out.println("<h1>登录失败</h1>");
}
out.flush();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
8.浏览器url访问登录页面,展示运行效果
http://localhost:8080/stuManage_02_war_exploded/login.html
正常jdbc流程:
public User queryOneUser(User user) throws SQLException, ClassNotFoundException {
//1.加载驱动 建厂
String driverClassName="com.mysql.jdbc.Driver";
String url="jdbc://mysql:localhost:3306/test?characterEncoding=utf8";
String username="root";
String password="123456";
String sql="select * from user where username=? and password=?";
User u=null;
Class.forName(driverClassName);
//2.获取连接 修路
Connection conn = DriverManager.getConnection(url, username, password);
//3.创建PreparedStatement 造车
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,user.getUsername());
pstmt.setString(2,user.getPassword());
//4.执行操作 拉货
ResultSet rs = pstmt.executeQuery();
//5.处理结果集 查询会有结果集 增删改 没有 处理货物
if(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String pass = rs.getString(3);
u=new User(id,name,pass);
}
//6. 关闭资源 路 砸了 货物 毁了 车 砸了
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
return u;
}
eg3: 使用Servlet实现注册功能
-
在web目录下新建register.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>注册页面</h1> <!--前端访问路径都不加/ --> <form action="register" method="post"> 用户名: <input type="text" name="username"><br> 密码: <input type="password" name="password"><br> <input type="submit" value="注册"> </form> </body> </html>
-
编写数据访问层UserDao和实现类里面的注册逻辑
UserDao接口
public int insertUser(User user);
UserDaoImpl接口实现类
@Override public int insertUser(User user) { String sql="INSERT INTO user (username, password) VALUES ( ?, ?)"; Connection conn = DBUtil.getConnection(); PreparedStatement pstmt=null; int row=0; try { pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUsername()); pstmt.setString(2, user.getPassword()); row = pstmt.executeUpdate(); }catch(SQLException e) { e.printStackTrace(); }finally { DBUtil.close(pstmt,conn); } return row; }
-
编写service层注册逻辑
UserService接口:
public boolean register(User user);//注册
UserServiceImpl接口实现类
@Override public boolean register(User user) { int row = userDao.insertUser(user); if(row>0){ return true; } return false; }
-
编写RegisterServlet注册实现逻辑
RegisterServlet
package com.jishou.servlet; import com.jishou.pojo.User; import com.jishou.service.UserService; import com.jishou.service.UserServiceImpl; 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 = "RegisterServlet",urlPatterns = "/register") public class RegisterServlet extends HttpServlet { private UserService userService=new UserServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //取参 req.setCharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); User qtUser=new User(username,password); //链接数据库添加 boolean flag = userService.register(qtUser); /*resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); //响应 if(flag){ out.println("<h1>注册成功<h1>"); }else { out.println("<h1>注册失败<h1>"); } out.flush(); out.close();*/ //注册成功 需要跳转到登录页面,注册失败 需要 回到注册页面,继续注册 if(flag){ //重定向 就表示重新定位到一个地址 resp.sendRedirect("login.html"); }else{ resp.sendRedirect("register.html"); } } }
-
浏览器url访问测试,展示运行效果
http://localhost:8080/stuManage_04_war_exploded/register.html
eg4: 使用Servlet实现查询所有学生信息功能
-
创建数据库表
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kNu3TZEG-1629530327489)(img\\stu.png)]
-
编写实体类
Student
package com.jishou.pojo; import java.util.Date; public class Student { private Integer id; private String name; private Date birthday; private Integer age; private String address; private String photo; public Student() { } public Student(Integer id, String name, Date birthday, Integer age, String address, String photo) { this.id = id; this.name = name; this.birthday = birthday; this.age = age; this.address = address; this.photo = photo; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\\'' + ", birthday=" + birthday + ", age=" + age + ", address='" + address + '\\'' + ", photo='" + photo + '\\'' + '}'; } }
-
数据访问层StudentDao,StudentDaoImpl查询所有
StudentDao
package com.jishou.dao; import com.jishou.pojo.Student; import java.util.List; public interface StudentDao { public List<Student> queryAllStudents(); }
StudentDaoImpl
package com.jishou.dao; import com.jishou.pojo.Student; import com.jishou.util.DBUtil; import java.sql.*; import java.util.ArrayList; import java.util.List; public class StudentDaoImpl implements StudentDao{ @Override public List<Student> queryAllStudents() { String sql="select * from stu"; PreparedStatement pstmt=null; ResultSet rs=null; List<Student> list=new ArrayList<>(); //2. 获取连接 修路 Connection conn = DBUtil.getConnection(); try { //3. 创建PreparedStatement 造车 pstmt = conn.prepareStatement(sql); //4. 执行sql 拉货 rs = pstmt.executeQuery(); //5. 处理结果集 查询会有结果集 处理货物 while (rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); Date birthday = rs.getDate(3); int age = rs.getInt(4); String address = rs.getString(5); String photo = rs.getString(6); Student student=new Student(id,name,birthday,age,address,photo); list.add(student); } }catch (SQLException e){ e.printStackTrace(); }finally { //6. 关闭资源 货 车 路全都毁了 DBUtil.close(rs,pstmt,conn); } return list; } }
-
服务层service层接口和实现
StudentService
package com.jishou.service; import com.jishou.pojo.Student; import java.util.List; public interface StudentService { public List<Student> queryAllStudents(); }
StudentServiceImpl
package com.jishou.service; import com.jishou.dao.StudentDao; import com.jishou.dao.StudentDaoImpl; import com.jishou.pojo.Student; import java.util.List; public class StudentServiceImpl implements StudentService{ private StudentDao studentDao=new StudentDaoImpl(); @Override public List<Student> queryAllStudents() { return studentDao.queryAllStudents(); } }
-
查询所有的Servlet实现
ListServlet
package com.jishou.servlet; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; 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.net.ServerSocket; import java.util.List; @WebServlet(name = "ListServlet",urlPatterns = "/list") public class ListServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //查询所有学生 List<Student> list = studentService.queryAllStudents(); //吧学生信息放在request对象里面 req.setAttribute("list",list); //请求转发 req.getRequestDispatcher("list.jsp").forward(req,resp); } }
-
前端页面
list.jsp
<%@ page import="com.jishou.pojo.Student" %> <%@ page import="java.util.List" %> <%@ 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> </head> <body> <h1>学生管理系统</h1> <table> <tr> <td>编号</td> <td>姓名</td> <td>出生日期</td> <td>年龄</td> <td>地址</td> <td><a href="">添加学生</a></td> </tr> <c:forEach var="s" items="${requestScope.list}"> <tr> <td>${s.id}</td> <td>${s.name}</td> <td>${s.birthday}</td> <td>${s.age}</td> <td>${s.address}</td> <td> <a href="">修改</a> <a href="">删除</a> </td> </tr> </c:forEach> </table> </body> </html>
-
浏览器url访问
http://localhost:8080/stuManage_04_war_exploded/list
eg5: 实现在首页展示当前用户名功能,退出系统功能,展示当前服务器总在线人数功能
LoginServlet:
package com.jishou.servlet;
import com.jishou.pojo.User;
import com.jishou.service.UserService;
import com.jishou.service.UserServiceImpl;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
private Integer count=0;//总在线人数
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 取前台参数
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
User qtuser=new User(username,password);
//2. 连接数据库查询
User htuser = userService.login(qtuser);
//3. 判断登录是否成功
if(htuser!=null){
//登录成功
HttpSession session = request.getSession();
ServletContext servletContext = request.getServletContext();
session.setAttribute("user",htuser);
servletContext.setAttribute("count",++count);
response.sendRedirect("list");
}else{
//登录失败
response.sendRedirect("login.html");
}
}
}
LogOutServlet:
package com.jishou.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(name = "LogOutServlet",urlPatterns = "/logout")
public class LogOutServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.invalidate();//session失效
//让总在线人数减少
ServletContext servletContext = req.getServletContext();
Integer count = (Integer) servletContext.getAttribute("count");
servletContext.setAttribute("count",--count);
resp.sendRedirect("login.html");
}
}
list.jsp
加上下面代码:
<%
List<Student> list = (List<Student>) request.getAttribute("list");
User user = (User) request.getSession().getAttribute("user");
%>
<div id="login">欢迎<%=user.getUsername()%>登录 <a href="logout">退出系统</a></div>
<div id="count">当前共有<%=application.getAttribute("count")%>人在线</div>
eg6: 使用Servlet实现添加、删除和修改学生信息功能
思路:
添加:
<a href="add.jsp">添加学生</a>
当在主页面点击添加超链接时--->跳转到add.jsp----->add.jsp表单里面输入相应值时,跳转AddServlet,实现添加逻辑
----->AddServlet实现添加功能------>添加成功,跳转到ListServlet,添加失败,回到添加页面add.jsp
注意: 数据库表主键id自增,所以不用添加id属性
删除:
<a href="delete?id=<%=s.getId()%>">删除</a>
删除要根据id来删除该条数据信息;当点击删除超链接时,需要跳转到DeleteServlet,并吧要删除的id传过去,删除成功,再重新查询所有
超链接访问属于get请求方式,get请求走浏览器地址栏传参,所以href="delete?id=<%=s.getId()%>" 即可
修改:
修改的实现逻辑是在update.jsp里面在原来老数据的基础之上吧老数据修改成新数据,所以,修改的逻辑需要先根据id来查询单个,查询出来的对象信息回显到update.jsp表单里面,用户再在老数据的基础之上输入新数据,点击修改按钮,实现后台的修改功能;修改成功,回到主页面,查询所有;修改失败,回到update.jsp
list.jsp <a href="load?id=<%=s.getId()%>">修改</a> ----->LoadServlet 根据id查询单个---->
update.jsp 实现老数据回显------>用户在老数据的基础之上吧老数据修改成新数据,submit修改按钮----->
UpdateServlet 修改的后台实现----->修改成功,ListServlet;修改失败,回到update.jsp
注意: 由于数据库中birthday是date类型,他对应的java代码中的类型为java.sql.Date; 而平时java代码使用最多的是java.util.Date.
所以就涉及到不同的日期类型之间的转换,最好的方式就是写个日期工具类DateUtil:
DateUtil:
package com.jishou.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
// util.date转换成sql.date
public static java.sql.Date toSqlDate(Date date){
return new java.sql.Date(date.getTime());
}
// sql.date转换成util.date
public static Date toUtilDate(java.sql.Date date){
return new java.util.Date(date.getTime());
}
//String 转换成发 util.Date
public static Date strToUtilDate(String dateStr){
Date date = null;
//注意format的格式要与日期String的格式相匹配
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
date = sdf.parse(dateStr);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
//util.Date转换为String
public static String dateToStr(Date date){
String dateStr = "";
//format的格式可以任意
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
dateStr = sdf.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return dateStr;
}
}
添加功能:
- 前台:add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<center>
<h1>添加学生</h1>
<form action="add" method="post">
<table width="50%" height="35%">
<tr>
<td>姓名</td>
<td><input type="text" name="sname"></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>生日</td>
<td><input type="date" name="birthday"></td>
</tr>
<tr>
<td>地址</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td>头像</td>
<td><input type="text" name="photo"></td>
</tr>
<tr>
<td><input type="submit" value="添加"></td>
<td><input type="reset" name="重置"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
-
后台:dao层:
StudentDao:
package com.jishou.dao;
import com.jishou.pojo.Student;
import java.util.List;
public interface StudentDao {
public List<Student> queryAllStudents();
public int addStudent(Student student);
public int deleteStudentById(Integer id);
public int updateStudent(Student student);
public Student queryOneStudentById(Integer id);
}
StudentDaoImpl:
package com.jishou.dao;
import com.jishou.pojo.Student;
import com.jishou.util.DBUtil;
import com.jishou.util.DateUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentDaoImpl implements StudentDao{
@Override
public List<Student> queryAllStudents() {
String sql="select * from stu";
Connection conn = DBUtil.getConnection();
List<Student> list = new ArrayList<>();
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
pstmt= conn.prepareStatement(sql);
rs= pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
String sname = rs.getString(2);
int age = rs.getInt(3);
Date birthday = rs.getDate(4);
String address = rs.getString(5);
String photo = rs.getString(6);
Student student = new Student(id, sname, age, birthday, address, photo);
list.add(student);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(rs,pstmt,conn);
}
return list;
}
@Override
public int addStudent(Student student) {
String sql="INSERT INTO stu ( `sname`, `age`, `birthday`, `address`, `photo`) VALUES (?, ?, ?,?,?)";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
int row=0;
try {
pstmt= conn.prepareStatement(sql);
pstmt.setString(1,student.getSname());
pstmt.setInt(2,student.getAge());
pstmt.setDate(3, DateUtil.toSqlDate(student.getBirthday()));
pstmt.setString(4,student.getAddress());
pstmt.setString(5,student.getPhoto());
row= pstmt.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(pstmt,conn);
}
return row;
}
@Override
public int deleteStudentById(Integer id) {
String sql="delete from stu where id=?";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
int row=0;
try {
pstmt= conn.prepareStatement(sql);
pstmt.setInt(1,id);
row= pstmt.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(pstmt,conn);
}
return row;
}
@Override
public int updateStudent(Student student) {
String sql="UPDATE stu SET `sname`=?, `age`=?, `birthday`=?, `address`=?, `photo`=? WHERE `id`=?";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
int row=0;
try {
pstmt= conn.prepareStatement(sql);
pstmt.setString(1,student.getSname());
pstmt.setInt(2,student.getAge());
pstmt.setDate(3, DateUtil.toSqlDate(student.getBirthday()));
pstmt.setString(4,student.getAddress());
pstmt.setString(5,student.getPhoto());
pstmt.setInt(6,student.getId());
row= pstmt.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(pstmt,conn);
}
return row;
}
@Override
public Student queryOneStudentById(Integer id) {
String sql="select * from stu where id=?";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
ResultSet rs=null;
Student student=null;
try {
pstmt= conn.prepareStatement(sql);
pstmt.setInt(1,id);
rs= pstmt.executeQuery();
if (rs.next()) {
int idd = rs.getInt(1);
String sname = rs.getString(2);
int age = rs.getInt(3);
Date birthday = rs.getDate(4);
String address = rs.getString(5);
String photo = rs.getString(6);
student = new Student(idd, sname, age, birthday, address, photo);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(rs,pstmt,conn);
}
return student;
}
}
- service层:
StudentService:
package com.jishou.service;
import com.jishou.pojo.Student;
import java.util.List;
public interface StudentService {
public List<Student> queryAllStudents();
public boolean addStudent(Student student);
public boolean deleteStudentById(Integer id);
public boolean updateStudent(Student student);
public Student queryOneStudentById(Integer id);
}
StudentServiceImpl:
package com.jishou.service;
import com.jishou.dao.StudentDao;
import com.jishou.dao.StudentDaoImpl;
import com.jishou.pojo.Student;
import java.util.List;
public class StudentServiceImpl implements StudentService{
private StudentDao studentDao=new StudentDaoImpl();
@Override
public List<Student> queryAllStudents() {
return studentDao.queryAllStudents();
}
@Override
public boolean addStudent(Student student) {
int row = studentDao.addStudent(student);
if(row>0){
return true;
}
return false;
}
@Override
public boolean deleteStudentById(Integer id) {
int row = studentDao.deleteStudentById(id);
if(row>0){
return true;
}
return false;
}
@Override
public boolean updateStudent(Student student) {
int row = studentDao.updateStudent(student);
if(row>0){
return true;
}
return false;
}
@Override
public Student queryOneStudentById(Integer id) {
return studentDao.queryOneStudentById(id);
}
}
- servlet:
AddServlet:
package com.jishou.servlet;
import com.jishou.pojo.Student;
import com.jishou.service.StudentService;
import com.jishou.service.StudentServiceImpl;
import com.jishou.util.DateUtil;
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.Date;
@WebServlet(name = "AddServlet",urlPatterns = "/add")
public class AddServlet extends HttpServlet {
private StudentService studentService=new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//取参数值
req.setCharacterEncoding("utf-8");
String sname = req.getParameter("sname");
//将String的年龄转换为int类型
Integer age = Integer.parseInt(req.getParameter("age"));
String date = req.getParameter("birthday");
//将String日期类型转换为java.util.Date
Date birthday = DateUtil.strToUtilDate(date);
String address = req.getParameter("address");
String photo = req.getParameter("photo");
Student student=new Student(sname,age,birthday,address,photo);
//实现修改逻辑
boolean flag = studentService.addStudent(student);
if(flag){
//添加成功
resp.sendRedirect("list");
}else{
//添加失败
resp.sendRedirect("add.jsp");
}
}
}
删除功能:
- 前台:list.jsp:
<a href="delete?id=<%=s.getId()%>">删除</a>
- 后台:DeleteServlet:
package com.jishou.servlet;
import com.jishou.service.StudentService;
import com.jishou.service.StudentServiceImpl;
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 = "DeleteServlet",urlPatterns = "/delete")
public class DeleteServlet extends HttpServlet {
private StudentService studentService=new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//取参
String ids = req.getParameter("id");
//类型转换
Integer id=Integer.parseInt(ids);
boolean flag = studentService.deleteStudentById(id);
if(flag){
resp.sendRedirect("list");
}
}
}
修改功能:
- list.jsp:
<a href="load?id=<%=s.getId()%>">修改</a>
-
LoadServlet:
package com.jishou.servlet; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; 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 = "LoadServlet",urlPatterns = "/load") public class LoadServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Integer id=Integer.parseInt(req.getParameter("id")); //根据id查询单个 Student student = studentService.queryOneStudentById(id); req.setAttribute("s",student); //请求转发 req.getRequestDispatcher("update.jsp").forward(req,resp); } }
-
update.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <center> <h1>修改学生</h1> <form action="update" method="post"> <table width="50%" height="35%"> <tr> <td>编号</td> <td><input type="text" name="id" value="${s.id}" readonly></td> </tr> <tr> <td>姓名</td> <td><input type="text" name="sname" value="${s.sname}"></td> </tr> <tr> <td>年龄</td> <td><input type="text" name="age" value="${s.age}"></td> </tr> <tr> <td>生日</td> <td><input type="date" name="birthday" value="${s.birthday}"></td> </tr> <tr> <td>地址</td> <td><input type="text" name="address" value="${s.address}"></td> </tr> <tr> <td>头像</td> <td><input type="text" name="photo" value="${s.photo}"></td> </tr> <tr> <td><input type="submit" value="修改"></td> <td><input type="reset" name="重置"></td> </tr> </table> </form> </center> </body> </html>
-
UpdateServlet:
package com.jishou.servlet; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; import com.jishou.util.DateUtil; 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.Date; @WebServlet(name = "UpdateServlet",urlPatterns = "/update") public class UpdateServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //取参数值 req.setCharacterEncoding("utf-8"); Integer id = Integer.parseInt(req.getParameter("id")); String sname = req.getParameter("sname"); //将String的年龄转换为int类型 Integer age = Integer.parseInt(req.getParameter("age")); String date = req.getParameter("birthday"); //将String日期类型转换为java.util.Date Date birthday = DateUtil.strToUtilDate(date); String address = req.getParameter("address"); String photo = req.getParameter("photo"); Student student=new Student(id,sname,age,birthday,address,photo); //实现修改逻辑 boolean flag = studentService.updateStudent(student); if(flag){ //修改成功 resp.sendRedirect("list"); }else{ //修改失败 resp.sendRedirect("update.jsp"); } } }
eg7: 使用Servlet实现学生信息的分页展示
-
编写PageBean : PageBean对象就是当前页面对象,包含了当前页面所包含的所有信息
package com.jishou.pojo; import java.util.List; /** * 存放分页相关的数据 * */ public class PageBean<T> { //基本属性 private int currentPageNum;//当前页数,由用户指定 private int pageSize = 5;//每页显示的条数,固定的 private int totalRecords;//总记录条数,数据库查出来的 private int totalPageNum;//总页数,计算出来的 private List<T> list;//已经分好页的结果集 public int getCurrentPageNum() { return currentPageNum; } public void setCurrentPageNum(int currentPageNum) { this.currentPageNum = currentPageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalRecords() { return totalRecords; } public void setTotalRecords(int totalRecords) { this.totalRecords = totalRecords; //总记录数固定,页面大小固定,计算出总页数 if(this.totalRecords%this.pageSize==0){ this.totalPageNum=this.totalRecords/this.pageSize; }else{ this.totalPageNum=this.totalRecords/this.pageSize+1; } } public int getTotalPageNum() { return totalPageNum; } public void setTotalPageNum(int totalPageNum) { this.totalPageNum = totalPageNum; } public List getList() { return list; } public void setList(List list) { this.list = list; } @Override public String toString() { return "PageBean{" + "currentPageNum=" + currentPageNum + ", pageSize=" + pageSize + ", totalRecords=" + totalRecords + ", totalPageNum=" + totalPageNum + ", list=" + list + '}'; } }
-
dao层编写 获取总记录数和分页查询的逻辑
StudentDao:
//查询总记录数 public int getTotalRecords(); //分页查询学生信息 参数为当前页和页面大小 public List<Student> queryStudentsByPage(int currentPage,int pageSize);
StudentDaoImpl:
@Override public int getTotalRecords() { String sql="select count(*) from stu"; Connection conn = DBUtil.getConnection(); PreparedStatement pstmt=null; ResultSet rs=null; int count=0; try { pstmt= conn.prepareStatement(sql); rs= pstmt.executeQuery(); if (rs.next()) { count = rs.getInt(1); } }catch (SQLException e){ e.printStackTrace(); }finally { DBUtil.close(rs,pstmt,conn); } return count; } @Override public List<Student> queryStudentsByPage(int currentPage, int pageSize) { String sql="select * from stu limit ?,?"; Connection conn = DBUtil.getConnection(); List<Student> list = new ArrayList<>(); PreparedStatement pstmt=null; ResultSet rs=null; try { pstmt= conn.prepareStatement(sql); //注意第一个参数值的写法 pstmt.setInt(1,(currentPage-1)*pageSize); pstmt.setInt(2,pageSize); rs= pstmt.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String sname = rs.getString(2); int age = rs.getInt(3); Date birthday = rs.getDate(4); String address = rs.getString(5); String photo = rs.getString(6); Student student = new Student(id, sname, age, birthday, address, photo); list.add(student); } }catch (SQLException e){ e.printStackTrace(); }finally { DBUtil.close(rs,pstmt,conn); } return list; }
-
service层代码
StudentService:
//分页查询学生信息 参数为当前页和页面大小 public PageBean<Student> queryStudentsByPage(int currentPage, int pageSize);
StudentServiceImpl:
@Override public PageBean<Student> queryStudentsByPage(int currentPage, int pageSize) { List<Student> students = studentDao.queryStudentsByPage(currentPage, pageSize); int total = studentDao.getTotalRecords(); PageBean<Student> pageBean=new PageBean<>(); pageBean.setPageSize(pageSize);//设置页面大小 pageBean.setTotalRecords(total);//设置总记录数 pageBean.setCurrentPageNum(currentPage);//设置当前页 pageBean.setList(students);//设置当前页数据 return pageBean; }
-
ListPageServlet 分页的Servlet
ListPageServlet:
package com.jishou.servlet; import com.jishou.pojo.PageBean; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; 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 = "ListPageServlet",urlPatterns = "/listpage") public class ListPageServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //取当前页 String currentPage= req.getParameter("currentPage"); //第一次访问,默认currentPage 访问第一页 if(currentPage==null) { currentPage = "1"; } Integer currentPageNum=Integer.parseInt(currentPage); //页面大小暂设置成固定值3 //分页查询所有 PageBean<Student> pageBean = studentService.queryStudentsByPage(currentPageNum,3); //servlet重在业务逻辑,取值传值 jsp侧重于页面显示 req.setAttribute("page",pageBean); //请求转发 req.getRequestDispatcher("listpage.jsp").forward(req,resp); } }
注意:
登录成功之后跳转到llistpage
response.sendRedirect("listpage");
-
前端 listpage.jsp
<%@ page import="com.jishou.pojo.Student" %> <%@ page import="java.util.List" %> <%@ page import="com.jishou.pojo.User" %> <%@ page import="com.jishou.pojo.PageBean" %> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> <style> #login{ float: left; } #count{ float: right; } </style> </head> <body> <div id="login">欢迎${sessionScope.user.username}登录 <a href="logout">退出系统</a></div> <div id="count">当前共有${applicationScope.count}人在线</div> <center> <h1>学生管理系统</h1> <table width="70%" height="50%"> <tr> <td>头像</td> <td>Id</td> <td>姓名</td> <td>年龄</td> <td>生日</td> <td>地址</td> <td> <a href="add.jsp">添加学生</a> </td> </tr> <c:if test="${requestScope.page!=null}"> <c:if test="${requestScope.page.list ne null and requestScope.page.list.size() gt 0}"> <c:forEach var="s" items="${requestScope.page.list}"> <tr> <td> <img src="${s.photo}" width="20px" height="20px"/> </td> <td>${s.id}</td> <td>${s.sname}</td> <td>${s.age}</td> <td>${s.birthday}</td> <td>${s.address}</td> <td> <a href="load?id
以上是关于使用Servlet+JSP实现学生管理系统的主要内容,如果未能解决你的问题,请参考以下文章
使用Jsp+Servlet+JavaBean技术做学生成绩管理系统
JSP+Servlet+JDBC+mysql实现的学生成绩管理系统