JavaEE(10)——“學生資訊管理模組的”MVC實現
實驗10 “學生資訊管理模組的”MVC實現 一、實驗目的
- 重點掌握資料庫連線過程及增、刪、改、查操作;
- 重點掌握Servlet的應用;
- 掌握專案的結構及組成。 二、實驗演示效果
圖1 單擊連結“新增”,彈出圖2所示頁面。
圖2
- 在圖2所示頁面輸入一個學生相關資訊,如圖3所示。
圖3 3. 在圖2所示頁面中,單擊學號為10的學生所在行的“修改”修改連結,彈出如圖4所示頁面,在頁面上修改相關資料,如圖5所示。
圖4 圖5 單擊圖5頁面中的按鈕“修改”,彈出如圖6所示頁面,觀察記錄10資料。
圖6 3. 單擊圖6所示記錄為10的學生所在行中的刪除按鈕,彈出如圖7所示頁面。
圖7 單擊圖7所示頁面中的“刪除”按鈕,彈出如圖8所示頁面,觀察資料變更情況。
圖8
三、實驗任務與步驟 (一)專案結構圖如圖9所示。
圖9 (二) 建立資料庫及相關連線
- 實驗任務:設計一個Web專案,實現(一)所示功能。
- 實驗步驟。 【步驟1】 在MySQL中建立資料庫students(編碼為UTF-8),在該資料庫中新建表格student,向表格中插入幾條記錄,指令碼如下: /* Navicat MySQL Data Transfer
Source Server : localhost_33061 Source Server Version : 50170 Source Host : localhost:3306 Source Database : students
Target Server Type : MYSQL Target Server Version : 50170 File Encoding : 65001
Date: 2018-09-11 09:40:37 */
SET FOREIGN_KEY_CHECKS=0;
– Table structure for student
DROP TABLE IF EXISTS student
;
CREATE TABLE student
(
id
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(20) DEFAULT NULL,
sex
varchar(8) DEFAULT NULL,
age
grade
varchar(30) DEFAULT NULL,
score
float DEFAULT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
– Records of student
INSERT INTO student
VALUES (‘1’, ‘張轉’, ‘男’, ‘20’, ‘16計算機3班’, ‘96’);
INSERT INTO student
VALUES (‘2’, ‘楊和’, ‘男’, ‘22’, ‘16計算機1班’, ‘98’);
INSERT INTO student
VALUES (‘4’, ‘李智’, ‘女’, ‘19’, ‘16計算機1班’, ‘90’);
INSERT INTO student
VALUES (‘5’, ‘何輝’, ‘男’, ‘18’, ‘16計算機3班’, ‘88’);
INSERT INTO student
VALUES (‘7’, ‘Tom’, ‘男’, ‘19’, ‘16計算機2班’, ‘87’);
INSERT INTO student
VALUES (‘8’, ‘Jenny’, ‘nv’, ‘19’, ‘16計算機2班’, ‘99’);
【步驟2】新建Web專案,向專案中匯入MySQL驅動程式(如:mysql-connector-java-5.1.18-bin.jar)。
【步驟3】建立實體類
實體類與資料庫表student進行對映,建立一個實體類student.java,其屬性與資料庫表student的欄位對應,程式需要獲取資料庫表student中的資料,然後存放到該實體類的例項中(即物件中)。實體類Student.java對應程式碼如程式碼1所示。
程式碼1:Student.java
package entity;
public class Student { public int id; public String name; public String sex; public String grade; public int age; public float score; 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 getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } } 注意:實體類的型別與個數與資料庫表student的欄位個數與型別對應。 【步驟4】設計訪問資料庫的工具類JavaBean(Dbconn.java)程式碼如程式碼2所示。 程式碼2:Dbconn.java package dbutil;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;
public class Dbconn {
private Connection conn;
public Connection getConnection() throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/students?useUnicode=true&characterEncoding=utf8","root","");
} catch (ClassNotFoundException e) {
System.out.println("連線異常!");
e.printStackTrace();
}
return conn;
}
public void closeAll(Connection conn,Statement stat,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}
}
} 【步驟5】設計訪問資料庫的業務邏輯類(StudentModel.java),包括對資料庫的增刪改查操作,參考程式碼如程式碼3所示。 程式碼3:StudentModel.java package model;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;
import dbutil.Dbconn; import entity.Student;
public class StudentModel { private static PreparedStatement ps; private static ResultSet rs; static Dbconn s=new Dbconn();
public List search(){
List studentlist = null;
String sql = "select * from student";
try {
Connection conn=s.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
studentlist = new ArrayList();
while(rs.next()){
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
student.setSex(rs.getString("sex"));
student.setGrade(rs.getString("grade"));
student.setScore(rs.getFloat("score"));
studentlist.add(student);
}
s.closeAll(conn,ps,rs);
} catch (Exception e) {
e.printStackTrace();
}
return studentlist;
}
public Student load(Integer id) {
Student student = null;
String sql = "select * from student where student.id = ? ";
try {
Connection conn=s.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, id.intValue());
rs = ps.executeQuery();
if(rs.next()){
student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex"));
student.setAge(rs.getInt("age"));
student.setGrade(rs.getString("grade"));
student.setScore(rs.getFloat("score"));
}
s.closeAll(conn,ps,rs);
} catch (Exception e) {
e.printStackTrace();
}
return student;
}
public int update(int id,String name,String sex,int age,String grade,float score){
int a=0;
try {
Connection conn=s.getConnection();
String sql="update student set name=?,sex=?,age=?,grade=?,score=? where id=?";
ps=conn.prepareStatement(sql);
ps.setInt(6, id);
ps.setString(1, name);
ps.setString(2, sex);
ps.setInt(3,age);
ps.setString(4,grade);
ps.setFloat(5,score);
a=ps.executeUpdate();
s.closeAll(conn,ps,rs);
} catch (SQLException e) {
e.printStackTrace();
}
return a;
}
public int insert(int id,String name,String sex,int age,String grade,float score){
int a=0;
try {
Connection conn=s.getConnection();
String sql="insert student values(?,?,?,?,?,?)";
ps=conn.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, name);
ps.setString(3, sex);
ps.setInt(4,age);
ps.setString(5,grade);
ps.setFloat(6,score);
a=ps.executeUpdate();
s.closeAll(conn,ps,rs);
} catch (SQLException e) {
e.printStackTrace();
}
return a;
}
public int delete(int id){
int a=0;
try {
Connection conn=s.getConnection();
String sql="delete from student where student.id=?";
ps=conn.prepareStatement(sql);
ps.setInt(1, id);
a=ps.executeUpdate();
s.closeAll(conn,ps,rs);
} catch (SQLException e) {
e.printStackTrace();
}
return a;
}
} 【步驟6】設計控制層的Servlet,程式碼如程式碼4到程式碼9所示。 程式碼4:Deleteservlet.java package control;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import model.StudentModel;
public class Deleteservlet extends HttpServlet {
/**
* Constructor of the object.
*/
public Deleteservlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int id=Integer.parseInt(request.getParameter("id"));
StudentModel model = new StudentModel();
model.delete(id);
response.sendRedirect("ListStudentServlet.do");
}
}
程式碼5:DoUpdateservlet.java package control;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import model.StudentModel;
public class DoUpdateservlet extends HttpServlet {
public DoUpdateservlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String sex = request.getParameter("sex");
int age = Integer.parseInt(request.getParameter("age"));
String grade = request.getParameter("grade");
float score = Float.parseFloat(request.getParameter("score"));
StudentModel model = new StudentModel();
model.update(id, name, sex, age, grade, score);
response.sendRedirect("ListStudentServlet.do");
}
}
程式碼6:Insertservlet.java package control;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import model.StudentModel;
public class Insertservlet extends HttpServlet {
public Insertservlet() {
super();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String sex = request.getParameter("sex");
int age = Integer.parseInt(request.getParameter("age"));
String grade = request.getParameter("grade");
float score = Float.parseFloat(request.getParameter("score"));
StudentModel model = new StudentModel();
model.insert(id, name, sex, age, grade, score);
response.sendRedirect("ListStudentServlet.do");
}
}
程式碼7:ListStudentServlet.java package control;
import java.io.IOException; import java.util.List;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import model.StudentModel;
public class ListStudentServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentModel model = new StudentModel();
List list = model.search();
request.setAttribute("studentlist", list);
request.getRequestDispatcher("/jsp/studentlist.jsp").forward(request, response);
//response.sendRedirect("jsp/studentlist.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
} 程式碼8:ShowStudentServlet.java package control;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import model.StudentModel; import entity.Student;
public class ShowStudentServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 得到傳入引數:學生ID
String id = request.getParameter("id");
if (null==id)
{
request.setAttribute("error", "沒有該學生!");
request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
return ;
}
Integer studentId = Integer.valueOf(id);
// 呼叫查詢方法,得到學生資料
StudentModel model = new StudentModel();
Student student = model.load(studentId);
if (null==student)
{
request.setAttribute("error", "沒有指定編號的學生記錄");
request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
return ;
}
// 將學生資料儲存到request中
request.setAttribute("student", student);
// 轉發到student.jsp
request.getRequestDispatcher("/jsp/studentshow.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}
程式碼9:Updateservlet.java package control;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import model.StudentModel; import entity.Student;
public class Updateservlet extends HttpServlet {
/**
* Constructor of the object.
*/
public Updateservlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
// 得到傳入引數:學生ID
String id = request.getParameter("id");
if (null==id)
{
request.setAttribute("error", "沒有該學生!");
request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
return ;
}
Integer studentId = Integer.valueOf(id);
// 呼叫查詢方法,得到學生資料
StudentModel model = new StudentModel();
Student student = model.load(studentId);
if (null==student)
{
request.setAttribute("error", "沒有指定編號的學生記錄");
request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
return ;
}
// 將管理員資料儲存到request中
request.setAttribute("student", student);
// 轉發到student.jsp
request.getRequestDispatcher("/jsp/studentupdate.jsp").forward(request, response);
}
} 【步驟7】配置檔案web.xml,如程式碼10所示。 程式碼10:web.xml
<?xml version="1.0" encoding="UTF-8"?> showStudent showStudentServlet control.ShowStudentServlet ListStudentServlet control.ListStudentServlet insertStudentservlet control.Insertservlet deleteStudentservlet control.Deleteservlet updateStudentservlet control.Updateservlet doupdateStudentservlet control.DoUpdateservlet showStudentServlet /showStudent.do ListStudentServlet /ListStudentServlet.do insertStudentservlet /InsertStudentservlet.do deleteStudentservlet /DeleteStudentservlet.do updateStudentservlet /UpdateStudentservlet.to doupdateStudentservlet /DoUpdatStudenteservlet.do 【步驟8】設計MVC檢視層的jsp頁面,在WebRoot下新建資料夾jsp,將新建的jsp頁面放到jsp資料夾下,jsp頁面對應程式碼如程式碼11到程式碼16所示。 程式碼11:studentinsert.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>插入學生資訊
<p>學號: <input type="text" name="id"></p>
<p>姓名:
<input type="text" name="name" />
<br></p>
<p>性別:
<input type="text" name="sex" />
<br></p>
<p> 年齡:
<input type="text" name="age" />
<br></p>
<p> 班級:
<input type="text" name="grade" />
<br></p>
<p> 成績:
<input type="text" name="score" />
<br></p>
<input type="submit" value="提交" />
<input type="reset" value="重置" />
</form>
</center>
程式碼12:studentlist.jsp <%@ page language=“java” contentType=“text/html; charset=UTF-8” pageEncoding=“GBK”%> <%@ taglib uri=“http://java.sun.com/jsp/jstl/core” prefix=“c”%>
學生資訊列表 |
新增 |
學號 | 姓名 | 年齡 | 班級 | 成績 | 修改 | 刪除 |
---|---|---|---|---|---|---|
${studentitem.id} | ${studentitem.name} | ${studentitem.age} | ${studentitem.grade} | ${studentitem.score} | 修改 | 刪除 |
程式碼13:studentshow.jsp <%@ page language=“java” contentType=“text/html; charset=UTF-8” pageEncoding=“GBK”%>
刪除的學生資訊
<tr>
<td align="center">
編號
</td>
<td>
${student.id}
</td>
</tr>
<tr>
<td align="center">
姓名
</td>
<td>
${student.name}
</td>
</tr>
<tr>
<td align="center">
性別
</td>
<td>
${student.sex}
</td>
</tr>
<tr>
<td align="center">
班級
</td>
<td>
${student.grade}
</td>
</tr>
<tr>
<td align="center">
年齡
</td>
<td>
${student.age}
</td>
</tr>
<tr>
<td align="center">
成績
</td>
<td>
${student.score}
</td>
</tr>
</table>
<table align="center" width="360" border="0">
<tr>
<td align="center">
<form action="DeleteStudentservlet.do?id=${student.id}" method="post">
<input type="submit" value="刪除">
</form>
</td>
<td align="center">
<form action="ListStudentServlet.do" method="post">
<input type="submit" value="返回">
</form>
</td>
</tr>
</table>
</body>
程式碼14:studentupdate.jsp <%@ page language=“java” import=“java.util.,dbutil.,entity.,model.” pageEncoding=“UTF-8”%>
<body>
<center>
<h1>
修改學生資訊
</h1>
<form action="DoUpdatStudenteservlet.do?id=${student.id}" method="post">
<p>
學號: ${student.id}
</p>
<p>
姓名:
<input type="text" name="name" value="${student.name}" />
<br>
</p>
<p>
性別:
<input type="text" name="sex" value="${student.sex}" />
<br>
</p>
<p>
年齡:
<input type="text" name="age" value="${student.age}" />
<br>
</p>
<p>
班級:
<input type="text" name="grade" value="${student.grade}" />
<br>
</p>
<p>
成績:
<input type="text" name="score" value="${student.score}" />
<br>
</p>
<input type="submit" value="修改" />
<input type="reset" value="重置" />
</form>
</center>
</body>
程式碼15:error.jsp <%@ page language=“java” pageEncoding=“UTF-8”%>
出錯啦,請重新再試! |