JavaWeb基于Jsp+Servlet的学生信息管理系统(源码+SQL文件+实验报告)分享

     阅读:51

Java Web项目,使用了Jsp+Servlet技术
注册+登录+验证码+学生信息增删改查+分页查询+jsp+servlet+JavaBean+MySQL+tomcat
此项目为最基本的Java web课程设计。只需要对数据、数据类型进行修改,就可以作为其他名称的项目。
主要技术:Jsp+Servlet+Mysql+Tomcat+Eclipse
适用场合:Java课程设计/Java大作业
项目类型:JAVA WEB项目
用户类型:管理员
开发工具:Eclipse
数据库表:2张
功能介绍:实现注册登录,分页查询,以及对学生信息的增删改查。

1.注册
2.登录
3.分页查询
4.添加学生
5.删除学生
6.修改学生
7.查找学生
8.分页查询

更多的Java项目源码+数据库尽在:“那条学长”
在这里插入图片描述
回复“学生信息管理系统”免费获取

一些适用于毕业设计或课程设计的Java Web项目
Jsp+Servlet的学生上课签到打卡系统【原创开发】
Jsp+Servlet图书管理系统【原创开发】
Jsp+Servlet的新闻管理系统【原创开发】
Jsp+Servlet的外卖配送系统/在线点餐系统【原创开发】
Java Web在线商城(SSM)

1.功能介绍

1.1注册

请添加图片描述

1.2登录

请添加图片描述

1.3分页查询学生信息、批量删除

请添加图片描述

1.4添加学生信息

请添加图片描述

1.5修改学生信息

请添加图片描述

2.项目结构

在这里插入图片描述

3.代码展示

3.1PageBean.java

package cn.student.bean;

import java.util.List;

/**
 * 分页对象
 */
public class PageBean<T> {
    private int totalCount; // 总记录数
    private int totalPage ; // 总页码
    private List<T> list ; // 每页的数据
    private int currentPage ; //当前页码
    private int rows;//每页显示的记录数
    public int getTotalCount() {
        return totalCount;
    }
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
    public int getTotalPage() {
        return totalPage;
    }
    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
    public List<T> getList() {
        return list;
    }
    public void setList(List<T> list) {
        this.list = list;
    }
    public int getCurrentPage() {
        return currentPage;
    }
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    public int getRows() {
        return rows;
    }
    public void setRows(int rows) {
        this.rows = rows;
    }
    @Override
    public String toString() {
        return "PageBean{" +
                "totalCount=" + totalCount +
                ", totalPage=" + totalPage +
                ", list=" + list +
                ", currentPage=" + currentPage +
                ", rows=" + rows +
                '}';
    }
}

3.2StudentDao.java

package cn.student.dao;
import java.util.List;
import java.util.Map;
import cn.student.bean.Student;
/*
 * 用户操作的DAO
 */
public interface StudentDao {
    public List<Student> findAll();
    //Student findUserByUsernameAndPassword(String username, String password);
    void add(Student student);
    void delete(int id);
    Student findById(int i);
    void update(Student student);
    /**
     * 查询总记录数
     * @return
     * @param condition
     */
    int findTotalCount(Map<String, String[]> condition);
    /**
     * 分页查询每页记录
     * @param start
     * @param rows
     * @param condition
     * @return
     */
    List<Student> findByPage(int start, int rows, Map<String, String[]> condition);
}

3.3StudentDaoImpl.java

package cn.student.dao.impl;
import cn.student.bean.Student;
import cn.student.dao.StudentDao;
import cn.student.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class StudentDaoImpl implements StudentDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<Student> findAll() {
        //使用JDBC操作数据库...
        //1.定义sql
        String sql = "select * from student";
        List<Student> students = template.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
        return students;
    }
    @Override
    public void add(Student student) {
        //1.定义sql
        String sql = "insert into student values(null,?,?,?,?,?,?)";
        //2.执行sql
        template.update(sql, student.getName(), student.getGender(), student.getAge(), student.getAddress(), student.getQq(), student.getEmail());
    }
    @Override
    public void delete(int id) {
        //1.定义sql
        String sql = "delete from student where id = ?";
        //2.执行sql
        template.update(sql, id);
    }
    @Override
    public Student findById(int id) {
        String sql = "select * from student where id = ?";
        return template.queryForObject(sql, new BeanPropertyRowMapper<Student>(Student.class), id);
    }
    @Override
    public void update(Student student) {
        String sql = "update student set name = ?,gender = ? ,age = ? , address = ? , qq = ?, email = ? where id = ?";
        template.update(sql, student.getName(), student.getGender(), student.getAge(), student.getAddress(), student.getQq(), student.getEmail(), student.getId());
    }
    @Override
    public int findTotalCount(Map<String, String[]> condition) {
        //1.定义模板初始化sql
        String sql = "select count(*) from student where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //2.遍历map
        Set<String> keySet = condition.keySet();
        //定义参数的集合
        List<Object> params = new ArrayList<Object>();
        for (String key : keySet) {
            //排除分页条件参数
            if("currentPage".equals(key) || "rows".equals(key)){
                continue;
            }
            //获取value
            String value = condition.get(key)[0];
            //判断value是否有值
            if(value != null && !"".equals(value)){
                //有值
                sb.append(" and "+key+" like ? ");
                params.add("%"+value+"%");//?条件的值
            }
        }
        System.out.println(sb.toString());
        System.out.println(params);
        return template.queryForObject(sb.toString(),Integer.class,params.toArray());
    }
    @Override
    public List<Student> findByPage(int start, int rows, Map<String, String[]> condition) {
        String sql = "select * from student  where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //2.遍历map
        Set<String> keySet = condition.keySet();
        //定义参数的集合
        List<Object> params = new ArrayList<Object>();
        for (String key : keySet) {
            //排除分页条件参数
            if("currentPage".equals(key) || "rows".equals(key)){
                continue;
            }
            //获取value
            String value = condition.get(key)[0];
            //判断value是否有值
            if(value != null && !"".equals(value)){
                //有值
                sb.append(" and "+key+" like ? ");
                params.add("%"+value+"%");//?条件的值
            }
        }
        //添加分页查询
        sb.append(" limit ?,? ");
        //添加分页查询参数值
        params.add(start);
        params.add(rows);
        sql = sb.toString();
        System.out.println(sql);
        System.out.println(params);
        return template.query(sql,new BeanPropertyRowMapper<Student>(Student.class),params.toArray());
    }
}

