1. 程式人生 > 實用技巧 >Java——JSP使用三層架構完成學生管理系統

Java——JSP使用三層架構完成學生管理系統

先介紹三層架構有那些三層:第一層就是表示層、第二層就是業務邏輯層、第三層是資料訪問層

再介紹三層所要負責的內容,並搭建框架:

1.表示層:需要負責兩個地方,一個是前臺,另一個是後臺

(1)前臺:使用JSP增加學生

建立JSP檔案,取名為:add.jsp,效果如下:

(2)後臺:使用Servlet,再將JSP所增加的資料提交給後臺

建立包,包類名為:org.student.servlet,如下:

之後再包中建立Java檔案,Java檔名為:servlet.java,專門處理將JSP中提交後臺,效果如下:

2.業務邏輯層:將資料訪問層進行組裝

先建立包類,包名為:org.student.service,效果如下:

然後再建立Java檔案,效果如下:

3.資料訪問層:採用的是原子性的增刪改查,只要是對資料庫進行操作,就必須使用JDBC操作mysql資料庫

建立包類,包名為:org.student.dao,如果如下:

包建立好以後,再建立Java檔案,Java檔名為:studentDao.java,使用資料訪問層中原子性的增刪改查進行操作,並使用JDBC效果如下:

4.建立學生類:封裝mysql資料庫中表的欄位,但名字可以不設定一樣,這裡只是為了servlet類方便的使用

(1)這裡的所建立的包類名為:

(2) 再建立Java檔案。這裡的Java檔名為:student.java,這裡就是對mysql資料庫中表的所有欄位進行封裝,效果如下:

整體Java檔案+所用到的包,還所建立的jsp檔案等,展示:

第一步:在表示層中前臺(add.jsp)下完成form表單,配置如下:

程式碼:

<form action="servlet" method="get">
學號:<input type="text" name="id"><br>
姓名:<input type="text" name="name"/><br>
年齡:<input type="text" name="age"/><br>
地址:<input type="text" name
="address"/><br> <input type="submit" value="新增">

效果:

注:(1)form表單中所設定的欄位是根據mysql資料庫中的欄位來的(注:也不一定要把mysql資料庫中表下的欄位所有取出來,比如說:我只要姓名、年齡這個兩個引數,也可以,並沒有規定設定規定,反正看自己吧),後面設定的name值可以隨便取,(2)在form表單中的action的用途是進行跳轉到表示層下的後臺中的doGet()方法下

第二步:根據表中的欄位,建立實體類進行封裝,這裡欄位名可以取別名來代替(注:在org.student.app包下的student.java中的Java檔案裡進行新增)

//這是封裝類,進行封裝mysql資料庫中的所有欄位,為了servlet類方便使用
package org.student.app;

public class student {
    private int id;
    private String name;
    private int age;
    private String address;
    
    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 int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
    //構造方法
    //無參
    public student() {
        
    }
    //有參
    public student(int id,String name,int age,String address) {
        this.id=id;
        this.name=name;
        this.age=age;
        this.address=address;
    }
}
程式碼

第三步:表示層(servlet.java)中的doGet()方法下進行獲取JSP中表單所定義的欄位

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通過servlet來獲取JSP中表單所定義的欄位
        
        //將字串型別轉化成int型別
        int id=Integer.parseInt(request.getParameter("id"));
        
        String name=request.getParameter("name");
        
        //將字串型別轉化成int型別
        int age=Integer.parseInt(request.getParameter("age"));
        
        String address=request.getParameter("address");
        
        
        //例項化student類
        student stu=new student(id,name,age,address);
        
    }

第四步:資料訪問層(studentDao.java)中使用JDBC來操作資料庫的增刪改查,注:這裡採取原子性的增刪改查

(1)先定義查詢總,專門處理關於JDBC中的查詢功能,這裡方法名為“atomicity”

//這是三層中的資料訪問層:原子性的增刪改查
package org.student.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.student.app.student;

