JavaWeb学习JavaWebJavaweb

【javaweb期末项目】从零开始制作网上学生成绩管理系统(报告

2018-12-15  本文已影响39人  Topus

目录:
一、 前提与摘要
二、 课程设计的目的和要求
三、 系统分析与设计
四、 实现与测试
五、 主要源代码
六、 遇到的问题和解决方法
七、 存在的不足和改进的思路

一、前提与摘要

学生成绩管理系统是一个教育单位不可缺少的部分,它的内容对于学校的教师、学生和管理者来说都至关重要。本论文叙述到的学生成绩管理系统是用JSP网页编程+SQL查询语言实现的。重点介绍了学生成绩管理系统的实现过程:包括系统分析与设计、数据库设计、系统功能设计、系统实现、系统测试等。本系统主要功能有教师信息管理、学生信息管理、成绩管理,包括功能需求设计、数据库设计等内容。
现在的社会日新月异,发展的非常快。学校的发展也在加快,老师和学生做为学校的最主要的管理对象,老师和学生的信息管理系统就成了学校信息化管理系统中不可缺少的部分,它的内容对于学校的组织管理至关重要。但一直以来人们使用传统人工的方式进行学生的档案管理,这种管理方式存在着许多缺点,如:效率低,容易出错,格式不规范。另外时间一长,不容易进行统计和分析。
随着科学技术的不断提高,计算机科学日渐成熟,它已进入人类社会的各个领域并发挥着越来越重要的作用。作为计算机应用的一部分,使用计算机对学生档案进行管理,具有手工管理所无法比拟的优点。例如:检索迅速、查找方便、可靠性高、存储量大、寿命长、成本低等。这些优点能够极大地提高学校学生档案管理的效率。因此,开发这样一套管理软件成为很有必要的事情。而且只要软件的设计合理,可以为学校提供合理的管理模式。
摘要:学生成绩管理系统、JSP网页编程、SQL

二、课程设计的目的和要求

2.1 目的:

该系统的具体任务就是设计一个学生成绩的数据库管理系统,由计算机来代替人工执
行一系列诸如对教师、学生信息以及学生成绩的增加、删除、查询和修改的处理操作,以
方便对以上信息的管理组织工作。
建立学生成绩管理系统,采用计算机对学生成绩进行管理,进一步提高办学效益和现
代化水平。帮助广大教师提高工作效率,实现学生成绩信息管理工作流程的系统化、规范
化和自动化

2.2 要求:

网上学生成绩管理系统
实现学生信息的输入
实现课程的输入
实现成绩的输入
实现成绩的查询(按照姓名、学号等信息查询)
实现成绩的统计(平均分的统计、总成绩的统计)

三、 系统分析与设计

3.1 数据库设计

学生表的设计:(学号,姓名,密码,性别,家庭住址,成绩,备注)


学生数据

管理员表的设计:(id,名字,密码)


管理员数据
3.2 业务流程设计
业务流程设计.jpg
3.3 用例图设计
用例.jpg
3.4 类与页面逻辑对应关系图设计
mulu
3.5 项目截图
项目截图.png

四、 实现与测试

4.1 实现步骤:

4.1.1 配置数据库

1️⃣首先在mysql内建立连接并记住端口号和数据库用户名和账号


屏幕快照 2018-12-15 下午8.59.12.png

2️⃣创建数据库test(注:本项目只用到了stu和mgr两个表,user是测试用)


数据库建立.png

3️⃣输入以下代码创建学生表stu:(同理创建管理员表mgr,其中insert values的值自己定义)

use test;
CREATE TABLE `stu` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `pwd` varchar(255) NOT NULL,
  `sex` varchar(255) NOT NULL,
  `home` varchar(255) NOT NULL,
  `grades` varchar(255),
  `info` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `stu` VALUES ('1', 'stu1', '123', 'men', 'here', '0','i am the data-manerger');
INSERT INTO `stu` VALUES ('2', 'stu2','123','women','there','100','she is a good girl');
管理员数据库.png 学生数据库.png

4.1.2 在webroot下的WEB-INF下的lib中导入mysql的驱动jar包

jar包.png 导入jar.png
4.1.2 类的编写

创建一下五个类包:

类包
五个类包作用:
①dao:数据库操作的对象,用于使相关数据库操作更简单(有关Dao模式的文章https://blog.csdn.net/dragon_dai_2017/article/details/76937553

②entity:相当于Javabean,用于抽象数据结构

③filter:过滤器,用于过滤字符(当然也可以自己编写过滤IP等操作,详见:https://www.jianshu.com/p/1cf4ab2f7e21

④servlet:业务逻辑实体类,用于执行对应JSP页面的业务逻辑,完成MVC中C的相关操作

⑤util:用于连接数据库(相关连接数据库的操作详见https://blog.csdn.net/yanglong_blog_/article/details/73733176

在五个类包中编写相关代码:
1️⃣dao包中:
创建一个接口类 StuDao.java,用于规范化数据库相关操作

//StuDao.java
package com.dao;

import java.util.List;
import com.entity.Stu;


public interface StuDao {
    
    
    //1.注册
    public boolean register(Stu stu);
    
    //2.登录
    public boolean stulogin(String name,String pwd);
    public boolean mgrlogin(String name,String pwd);
        
    //3.返回学生信息集合
    public List<Stu> getStuAll();
    
    //4.根据用户名返回某个用户信息集合
    public List<Stu> getStuByName(String namestr);
    
    //5.根据学号返回某个用户信息集合
    public List<Stu> getStuById(String IdStr);
    
    //6.根据id删除用户
    public boolean delete(int id) ;
    
    //7.更新用户信息
    public boolean update(int id,String name, String pwd,String sex, String home, String grades,String info);
    
    //8.求成绩总和
    public int sum();
    
    //9.求成绩平均
    public int avg();
}

再创建StuDao的实现类StuDaoImpl.java(自动忽略我的相关测试用的输出语句哈哈)

package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
 
import com.entity.Stu;
import com.util.DBconn;
 
public class StuDaoImpl implements StuDao{
    //1.注册
        public boolean register(Stu stu) {
            boolean flag = false;
            DBconn.init();
            int i =DBconn.addUpdDel("insert into stu(name,pwd,sex,home,grades,info) " +
                    "values('"+stu.getName()+"','"+stu.getPwd()+"','"+stu.getSex()+"','"+stu.getHome()+"','"+stu.getGrades()+"','"+stu.getInfo()+"')");
            if(i>0){
                flag = true;
            }
            DBconn.closeConn();
            return flag;
        }
        //2.登录(学生与管理员的区别是查找的表不一样)
        //(学生)
        public boolean stulogin(String name, String pwd) {
            boolean flag = false;
            try {
                    DBconn.init();
                    ResultSet rs = DBconn.selectSql("select * from stu where name='"+name+"' and pwd='"+pwd+"'");
                    while(rs.next()){
                        if(rs.getString("name").equals(name) && rs.getString("pwd").equals(pwd)){
                            flag = true;
                        }
                    }
                    DBconn.closeConn();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return flag;
        }
      //(管理员)
        public boolean mgrlogin(String name, String pwd) {
            boolean flag = false;
            try {
                    DBconn.init();
                    ResultSet rs = DBconn.selectSql("select * from mgr where name='"+name+"' and pwd='"+pwd+"'");
                    while(rs.next()){
                        if(rs.getString("name").equals(name) && rs.getString("pwd").equals(pwd)){
                            flag = true;
                        }
                    }
                    DBconn.closeConn();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return flag;
        }
      //3.返回用户信息集合
        public List<Stu> getStuAll() {
            List<Stu> list = new ArrayList<Stu>();
            try {
                DBconn.init();
                ResultSet rs = DBconn.selectSql("select * from stu");
                
                while(rs.next()){
                    Stu stu = new Stu();
                    stu.setId(rs.getInt("id"));
                    stu.setName(rs.getString("name"));
                    stu.setPwd(rs.getString("pwd"));
                    stu.setSex(rs.getString("sex"));
                    stu.setHome(rs.getString("home"));
                    stu.setGrades(rs.getString("grades"));
                    stu.setInfo(rs.getString("info"));
                    list.add(stu);
                }
                DBconn.closeConn();
                return list;
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.print("错误");
            }
            return null;
        }
        
        //4.根据用户名返回某个用户信息集合
        public List<Stu> getStuByName(String namestr)
        {
            List<Stu> list = new ArrayList<Stu>();
            try {
                DBconn.init();
                ResultSet rs = DBconn.selectSql("select * from stu where name='"+namestr+"'");
                while(rs.next()){
                    Stu stu = new Stu();
                    stu.setId(rs.getInt("id"));
                    stu.setName(rs.getString("name"));
                    stu.setPwd(rs.getString("pwd"));
                    stu.setSex(rs.getString("sex"));
                    stu.setHome(rs.getString("home"));
                    stu.setGrades(rs.getString("grades"));
                    stu.setInfo(rs.getString("info"));
                    list.add(stu);
                }
                //DBconn.closeConn();
                return list;
            } catch (SQLException e) {
                System.out.println("查询的用户可能不存在!");
                e.printStackTrace();
                
            }finally{
                DBconn.closeConn();
            }
            return null;
            
        }
        
        //5.根据学号返回某个用户信息集合
           public List<Stu> getStuById(String IdStr)
                {
                    List<Stu> list = new ArrayList<Stu>();
                    try {
                        DBconn.init();
                        ResultSet rs = DBconn.selectSql("select * from stu where id='"+IdStr+"'");
                        while(rs.next()){
                            Stu stu = new Stu();
                            stu.setId(rs.getInt("id"));
                            stu.setName(rs.getString("name"));
                            stu.setPwd(rs.getString("pwd"));
                            stu.setSex(rs.getString("sex"));
                            stu.setHome(rs.getString("home"));
                            stu.setGrades(rs.getString("grades"));
                            stu.setInfo(rs.getString("info"));
                            list.add(stu);
                        }
                        DBconn.closeConn();
                        return list;
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    return null;
                    
                }
                
           
        //6.更新用户信息
        public boolean update(int id,String name, String pwd,String sex, String home, String grades,String info) {
            boolean flag = false;
            DBconn.init();
            String sql ="update stu set name ='"+name
                    +"' , pwd ='"+pwd
                    +"' , sex ='"+sex
                    +"' , home ='"+home
                    +"' , grades ='"+grades
                    +"' , info ='"+info+"' where id = "+id;
            int i =DBconn.addUpdDel(sql);
            if(i>0){
                flag = true;
            }
            DBconn.closeConn();
            return flag;
        }
        
        //7.根据id删除用户
        public boolean delete(int id) {
            boolean flag = false;
            DBconn.init();
            String sql = "delete  from stu where id="+id;
            int i =DBconn.addUpdDel(sql);
            if(i>0){
                flag = true;
            }
            DBconn.closeConn();
            return flag;
        }
        
        //8.求成绩总和
        public int sum(){
            int sum = 0;
            try {
                    DBconn.init();
                    
                    ResultSet rs = DBconn.selectSql("SELECT SUM(grades) FROM stu");
                    while(rs.next()){
                        System.out.print("进来了1");
                        if(rs.getInt("SUM(grades)")!=0){
                            System.out.print("进来了2");
                            sum = rs.getInt("SUM(grades)");
                        }
                    }
                    
                    DBconn.closeConn();
                    return sum; 
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            return 0;
        }
        
        //9.求成绩平均
        public int avg(){
            int avg = 0;
            try {
                    DBconn.init();
                    
                    ResultSet rs = DBconn.selectSql("SELECT AVG(grades) FROM stu");
                    while(rs.next()){
                        System.out.print("进来了1");
                        if(rs.getInt("AVG(grades)")!=0){
                            System.out.print("进来了2");
                            avg = rs.getInt("AVG(grades)");
                        }
                    }
                    
                    DBconn.closeConn();
                    return avg; 
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            return 0;
        }
        
        
        

}

②entity中:
创建Stu.java(功能就是javabean)

package com.entity;

public class Stu {
     private int id;
        private String name;
        private String pwd;
        private String sex;
        private String home;
        private String info;
        private String grades;
        
        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 String getPwd() {
            return pwd;
        }
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public String getHome() {
            return home;
        }
        public void setHome(String home) {
            this.home = home;
        }
        public String getInfo() {
            return info;
        }
        public void setInfo(String info) {
            this.info = info;
        }
        public String getGrades() {
            return grades;
        }
        public void setGrades(String grades) {
            this.grades = grades;
        }
        
}

③filter中:
创建过滤器EncodingFilter

//字符编码的过滤器
package com.filter;
 
import java.io.IOException;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
public class EncodingFilter implements Filter{
    public EncodingFilter(){
        System.out.println("过滤器构造");
    }
    public void destroy() {
        System.out.println("过滤器销毁");
    }
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8"); //将编码改为utf-8
        response.setContentType("text/html;charset=utf-8");
        chain.doFilter(request, response);
    }
 
    public void init(FilterConfig arg0) throws ServletException {
        System.out.println("过滤器初始化");
    }
 
}

④servlet中创建一下类:
AddupServlet(用于录入学生信息)

package com.servlet;

import java.io.IOException;
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 com.dao.StuDao;
import com.dao.StuDaoImpl;
import com.entity.Stu;

/**
 * Servlet implementation class AddupServlet
 */
@WebServlet("/AddupServlet")
public class AddupServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String name = request.getParameter("name"); //获取jsp页面传过来的参数
        String pwd = request.getParameter("pwd");
        String sex = request.getParameter("sex");
        String home = request.getParameter("home");
        String grades = request.getParameter("grades");
        String info = request.getParameter("info");
        
        Stu stu = new Stu(); //实例化一个对象,组装属性
        stu.setName(name);
        stu.setPwd(pwd);
        stu.setSex(sex);
        stu.setHome(home);
        stu.setGrades(grades);
        stu.setInfo(info);
        
        StuDao ud = new StuDaoImpl();
        
        if(ud.register(stu)){
            request.setAttribute("username", name);  //向request域中放置参数
            request.setAttribute("message", "录入成功");
            request.getRequestDispatcher("/mgrsuccess.jsp").forward(request, response);  //转发到登录页面
        }else{
            
            response.sendRedirect("error.jsp");//重定向到首页
        }
    }

}

DeleteServlet(在管理所有学生的界面执行删除某个学生记录的操作)

package com.servlet;

import java.io.IOException;
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 com.dao.StuDao;
import com.dao.StuDaoImpl;

/**
 * Servlet implementation class UpdateServlet
 */
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String id = request.getParameter("id");
        int userId = Integer.parseInt(id);
        
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        String sex = request.getParameter("sex");
        String home = request.getParameter("home");
        String grades = request.getParameter("grades");
        String info = request.getParameter("info");
        
        System.out.println("------------------------------------"+userId);
        
        StuDao ud = new StuDaoImpl();//数据库的操作对象
        if(ud.update(userId, name, pwd, sex, home, grades,info)){
            request.setAttribute("message", "更新成功");
            request.getRequestDispatcher("/SearchallServlet").forward(request, response);
        }else{
            response.sendRedirect("error.jsp");
        }
    }
}

UpdateServlet(在管理所有学生的界面执行更新某个学生记录的操作)

package com.servlet;

import java.io.IOException;
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 com.dao.StuDao;
import com.dao.StuDaoImpl;

/**
 * Servlet implementation class UpdateServlet
 */
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String id = request.getParameter("id");
        int userId = Integer.parseInt(id);
        
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        String sex = request.getParameter("sex");
        String home = request.getParameter("home");
        String grades = request.getParameter("grades");
        String info = request.getParameter("info");
        
        System.out.println("------------------------------------"+userId);
        
        StuDao ud = new StuDaoImpl();//数据库的操作对象
        if(ud.update(userId, name, pwd, sex, home, grades,info)){
            request.setAttribute("message", "更新成功");
            request.getRequestDispatcher("/SearchallServlet").forward(request, response);
        }else{
            response.sendRedirect("error.jsp");
        }
    }
}

FindByIdServlet(通过学生Id来查找学生相关信息)

package com.servlet;

import java.io.IOException;
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 com.dao.StuDao;
import com.dao.StuDaoImpl;

/**
 * Servlet implementation class FindByIdServlet
 */
@WebServlet("/FindByIdServlet")
public class FindByIdServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindByIdServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        

        String id = request.getParameter("id");
        
        StuDao ud = new StuDaoImpl();
        
        if(id!= "") {
            if(ud.getStuById(id).isEmpty()) 
            {
                System.out.println("查询到的为空值");
                response.sendRedirect("error.jsp");
            }else 
            {
                request.setAttribute("findlist", ud.getStuById(id));  //向request域中放置参数
                request.setAttribute("message", " 查找成功");
                request.getRequestDispatcher("/findlist.jsp").forward(request, response);  //转发到登录页面
            }
        }else {
            response.sendRedirect("error.jsp");
        }


}
}

