• 使用Java MVC模式设计一个学生管理系统


    最近在做web实验,要求是用jsp+servlet+mysql实现一个学生管理系统,完成对数据库的增删改查。

    效果图:

     

     代码:

    package dao;
    import java.util.List;
    import entity.Student;
    public interface IStudentDao {
        public boolean isExist(int sno);
        public boolean AddStudent(Student student); 
        public List<Student> queryAll();
        public boolean updateStudentBySno(int sno,Student student);
        public Student queryStudentBysno(int sno);
        public boolean deleteStudentBySno(int sno);
    }
    8)StudentDaoImpl
     package daoImpl;
    
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    import dao.IStudentDao;
    import entity.Student;
    import util.DBUtil;
    
    /*
     * 数据访问层 
     * 与数据库交互
     */
    public class StudentDaoImpl implements IStudentDao {    
        /*
         * 判断学号是否存在
         * 返回学号是否存在
         */
        public boolean isExist(int sno) {
            return queryStudentBysno(sno)==null?false:true;
        }
        
        /*
         * 增加学生信息
         * 返回是否成功
         */
        public boolean AddStudent(Student student) {
            String sql="insert into student values(?,?,?,?)";
            Object[] params= {student.getSno(),student.getSname(),student.getAge(),student.getAge(),student.getAddress()};
            return DBUtil.executeUpdate(sql, params); 
        }
        /*
         * 根据学号删人
         * 返回是否成功
         */
        public boolean deleteStudentBySno(int sno) {
            String sql="delete student where sno=?";
            Object[] params= {sno};
            return DBUtil.executeUpdate(sql, params);
        }
        /*
         * 根据学号sno修改数据student    
         * 返回是否成功
         */
        public boolean updateStudentBySno(int sno,Student student) {
            String sql="update student set sname=?,sage=?,saddress=? where sno=?";
            Object[] params= {student.getSname(),student.getAge(),student.getAddress(),sno};
            return DBUtil.executeUpdate(sql, params);
        }
        /*
         * 查询全部学生
         * 返回学生集合
         */
        public List<Student> queryAll() {
             Student student=null;
                PreparedStatement pst =null;
                ResultSet rs =null;
             List<Student> students=new ArrayList<Student>();
             try {
                 String sql="select * from student";
                 rs = DBUtil.executeQuery(sql, null);
                 while(rs.next()) {
                     int no=rs.getInt("sno");
                     String name=rs.getString("sname");
                     int age=rs.getInt("sage");
                     String address=rs.getString("saddress");
                     student=new Student(no,name,age,address);
                     students.add(student);
                 }
                 return students;
            } catch (SQLException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }finally {
                try {
                    if(rs!=null) rs.close();
                    if(pst!=null) pst.close();
                    if(DBUtil.connection!=null) DBUtil.connection.close();
                } 
                catch (SQLException e) {
                    e.printStackTrace();
                }
            }
             
        }
        /*
         * 根据学号查询学生
         * 返回查询学生类
         */
        public Student queryStudentBysno(int sno) {
             Student student=null;
                PreparedStatement pst =null;
                ResultSet rs =null;
             try {
                 String sql="select * from student where sno=?";
                 Object params[]= {sno};
                 rs = DBUtil.executeQuery(sql, params);
                 if(rs.next()) {
                     int no=rs.getInt("sno");
                     String name=rs.getString("sname");
                     int age=rs.getInt("sage");
                     String address=rs.getString("saddress");
                     student=new Student(no,name,age,address);
                 }
                 return student;
            } catch (SQLException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }finally {
                DBUtil.closeAll(rs, pst, DBUtil.connection);
            }    
        }
    }
    dao
    package util;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    
    //通用的数据库操作方法
    public class DBUtil {
        //sql数据库连接字符串
        private static final String URL="jdbc:sqlserver://localhost:1433;databasename=javatest";
        //sql用户名 和密码 用作连接用
        private static final String USERNAME="sa";
        private static final String PWD="cc123nice";
        
        public static Connection connection=null;
        public static PreparedStatement pst =null;
        public static ResultSet rs =null;
        
        /*
         * 得到PreparedStatement减少代码冗余
         */
        public static PreparedStatement getPreparedStatement(String sql,Object[] params) {
            //导入驱动,加载具体驱动类
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                //与数据库建立链接
                connection = DriverManager.getConnection(URL, USERNAME, PWD);
                pst=connection.prepareStatement(sql);
                if(params!=null) {
                    for(int i=0;i<params.length;i++){
                        pst.setObject(i+1,params[i]);
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return pst;
        }
        /*
         * 最后关闭所有
         */
        public static void closeAll(ResultSet rs,Statement stmt,Connection connection) {
            try {
                if(rs!=null) rs.close();
                if(stmt!=null) stmt.close();
                if(connection!=null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        /*
         * 通用的增删改 通过传入的sql和obj数组确认语句
         */
        public static boolean  executeUpdate(String sql,Object[] params) {
            try {    
                int count = getPreparedStatement(sql,params).executeUpdate();
                if(count>0)
                    return true;
                else 
                    return false;
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }finally {
                closeAll(null, pst, connection);
            }
        }
        /*
         * 通用的查询(只能返回到ResultSet)之后必须与具体类型耦合
         */
        public static ResultSet executeQuery(String sql,Object[] params) {
            try {
                rs= getPreparedStatement(sql,params).executeQuery();
                return rs;
            } catch (SQLException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    db
    package service;
    
    import java.util.List;
    
    import entity.Student;
    
    public interface IStudentService {
        public boolean addStudent(Student student);
        //
        public boolean deleteStudentBySno(int sno);
        //
        public boolean updateStudentBySno(int sno,Student student);
        //根据学号查
        public Student queryStudentBysno(int sno) ;
        //查询所有
        public List<Student> queryAll();
    }
    service
    public class StudentServiceImpl implements IStudentService{
        IStudentDao std=new StudentDaoImpl();
        //
        public boolean addStudent(Student student) {
            if(!std.isExist(student.getSno())){
                return std.AddStudent(student);
            }else
                return false;
        }
        //
        public boolean deleteStudentBySno(int sno) {
            if(std.isExist(sno)){
                return std.deleteStudentBySno(sno);
            }else
                return false;
        }
        //
        public boolean updateStudentBySno(int sno,Student student) {
            if(std.isExist(sno)){
                return std.updateStudentBySno(sno, student);
            }else
                return false;
        }
        //根据学号查
        public Student queryStudentBysno(int sno) {
            return std.queryStudentBysno(sno);
        }
        //查询所有
        public List<Student> queryAll(){
            return std.queryAll();
        }
    }
    ServiceImpl
    package MyServerlet;
    
    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 entity.Student;
    import service.IStudentService;
    import serviceImpl.StudentServiceImpl;
    
    /*
     * serverlet--增加
     */
    @WebServlet("/AddServerlet")
    public class AddServlet extends HttpServlet {
        private static final long serialVersionUID = 1204432039484958110L;
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
            int sno =Integer.parseInt( request.getParameter("sno"));
            String name = request.getParameter("sname");
            int age = Integer.parseInt(request.getParameter("sage"));
            String address = request.getParameter("saddress");
    
            Student student =new Student(sno,name,age,address);
            IStudentService studentService = new StudentServiceImpl();
            boolean res = studentService.addStudent(student);
            request.setCharacterEncoding("utf-8");
            //给request增加标识符
            if(!res)
                request.setAttribute("res", "增加失败");
            else
                request.setAttribute("res", "增加成功");
            }catch(Exception e){
                request.setAttribute("res", "数据有误增加失败");
            }
            request.getRequestDispatcher("QueryAllServlet").forward(request, response);     
        }
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }
    addservlet
    package MyServerlet;
    
    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 service.IStudentService;
    import serviceImpl.StudentServiceImpl;
    
    @WebServlet("/DeleteServerlet")
    public class DeleteServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //接受学号
            int sno = Integer.parseInt(request.getParameter("sno"));
            IStudentService  service = new StudentServiceImpl();
            boolean res = service.deleteStudentBySno(sno);
            response.setContentType("text/html; charset=utf-8");
            if(!res)
                request.setAttribute("res", "删除失败");
            else
                request.setAttribute("res", "删除成功");
            
            request.getRequestDispatcher("QueryAllServlet").forward(request, response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
    }
    deleteservlet
    package MyServerlet;
    
    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 service.IStudentService;
    import serviceImpl.StudentServiceImpl;
    
    @WebServlet("/DeleteServerlet")
    public class DeleteServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //接受学号
            int sno = Integer.parseInt(request.getParameter("sno"));
            IStudentService  service = new StudentServiceImpl();
            boolean res = service.deleteStudentBySno(sno);
            response.setContentType("text/html; charset=utf-8");
            if(!res)
                request.setAttribute("res", "删除失败");
            else
                request.setAttribute("res", "删除成功");
            
            request.getRequestDispatcher("QueryAllServlet").forward(request, response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
    }
    queryallservlet
    package MyServerlet;
    
    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 entity.Student;
    import service.IStudentService;
    import serviceImpl.StudentServiceImpl;
    
    
    @WebServlet("/QuerySnoServerlet")
    public class QuerySnoServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              int no = Integer.parseInt(request.getParameter("sno"));
              IStudentService  service = new StudentServiceImpl();
              Student student = service.queryStudentBysno(no);
              request.setAttribute("student", student);
              request.getRequestDispatcher("studentinfo.jsp").forward(request, response);
              
          }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doGet(request, response);
        }
    
    }
    queryoneservlet
    package MyServerlet;
    
    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 entity.Student;
    import service.IStudentService;
    import serviceImpl.StudentServiceImpl;
    
    @WebServlet("/UpdateServlet")
    public class UpdateServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //处理获取数据编码
            request.setCharacterEncoding("utf-8");
            //获取待修改学生的学号
            int no = Integer.parseInt(request.getParameter("sno"));
            //修改后内容
            String name = request.getParameter("sname");
            int age = Integer.parseInt(request.getParameter("sage"));
            String address = request.getParameter("saddress");
            Student student=new Student(name,age,address);
            IStudentService  service = new StudentServiceImpl(); 
            boolean res = service.updateStudentBySno(no, student);
            //处理相应编码
            response.setContentType("text/html; charset=utf-8");
            if(!res)
                request.setAttribute("res", "修改失败");
            else
                request.setAttribute("res", "修改成功");
            
            request.getRequestDispatcher("QueryAllServlet").forward(request, response);
        
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
    }
    updateservlet
    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>新增用户信息</title>
    </head>
    <body>
        <form action="AddServerlet">
            学号:<input type="text" name="sno"/><br/>
            姓名:<input type="text" name="sname"/><br/>
            年龄:<input type="text" name="sage"/><br/>
            地址:<input type="text" name="saddress"/><br/>
            <input type="submit" value="新增"/><br/>
        </form>
    </body>
    </html>
    add.jsp
    <%@page import="entity.Student"%>
    <%@page import="java.util.List"%>
    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>学生信息列表</title>
    </head>
    <body>
        <%
            String res=(String)request.getAttribute("res");
            if(res!=null){
                out.print(res);
            }
        %>
        <!-- 设置表格边框 -->
        <table border="1PX">
            
            <!-- 设置标题 -->
            <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>操作</th>
            </tr>
            <%
                //获取request域中的数据
                List<Student> students=( List<Student> ) request.getAttribute("students");
                for(Student student:students){
            %>
                <tr>
                    <td><a href="QuerySnoServerlet?sno=<%=student.getSno() %>"><%=student.getSno() %></a></td>
                    <td><%=student.getSname() %></td>
                    <td><%=student.getAge() %></td>
                    <td><a href="DeleteServerlet?sno=<%=student.getSno() %>">删除</a></td>
                </tr>
            <%     
                }
            %>
        </table>
        <a href="add.jsp">增加</a>
    </body>
    </html>
    index.jsp
    <%@page import="entity.Student"%>
    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Insert title here</title>
    </head>
    <body>
        <%
            Student student=(Student)request.getAttribute("student");
        %>
        <!-- 表单显示信息 -->
        <form action="UpdateServlet">
            学号:<input type="text" name="sno" value=<%=student.getSno() %>><br>
            姓名:<input type="text" name="sname" value=<%=student.getSname() %>><br>
            年龄:<input type="text" name="sage" value=<%=student.getAge() %>><br>
            地址:<input type="text" name="saddress" value=<%=student.getAddress() %>><br>    
            <input type="submit" value="修改">
        </form>
        <a href="QueryAllServlet">返回</a>
            
    </body>
    </html>
    info
  • 相关阅读:
    centos7 yum错误相关
    centos7 jenkins
    vim 常用命令
    Effective STL(第7条)
    【hihoCoder】1049.后序遍历
    C++ 单元测试 Cpputest
    【hihoCoder】1041. 国庆出游
    LeetCode(43. Multiply Strings)
    【LeetCode】16. 4Sum
    【LeetCode】1. Two Sum
  • 原文地址:https://www.cnblogs.com/1305536110-dym/p/14907752.html
Copyright © 2020-2023  润新知