import com.sun.org.apache.regexp.internal.recompile;

public class studentDao {
    //所要連線的資料庫
    String url="jdbc:mysql://localhost:3306/user";
    String user="root"; 
    String password="123"; 
    
    
    //根據學號,查改具體的學生,所以返回值為student,而不是void,以下方法可以理解為查詢總
    public student atomicity(int id)  {
        //呼叫學生類
        student stu=null;
        //設定變數,要用的話,直接呼叫即可
        Connection conn=null;
        PreparedStatement prepareStatement=null;
        ResultSet execut=null;
        
        //使用驅動
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,user,password);
            
//            sql語句,根據學號查詢此人是否存在
            String sql="select * from student where id=?";
            prepareStatement = conn.prepareStatement(sql);
            prepareStatement.setInt(1, id);
    
            execut = prepareStatement.executeQuery();
            
            //進行判斷,有資料則顯示,沒有資料則返回null
            if(execut.next()) {
                //id
                int nid = execut.getInt("id");
                //名稱
                String name = execut.getString("name");
                //年齡
                int age = execut.getInt("age");
                //地址
                String address = execut.getString("address");
                
                //例項化物件
                //這裡可以說將學生資訊封裝到所定的stu變數中
                stu=new student(nid,name,age,address);
            }
            //如果拿到了關於學生的資訊,則返回出去
            return stu;
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            //如果沒有拿到學生資訊,則返回null;
            return null;
            
        } catch (SQLException e) {
            e.printStackTrace();
            //如果沒有拿到學生資訊,則返回null;
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            //如果沒有拿到學生資訊,則返回null;
            return null;
        }
        finally {
            try {
                //釋放資源
                //這裡的意思是:當execut不等於空時,才執行釋放資源。以下都是這個意思
                if(execut!=null)execut.close();
                if(prepareStatement!=null)prepareStatement.close();
                if(conn!=null)conn.close();
            } catch (SQLException e) {
                
                e.printStackTrace();
            }
            
        }
    }
}
程式碼

(2)關於以上的查詢功能的作用是拿整體的資料,而這裡不取那麼多的資料,在原有的資料上建立一個子查詢呼叫查詢總的方法,這裡我取名為“isExit”,程式碼2如下:

//這是三層中的資料訪問層:原子性的增刪改查
package org.student.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.student.app.student;

import com.sun.org.apache.regexp.internal.recompile;

public class studentDao {
    //所要連線的資料庫
    String url="jdbc:mysql://localhost:3306/user";
    String user="root"; 
    String password="123"; 
····
    
    //在使用資料訪問層時,想要完成增加功能,就必須使用查詢功能,以免發成衝突,所以以下就是定義子查詢呼叫查詢總
    public boolean isExit(int id) throws Exception {
        //這是呼叫查詢總方法
        //解釋以下的寫法:下面也是進行判斷, 如果拿到了學生資訊,則返回true,沒有拿到的話,則返回false
        return atomicity(id)==null? false:true;
    }
····

}

注:這裡我想要的結果是向資料庫中增加新的資料。所以需要先完成查詢,再次增加。原因是:如果在新增資料時,發現此人已經存在的問題,則會增加失敗,所以在新增資料時,先進行查詢,如果此人沒有存在,才進行新增,接下來完成增加功能

(3)完成增加功能,提醒:只要新增失敗,都返回成false

//這是三層中的資料訪問層:原子性的增刪改查
package org.student.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.student.app.student;

import com.sun.org.apache.regexp.internal.recompile;