FindServlet(通过学生姓名查找相关信息)

package com.servlet;

import java.io.IOException;
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 com.dao.StuDao;
import com.dao.StuDaoImpl;

/**
 * Servlet implementation class FindServlet
 */
@WebServlet("/FindServlet")
public class FindServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        String name = request.getParameter("name"); 
        
        StuDao ud = new StuDaoImpl();
        
        if(name != "") {
            if(ud.getStuByName(name).isEmpty()) 
            {
                System.out.println("查询到的为空值");
                response.sendRedirect("error.jsp");
            }else 
            {
                request.setAttribute("findlist", ud.getStuByName(name));  //向request域中放置参数
                request.setAttribute("message", " 查找成功");
                request.getRequestDispatcher("/findlist.jsp").forward(request, response);  //转发到登录页面
            
            }       
        }else {
            response.sendRedirect("error.jsp");
        }
    
        
    }

}

MgrLoginServlet(管理员登录的业务逻辑)

package com.servlet;
 
import java.io.IOException;
//import java.io.PrintWriter;
 
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 com.dao.StuDao;
import com.dao.StuDaoImpl;
 
@WebServlet("/MgrLoginServlet")
//用来实现对用户登录的操作
public class MgrLoginServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;
    //需要继承HttpServlet  并重写doGet  doPost方法
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);  //将信息使用doPost方法执行   对应jsp页面中的form表单中的method
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String name = request.getParameter("name"); //得到jsp页面传过来的参数
        String pwd = request.getParameter("pwd");
        
        StuDao ud = new StuDaoImpl();
        
        if(ud.mgrlogin(name, pwd)){
            request.setAttribute("message", "欢迎管理员"+name); //向request域中放置信息
            request.getRequestDispatcher("/mgrsuccess.jsp").forward(request, response);//转发到成功页面
        }else{
            response.sendRedirect("error.jsp"); //重定向到error页面
        }
    }
 
}