3.4StudentService.java

package cn.student.service;

import java.util.List;
import java.util.Map;

import cn.student.bean.PageBean;
import cn.student.bean.Student;

/**
 * 用户管理的业务接口
 */
public interface StudentService {

    /**
     * 查询所有用户信息
     * @return
     */
    public List<Student> findAll();

    /**
     * 登录方法
     * @param student
     * @return
     */
   // Student login(Student student);

    /**
     * 保存User
     * @param student
     */
    void addUser(Student student);

    /**
     * 根据id删除User
     * @param id
     */
    void deleteUser(String id);

    /**
     * 根据id查询
     * @param id
     * @return
     */
    Student findUserById(String id);

    /**
     * 修改用户信息
     * @param student
     */
    void updateUser(Student student);

    /**
     * 批量删除用户
     * @param ids
     */
    void delSelectedUser(String[] ids);

    /**
     * 分页条件查询
     * @param currentPage
     * @param rows
     * @param condition
     * @return
     */
    PageBean<Student> findUserByPage(String currentPage, String rows, Map<String, String[]> condition);
}

3.5StudentServiceImpl.java

package cn.student.service.impl;

import cn.student.bean.PageBean;
import cn.student.bean.Student;
import cn.student.dao.StudentDao;
import cn.student.dao.impl.StudentDaoImpl;
import cn.student.service.StudentService;
import java.util.List;
import java.util.Map;
public class StudentServiceImpl implements StudentService {
    private StudentDao dao = new StudentDaoImpl();
    @Override
    public List<Student> findAll() {
        //调用Dao完成查询
        return dao.findAll();
    }

   // @Override
    //public Student login(Student student) {
       // return dao.findUserByUsernameAndPassword(student.getUsername(), student.getPassword());
    //}
    @Override
    public void addUser(Student student) {
        dao.add(student);
    }
    @Override
    public void deleteUser(String id) {
        dao.delete(Integer.parseInt(id));
    }
    @Override
    public Student findUserById(String id) {
        return dao.findById(Integer.parseInt(id));
    }

    @Override
    public void updateUser(Student student) {
        dao.update(student);
    }
    @Override
    public void delSelectedUser(String[] ids) {
        if(ids != null && ids.length > 0){
            //1.遍历数组
            for (String id : ids) {
                //2.调用dao删除
                dao.delete(Integer.parseInt(id));
            }
        }
    }
    @Override
    public PageBean<Student> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {

        int currentPage = Integer.parseInt(_currentPage);
        int rows = Integer.parseInt(_rows);

        if(currentPage <=0) {
            currentPage = 1;
        }
        //1.创建空的PageBean对象
        PageBean<Student> pb = new PageBean<Student>();
        //2.设置参数
        pb.setCurrentPage(currentPage);
        pb.setRows(rows);

        //3.调用dao查询总记录数
        int totalCount = dao.findTotalCount(condition);
        pb.setTotalCount(totalCount);
        //4.调用dao查询List集合
        //计算开始的记录索引
        int start = (currentPage - 1) * rows;
        List<Student> list = dao.findByPage(start,rows,condition);
        pb.setList(list);

        //5.计算总页码
        int totalPage = (totalCount % rows)  == 0 ? totalCount/rows : (totalCount/rows) + 1;
        pb.setTotalPage(totalPage);
        return pb;
    }
}

3.6UserServlet


