JavaEE(10)——“学生信息管理模块的”MVC实现

版权声明:zhaoxuyang1997@zxy97.com https://blog.csdn.net/zhaoxuyang1997/article/details/82942666

实验10 “学生信息管理模块的”MVC实现
一、实验目的

  1. 重点掌握数据库连接过程及增、删、改、查操作;
  2. 重点掌握Servlet的应用;
  3. 掌握项目的结构及组成。
    二、实验演示效果
  4. 设项目名称为“studentmanager”,项目部署成功后,在浏览器地址栏输入如下地址:
    http://localhost:8080/studentmanager/ListStudentServlet.do
    弹出如图1所示页面。

图1
单击链接“新增”,弹出图2所示页面。

图2

  1. 在图2所示页面输入一个学生相关信息,如图3所示。

图3
3. 在图2所示页面中,单击学号为10的学生所在行的“修改”修改链接,弹出如图4所示页面,在页面上修改相关数据,如图5所示。

图4 图5
单击图5页面中的按钮“修改”,弹出如图6所示页面,观察记录10数据。

图6
3. 单击图6所示记录为10的学生所在行中的删除按钮,弹出如图7所示页面。

图7
单击图7所示页面中的“删除”按钮,弹出如图8所示页面,观察数据变更情况。

图8

三、实验任务与步骤
(一)项目结构图如图9所示。

图9
(二) 建立数据库及相关连接

  1. 实验任务:设计一个Web项目,实现(一)所示功能。
  2. 实验步骤。
    【步骤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 int(11) DEFAULT NULL,
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”%>

出错啦

出错啦,请重新再试!

四、思考题 1. 理解本程序的执行过程,设计相关功能模块的流程图。 2. 理解模块中各个Servlet的功能及与页面的关系。 五、实验总结 本实验通过一个完整的“学生信息管理模块”MVC模式开发案例,介绍了模块的分解(包括增加、删除、修改、查询子模块)、数据库设计以及MVC模式的代码实现。

没有更多推荐了,返回首页