SearchallServlet(管理员管理所有学生的类)

package com.servlet;

import java.io.IOException;
import java.util.List;

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 com.dao.StuDao;
import com.dao.StuDaoImpl;
import com.entity.Stu;

/**
 * Servlet implementation class SearchallServlet
 */
@WebServlet("/SearchallServlet")
public class SearchallServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        
        StuDao ud = new StuDaoImpl();//定义数据库操作类的对象
        List<Stu> stuAll = ud.getStuAll();//获取到所有的对象并且存储到list里
        request.setAttribute("stuAll", stuAll);
        
        //求和
        int sum = ud.sum();
        request.setAttribute("sum", sum);
        
        //求平均
        int avg = ud.avg();
        request.setAttribute("avg", avg);
        
        request.getRequestDispatcher("/mgrall.jsp").forward(request, response);
    }
}

StuLoginServlet(学生登录的页面)

package com.servlet;

import java.io.IOException;
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 com.dao.StuDao;
import com.dao.StuDaoImpl;

/**
 * Servlet implementation class StuLoginServlet
 */
@WebServlet("/StuLoginServlet")
public class StuLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    //需要继承HttpServlet  并重写doGet  doPost方法
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);  //将信息使用doPost方法执行   对应jsp页面中的form表单中的method
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String name = request.getParameter("name"); //得到jsp页面传过来的参数
        String pwd = request.getParameter("pwd");
        
        StuDao ud = new StuDaoImpl();
        
        if(ud.stulogin(name, pwd)){
            request.setAttribute("message", "欢迎学生用户"+name); //向request域中放置信息
            request.setAttribute("name", name);
            request.getRequestDispatcher("/stusuccess.jsp").forward(request, response);//转发到成功页面
        }else{
            response.sendRedirect("error.jsp"); //重定向到error页面
        }
    }
}