@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        //2.获取参数
        Map<String, String[]> map = request.getParameterMap();
        //3.封装对象
        Student student = new Student();
        try {
            BeanUtils.populate(student,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //4.调用Service保存
        StudentService service = new StudentServiceImpl();
        service.addUser(student);

        //5.跳转到userListServlet
        response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

@WebServlet("/delUserServlet")
public class DelUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取id
        String id = request.getParameter("id");
        //2.调用service删除
        StudentService service = new StudentServiceImpl();
        service.deleteUser(id);

        //3.跳转到查询所有Servlet
        response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

@WebServlet("/delSelectedServlet")
public class DelSelectedServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取所有id
        String[] ids = request.getParameterValues("uid");
        //2.调用service删除
        StudentService service = new StudentServiceImpl();
        service.delSelectedUser(ids);

        //3.跳转查询所有Servlet
        response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        //1.获取参数
        String currentPage = request.getParameter("currentPage");//当前页码
        String rows = request.getParameter("rows");//每页显示条数

        if(currentPage == null || "".equals(currentPage)){

            currentPage = "1";
        }


        if(rows == null || "".equals(rows)){
            rows = "5";
        }
        
        //获取条件查询参数
        Map<String, String[]> condition = request.getParameterMap();


        //2.调用service查询
        StudentService service = new StudentServiceImpl();
        PageBean<Student> pb = service.findUserByPage(currentPage,rows,condition);

        System.out.println(pb);

        //3.将PageBean存入request
        request.setAttribute("pb",pb);
        request.setAttribute("condition",condition);//将查询条件存入request
        //4.转发到list.jsp
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取id
        String id = request.getParameter("id");
        //2.调用Service查询
        StudentService service = new StudentServiceImpl();
        Student student = service.findUserById(id);

        //3.将user存入request
        request.setAttribute("student", student);
        //4.转发到update.jsp
        request.getRequestDispatcher("/update.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}


@WebServlet("/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        //2.获取map
        Map<String, String[]> map = request.getParameterMap();
        //3.封装对象
        Student student = new Student();
        try {
            BeanUtils.populate(student,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //4.调用Service修改
        StudentService service = new StudentServiceImpl();
        service.updateUser(student);

        //5.跳转到查询所有Servlet
        response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
    }

3.7LoginServlet.java

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");

        //2.获取数据
        //2.1获取用户填写验证码
        String verifycode = request.getParameter("verifycode");

        //3.验证码校验
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//确保验证码一次性
        if(!checkcode_server.equalsIgnoreCase(verifycode)){
            //验证码不正确
            //提示信息
            request.setAttribute("login_msg","验证码错误!");
            //跳转登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);

            return;
        }

        Map<String, String[]> map = request.getParameterMap();
        //4.封装User对象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        //5.调用Service查询
        UserService service = new UserServiceImpl();
        User loginStudent = service.login(user);
        //6.判断是否登录成功
        if(loginStudent != null){
            //登录成功
            //将用户存入session
            session.setAttribute("user", loginStudent);
            //跳转页面
            response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
        }else{
            //登录失败
            //提示信息
            request.setAttribute("login_msg","用户名或密码错误!");
            //跳转登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

3.8RegisterServlet.java

@WebServlet("/registerUserServlet")
public class RegisterUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        //2.获取参数
        Map<String, String[]> map = request.getParameterMap();
        //3.封装对象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //4.调用Service保存
        UserService service = new UserServiceImpl();
        service.addUser(user);

        //5.跳转到userListServlet
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }

3.9JDBCUtils.java

/**
 * JDBC工具类 使用Durid连接池
 */
public class JDBCUtils {

    private static DataSource ds ;

    static {

        try {
            //1.加载配置文件
            Properties pro = new Properties();
            //使用ClassLoader加载配置文件,获取字节输入流
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);

            //2.初始化连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接池对象
     */
    public static DataSource getDataSource(){
        return ds;
    }


    /**
     * 获取连接Connection对象
     */
    public static Connection getConnection() throws SQLException {
        return  ds.getConnection();
    }
}

3.9durid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8
username=root
password=123456
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

4.数据库设计

在这里插入图片描述

4.1User表

在这里插入图片描述

4.2Student表

在这里插入图片描述

4.3表的创建

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `gender` varchar(5) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(32) DEFAULT NULL,
  `qq` varchar(20) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', '张三', '男', '15', '陕西', '12345', 'zhangsan@itcast.cn');
INSERT INTO `student` VALUES ('2', '李四', '女', '15', '北京', '88888', 'ls@itcast.cn');
INSERT INTO `student` VALUES ('4', '1', '男', '1', '陕西', '1212131', '1212131@123.com');
INSERT INTO `student` VALUES ('5', '2', '男', '2', '陕西', '2222', '2222@132.com');
INSERT INTO `student` VALUES ('6', 'ee', '男', '23', '陕西', '12312', '12312@123.com');

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123456');
INSERT INTO `user` VALUES ('2', 'lisi', 'aaaaaa');
INSERT INTO `user` VALUES ('7', 'zhaoliu', '123456');
INSERT INTO `user` VALUES ('8', 'wangwu', '123456');
INSERT INTO `user` VALUES ('9', '小明', '123');
INSERT INTO `user` VALUES ('10', 'admin', 'admin');
INSERT INTO `user` VALUES ('11', 'test', '123456');