JavaWeb -學生信息管理實踐(JDBC+web+三層架構+DBUtil構造思路)

前言:html

1 該程序使用動態web項目java

2 該程序使用SQL server需導入對應包( 具體可看前篇----JDBC的使用)web

3 三層架構思想:sql

  ①表示層數據庫

      前臺:jsp/html等 做爲前臺與用戶交互數組

      後臺:用於控制跳轉,調用業務邏輯層tomcat

  ②業務邏輯層架構

      將數據訪問層進行組裝jsp

      給表示層調用函數

  ③數據訪問層

      全部小功能和函數創建

      與數據庫相連 以dao命名

4 該程序體現面向接口開發:先接口-再實現類(此爲規範!!

  當實體類須要實例時

    運用:接口=new 實例

  service、dao加入接口

  命名規範:

    接口:IXXX    例:IStudentDao

    實現類:XXXImpl   例:StudentDaoImpl

5 DBUtil做爲通用數據庫工具類,實現通用調用數據庫方法

6 該程序使用tomcat8.5

如下是示例目錄

 

 

如下是代碼實例

IStudentDao(做爲dao的接口 將方法寫出但不作聲明)

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);
}

 

StudentDaoImpl(實現接口方法-增、刪、改、查單人/查全部)

##用DBUtil封裝方法 達到減小代碼量目的

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);
        }    
    }
}

 

 

DBUtil減小代碼冗餘-並實現 數據庫通用工具類思想

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;
        }
    }
}

 

 

 IStudentService(做爲service的接口 將方法寫出但不作聲明)

 

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();
}

 

 

 

 

StudentServiceImpl實現接口IStudentService方法實現

主要對dao實例內的方法進行封裝

 

package serviceImpl;

import java.util.List;

import dao.IStudentDao;
import daoImpl.StudentDaoImpl;
import entity.Student;
import service.IStudentService;

/*
 * 業務邏輯層 對dao層進行組裝 邏輯性增刪改查(增刪改==查+操做)
 */
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();
    }
}

 

 MyServerlet包中存放對各個方法的servlet(實現1對1的狀況)將表示層的信息處理、向下-處理層傳遞/向上-表示層傳遞

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 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);
    }
}

 

 

 

 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 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);
    }

}

 

 

 

 QuerySnoServlet實現‘經過學號查找’的表示層後臺

 此處重定向到studentinfo.jsp 如下進行解析

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);
    }

}

 

 UpdateServlet實現‘修改’的表示層後臺

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);
    }

}

 

 

 如下爲表示層前臺

 add.jsp增長學生信息表單

<%@ 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>

 

 

index.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>

 

 

studentinfo.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>

 成品示例(須要連接中不顯示具體信息,再提交表單處增長 method='post')

進入界面顯示全部學生信息

 

點擊學號1查看具體信息

直接修改數據

 

點擊增長可直接增長數據

新增後跳轉回顯示所有基本信息

點擊刪除後直接刪除行列

相關文章
相關標籤/搜索