⑤util包中创建:
DBconn.java(链接数据库的方法,注意其中的用户名密码要和你之前配置数据库的要一致)

//数据库连接的类
package com.util;
 
import java.sql.*;
 
public class DBconn {
    static String url = "jdbc:mysql://localhost:3306/test?useunicuee=true& characterEncoding=utf8"; 
    static String username = "root"; 
    static String password = "363316495"; 
    static Connection  conn = null;
    static ResultSet rs = null;
    static PreparedStatement ps =null;
    public static void init(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,username,password);
        } catch (Exception e) {
            System.out.println("init [SQL驱动程序初始化失败!]");
            e.printStackTrace();
        }
    }
    public static int addUpdDel(String sql){
        int i = 0;
        try {
            PreparedStatement ps =  conn.prepareStatement(sql);
            i =  ps.executeUpdate();
        } catch (SQLException e) {
            System.out.println("sql数据库增删改异常");
            e.printStackTrace();
        }
        
        return I;
    }
    public static ResultSet selectSql(String sql){
        try {
            ps =  conn.prepareStatement(sql);
            rs =  ps.executeQuery(sql);
        } catch (SQLException e) {
            System.out.println("sql数据库查询异常");
            e.printStackTrace();
        }
        return rs;
    }
    public static void closeConn(){
        try {
            conn.close();
        } catch (SQLException e) {
            System.out.println("sql数据库关闭异常");
            e.printStackTrace();
        }
    }
}
4.1.3 页面的编写