public class studentDao {
    //所要連線的資料庫
    String url="jdbc:mysql://localhost:3306/user";
    String user="root"; 
    String password="123"; 
    
    
    public boolean add(student stdent){
        try {
            
            student stu=null;
            //使用驅動
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn= DriverManager.getConnection(url,user,password);
            //sql語句,增加資料
            String sql="insert into student(id,name,age,address) value(?,?,?,?)";
            
            PreparedStatement prepareStatement = conn.prepareStatement(sql);
            
            prepareStatement.setInt(1, stdent.getId());
            prepareStatement.setString(2,stdent.getName());
            prepareStatement.setInt(3, stdent.getAge());
            prepareStatement.setString (4, stdent.getAddress());
            
            int cout=prepareStatement.executeUpdate();
            
            //如果是大於0,則返回增加成功
            if(cout>0) 
                return true;
            else 
                return false;
        } catch (ClassNotFoundException e) {
            return false;
            
        } catch (SQLException e) {
            
            return false;
        } catch (Exception e) {
            
            return false;
        }
        
    }
    
    
}

第五步:在業務邏輯層(StudentService.py)中進行組裝所寫的資料訪問層,接下來繼續完成業務邏輯層

//業務邏輯層,邏輯性的增加,想要增加的話,先進行查詢,如果此人不存在,再進行增加
package org.student.service;

import org.student.app.student;
import org.student.dao.studentDao;

public class StudentService {
    studentDao stu=new studentDao();
    public boolean add(student student) throws Exception {
        //判斷此人存不存在
        //查詢此人存不存在,不存在的話,才進行增加
        if(!stu.isExit(student.getId())) {
            stu.add(student);//這裡進行增加
            return true;
        }else {
            System.out.print("已存在");
            return false;
        }
    }
}

第六步:繼續完善表示層(servlet.java)下的doGet()方法,這裡是進行呼叫業務邏輯層(StudentServicce.java)

(1)完善的程式碼如下:

package org.student.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.student.app.student;
import org.student.service.StudentService;

public class servlet extends HttpServlet {
    

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
···
  //進行呼叫
        StudentService studentService = new StudentService();
        try {boolean add = studentService.add(stu);
            PrintWriter out = response.getWriter();
            if(add) {
                
                out.println("增加成功");
            }else {
                
                out.println("增加失敗");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            
        }
···  
}

(2)在執行專案時,直接在路徑的後面新增add.jsp(add.jsp是我自己建立的jsp,根據自己的jsp來),因為目前只做了新增功能,所以直接進入新增頁面,如果是其它的話,會出現500錯誤,先看怎麼在路徑後面新增

整體效果:

之後再依次填寫表單中的資訊,填寫好以後,再點選新增按鈕,然後會出現一個亂碼,但是所填寫好的資訊已經存在資料庫中效果如下:

檢視資料庫中所新增的資料,效果如下:

(3)出現了亂碼,所以接下來解決亂碼

注:在存到資料庫中的資料是沒有亂碼出現,只是在頁面中出現亂碼,所以接下來需要設定響應式編碼

在doGet()方法中進行設定,程式碼如下:

package org.student.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.student.app.student;
import org.student.service.StudentService;

public class servlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通過servlet來獲取JSP中表單所定義的欄位
        
        //將字串型別轉化成int型別
        int id=Integer.parseInt(request.getParameter("id"));
        
        String name=request.getParameter("name");
        
        //將字串型別轉化成int型別
        int age=Integer.parseInt(request.getParameter("age"));
        
        String address=request.getParameter("address");
        
        
        //例項化student類
        student stu=new student(id,name,age,address);
        
        //進行呼叫
        StudentService studentService = new StudentService();
        try {
            //解決亂碼,設定響應式編碼
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            
            boolean add = studentService.add(stu);
            PrintWriter out = response.getWriter();
            if(add) {
                
                out.println("增加成功");
            }else {
                
                out.println("增加失敗");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            
        }
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
程式碼

之後找到Servers檔案下的server.xml,點選server.xml,再找到Connector標籤,找到以後設定“utf-8”,效果如下:

最終再次執行專案,再新增資料,具體效果如下:

先填寫資訊

返回結果

檢視資料是否存到資料庫中

注:後面還有很多功能需要完成,這裡只是其中的一部分,後期在見!