addup.jsp (学生信息录入)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生信息录入</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<form action="AddupServlet"method="post" style="padding-top:-700px;">
       输入用户名:<input name="name" type="text"><br><br>
       输入密码:<input name="pwd" type="password"><br><br>
       选择性别:<input type="radio"name="sex"value="men"checked>男
            <input type="radio"name="sex"value="women">女<br><br>
       选择家乡:
       <select name="home">
           <option value="ShangHai">ShangHai</option>
           <option value="Beijing" selected>Beijing</option>
           <option value="ChangSha">ChangSha</option>
        </select><br>
        输入成绩:<input name="grades" type="text"><br><br>
        填写个人信息:<br>
       <textarea name="info" row="5" cols="30"></textarea><br>
       <input type="reset"value="重置"><input type="submit"value="录入">
</form>
</body>
</html>

error.jsp(错误页面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误页面</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>~(~ ̄▽ ̄)~出错啦!请尝试检查一下输入或者页面逻辑呦</h1>
<a href="Index.jsp">回到首页</a>
</body>
</html>

findlist.jsp(查找学生列表)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
    
 <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>查找列表</title>
</head>
<body>
  <%-- <h1>${message}</h1> --%>

    <table  width="200" border="1" cellpadding="0" >
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>性别</th>
            <th>密码</th>
            <th>家乡</th>
            <th>成绩</th>
            <th>备注</th>
        </tr>

     <c:forEach var="U" items="${findlist}"  > 
     
      <form action="UpdateServlet" method="post"> 
      
        <tr>
           <td><input type="text" value="${U.id}" name="id" ></td>
           <td><input type="text" value="${U.name}" name="name"></td>
           <td><input type="text" value="${U.sex}" name="sex"></td>
           <td><input type="text" value="${U.pwd}" name="pwd"></td>
           <td><input type="text" value="${U.home}" name="home"></td>
           <td><input type="text" value="${U.grades}" name="grades"></td>
           <td><input type="text" value="${U.info}" name="info"></td>
         </tr>
       
    </form> 
   
    
    </c:forEach> 
    

    </table>

</body>
</html>

index.jsp (主页入口)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎登陆zyz的学生管理系统</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>欢迎登陆zyz的学生管理系统</h1>
<a href="mgrlogin.jsp">管理员登录</a>
<a href="stulogin.jsp">学生登录</a>
</body>
</html>

mgrall.jsp(管理所有学生表)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
    
 <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>查找列表</title>
</head>
<body>
  <%-- <h1>${message}</h1> --%>

    <table  width="200" border="1" cellpadding="0" >
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>性别</th>
            <th>密码</th>
            <th>家乡</th>
            <th>成绩</th>
            <th>备注</th>
        </tr>

     <c:forEach var="U" items="${findlist}"  > 
     
      <form action="UpdateServlet" method="post"> 
      
        <tr>
           <td><input type="text" value="${U.id}" name="id" ></td>
           <td><input type="text" value="${U.name}" name="name"></td>
           <td><input type="text" value="${U.sex}" name="sex"></td>
           <td><input type="text" value="${U.pwd}" name="pwd"></td>
           <td><input type="text" value="${U.home}" name="home"></td>
           <td><input type="text" value="${U.grades}" name="grades"></td>
           <td><input type="text" value="${U.info}" name="info"></td>
         </tr>
       
    </form> 
   
    
    </c:forEach> 
    

    </table>

</body>
</html>

mgrlogin.jsp (管理员登录界面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>管理员登录页面</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>管理员登录页面</h1>
  <form action="MgrLoginServlet"  method="post"  style="padding-top:-700px;">
        用户名:<input type="text" name="name"value=""><br><br>
        密码:  <input type="password" name="pwd"value=""><br><br>
                    <input type="submit"value="登录"name="Mgrlogin"><input type="reset"value="重置"><br>
  </form>
</body>
</html>

mgrsuccess.jsp(管理员登录成功后的操作页面)

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>管理员登录成功</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
            ${message} <br>  
            <a href="SearchallServlet">查看所有学生信息表</a>
            <br/>
            <a href="addup.jsp">录入学生信息</a>

       <form action="FindServlet"method="post" style="padding-top:-700px;">
       输入用户名(按照用户名查找):<input name="name" type="text"><br><br>
       <input type="reset"value="重置"><input type="submit"value="查找">
       </form>
       

       <form action="FindByIdServlet"method="post" style="padding-top:-700px;">
       输入Id号(按照学号查找):<input name="id" type="text"><br><br>
       <input type="reset"value="重置"><input type="submit"value="查找">
       </form>
            
  </body>
</html>

stulogin.jsp(学生登录页面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生登录页面</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>学生登录页面</h1>
<form action="StuLoginServlet"  method="post"  style="padding-top:-700px;">
        用户名:<input type="text" name="name"value=""><br><br>
        密码:  <input type="password" name="pwd"value=""><br><br>
               <input type="submit"value="登录"name="Stulogin"><input type="reset"value="重置"><br>
</form>
</body>
</html>

stusuccess.jsp(学生登录成功后的查找我的成绩页面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生登录成功页面</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>学生登录成功页面</h1>
${message} <br>
<%-- ${name} --%>
<% 
String name = request.getParameter("name"); 
request.setAttribute("name", name);
%>

<form action="FindServlet"  method="post"  style="padding-top:-700px;">
<!-- 定义了一个隐藏的输入框 -->
<input type="hidden" name="name" value="${name}"><br>
<input type="submit"value="查找我的成绩"name="Stulogin"><br>
</form>
            
</body>
</html>

4.2 测试:

主页.png 管理员登陆成功操作界面.png 管理所有学生表(包含更新和删除).png 管理员登录界面.png 学生信息录入.png 按名Id查找.png 学生登录界面.png 学生登陆成功操作界面.png 显示该学生成绩的页面 .png 错误.png

五、 主要源代码

详见四:
其中最重要的是相关数据的操作:(有可能屏幕前的你用的不是Mysql,那么你的sql语句可能能不太一样,现在你自己的数据库中试好了再来编写java代码)

//1.注册
        public boolean register(Stu stu) {
            boolean flag = false;
            DBconn.init();
            int i =DBconn.addUpdDel("insert into stu(name,pwd,sex,home,grades,info) " +
                    "values('"+stu.getName()+"','"+stu.getPwd()+"','"+stu.getSex()+"','"+stu.getHome()+"','"+stu.getGrades()+"','"+stu.getInfo()+"')");
            if(i>0){
                flag = true;
            }
            DBconn.closeConn();
            return flag;
        }
        //2.登录(学生与管理员的区别是查找的表不一样)
        //(学生)
        public boolean stulogin(String name, String pwd) {
            boolean flag = false;
            try {
                    DBconn.init();
                    ResultSet rs = DBconn.selectSql("select * from stu where name='"+name+"' and pwd='"+pwd+"'");
                    while(rs.next()){
                        if(rs.getString("name").equals(name) && rs.getString("pwd").equals(pwd)){
                            flag = true;
                        }
                    }
                    DBconn.closeConn();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return flag;
        }
      //(管理员)
        public boolean mgrlogin(String name, String pwd) {
            boolean flag = false;
            try {
                    DBconn.init();
                    ResultSet rs = DBconn.selectSql("select * from mgr where name='"+name+"' and pwd='"+pwd+"'");
                    while(rs.next()){
                        if(rs.getString("name").equals(name) && rs.getString("pwd").equals(pwd)){
                            flag = true;
                        }
                    }
                    DBconn.closeConn();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return flag;
        }
      //3.返回用户信息集合
        public List<Stu> getStuAll() {
            List<Stu> list = new ArrayList<Stu>();
            try {
                DBconn.init();
                ResultSet rs = DBconn.selectSql("select * from stu");
                
                while(rs.next()){
                    Stu stu = new Stu();
                    stu.setId(rs.getInt("id"));
                    stu.setName(rs.getString("name"));
                    stu.setPwd(rs.getString("pwd"));
                    stu.setSex(rs.getString("sex"));
                    stu.setHome(rs.getString("home"));
                    stu.setGrades(rs.getString("grades"));
                    stu.setInfo(rs.getString("info"));
                    list.add(stu);
                }
                DBconn.closeConn();
                return list;
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.print("错误");
            }
            return null;
        }
        
        //4.根据用户名返回某个用户信息集合
        public List<Stu> getStuByName(String namestr)
        {
            List<Stu> list = new ArrayList<Stu>();
            try {
                DBconn.init();
                ResultSet rs = DBconn.selectSql("select * from stu where name='"+namestr+"'");
                while(rs.next()){
                    Stu stu = new Stu();
                    stu.setId(rs.getInt("id"));
                    stu.setName(rs.getString("name"));
                    stu.setPwd(rs.getString("pwd"));
                    stu.setSex(rs.getString("sex"));
                    stu.setHome(rs.getString("home"));
                    stu.setGrades(rs.getString("grades"));
                    stu.setInfo(rs.getString("info"));
                    list.add(stu);
                }
                //DBconn.closeConn();
                return list;
            } catch (SQLException e) {
                System.out.println("查询的用户可能不存在!");
                e.printStackTrace();
                
            }finally{
                DBconn.closeConn();
            }
            return null;
            
        }
        
        //5.根据学号返回某个用户信息集合
           public List<Stu> getStuById(String IdStr)
                {
                    List<Stu> list = new ArrayList<Stu>();
                    try {
                        DBconn.init();
                        ResultSet rs = DBconn.selectSql("select * from stu where id='"+IdStr+"'");
                        while(rs.next()){
                            Stu stu = new Stu();
                            stu.setId(rs.getInt("id"));
                            stu.setName(rs.getString("name"));
                            stu.setPwd(rs.getString("pwd"));
                            stu.setSex(rs.getString("sex"));
                            stu.setHome(rs.getString("home"));
                            stu.setGrades(rs.getString("grades"));
                            stu.setInfo(rs.getString("info"));
                            list.add(stu);
                        }
                        DBconn.closeConn();
                        return list;
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    return null;
                    
                }
                
           
        //6.更新用户信息
        public boolean update(int id,String name, String pwd,String sex, String home, String grades,String info) {
            boolean flag = false;
            DBconn.init();
            String sql ="update stu set name ='"+name
                    +"' , pwd ='"+pwd
                    +"' , sex ='"+sex
                    +"' , home ='"+home
                    +"' , grades ='"+grades
                    +"' , info ='"+info+"' where id = "+id;
            int i =DBconn.addUpdDel(sql);
            if(i>0){
                flag = true;
            }
            DBconn.closeConn();
            return flag;
        }
        
        //7.根据id删除用户
        public boolean delete(int id) {
            boolean flag = false;
            DBconn.init();
            String sql = "delete  from stu where id="+id;
            int i =DBconn.addUpdDel(sql);
            if(i>0){
                flag = true;
            }
            DBconn.closeConn();
            return flag;
        }
        
        //8.求成绩总和
        public int sum(){
            int sum = 0;
            try {
                    DBconn.init();
                    
                    ResultSet rs = DBconn.selectSql("SELECT SUM(grades) FROM stu");
                    while(rs.next()){
                        System.out.print("进来了1");
                        if(rs.getInt("SUM(grades)")!=0){
                            System.out.print("进来了2");
                            sum = rs.getInt("SUM(grades)");
                        }
                    }
                    
                    DBconn.closeConn();
                    return sum; 
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            return 0;
        }
        
        //9.求成绩平均
        public int avg(){
            int avg = 0;
            try {
                    DBconn.init();
                    ResultSet rs = DBconn.selectSql("SELECT AVG(grades) FROM stu");
                    while(rs.next()){
                        System.out.print("进来了1");
                        if(rs.getInt("AVG(grades)")!=0){
                            System.out.print("进来了2");
                            avg = rs.getInt("AVG(grades)");
                        }
                    }
                    
                    DBconn.closeConn();
                    return avg; 
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            return 0;
        }

六、 遇到的问题和解决方法

过程中中主要遇到的小问题不少,原因主要是jsp域相关的问题。遇到的比较棘手的问题主要是:
数据库语句编写错误到时数据库的增删改查错误


屏幕快照 2018-12-12 上午9.16.22.png 屏幕快照 2018-12-12 上午9.24.04.png
解决
"select * from mgr where name='"+name+"' and pwd='"+pwd+"'"

一定要注意其中""与''以及+等符号之间的关系,因为这里的aql语句是一个String,其中又用到了传入的参数,字符串拼接的时候一定要注意!

七、 存在的不足和改进的思路

1、界面的问题:解决思路是导入的一个css的包,然后在jsp页面引用了一下
2、查询时未输入也可以录入的问题:思路是添加一个录入判断
3、数据的中文问题:思路是更改字符编码

项目下载:
链接:https://pan.baidu.com/s/1X_aRx2GqWRjOgk0jZk098A 密码:vdrx

上一篇下一篇

猜你喜欢

热点阅读