Web基础之Servlet+JDBC+JSP项目实战记录(二)
一、项目说明:
通过前面的实战,我们已经通过Servlet+JDBC+JSP实现了新增班级信息以及显示班级信息的功能;接下来我们将继续这个项目的编写;从一个非常简单的小项目一步一步完善到一个比较成熟的小项目;
二、需求分析:
在实现新增班级和显示班级的基础上;
通过查看班级明细,能够显示该班级所有的学生信息;
为该班级新增学生信息;
三、项目思路分析:
1、在数据库中新建学生表,并自己设计学生表的字段;
2、编写实体类,和数据库中的学生表对应;
3、更改班级前台JSP界面;新增查看明细链接;
4、编写学生前台JSP界面
5、编写新增学生信息的Servlet类
6、编写新增学生信息的数据库操作类
数据库字段设计:
四、整体项目架构:
整个项目的访问流程:
访问classinfo.jsp页面(刚开始不会显示班级信息,因为此时request作用域中没有信息)
--> 新增班级信息(点确定)
-->ClassInfoServlet类处理(获取提交的班级信息)
-->ClassInfoServlet类中调用ClassInfoDao向数据库中插入新的班级信息
-->ClassInfoServlet类中调用ClassInfoDao查询所有班级信息并将查询到结果保存到request作用域中
-->转发请求,将请求再次交给classinfo.jsp前台页面处理(此时request作用域中有信息,会显示班级信息)
-->classinfo.jsp前台页示所有班级信息
-->点击查看每个班级后面查看明细链接
-->点击链接后,会发起GET请求
-->StudentInfoServlet类处理GET请求
-->StudentInfoServlet类获取GET请求的参数
-->StudentInfoServlet类中根据参数调用StudentInfoDao查询学生信息
-->将查询到的信息保存到request作用域中
-->转发请求,将请求转发给studentInfo.jsp处理
-->studentInfo.jsp前台页面显示查询到的信息以及可新增班级信息的界面
-->在studentInfo.jsp前台页面上点击新增班级信息
-->StudentInfoServlet类处理请求
-->StudentInfoServlet类中根据参数调用StudentInfoDao新增学生信息
-->StudentInfoServlet类中根据参数调用StudentInfoDao查询学生信息
-->将查询到的信息保存到request作用域中
-->转发请求,将请求再次交给studentInfo.jsp处理
-->studentInfo.jsp前台页面刷新,显示新增学生信息的结果
五、项目运行效果:
六、项目源代码:
classInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- 导入所需要的Java类相当于Java代码中的import -->
<%@ page import="com.huaxin.bean.ClassInfoBean"%>
<%@ page import="java.util.List"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>班级信息界面</title>
<style type="text/css">
th {
text-align: center;
}
td {
text-align: center;
}
</style>
</head>
<body>
<div style="margin: 0 auto; margin-top: 40px;">
<form action="classInfoReq?reqType=QUERY_ALL_CLASS" method="POST">
<center>
<table width="40%" ; border="1" ; bgcolor="#FFFFC6">
<caption style="margin-bottom: 20px">新增班级信息</caption>
<tr>
<td>班级名称:</td>
<td><input type="text" name="className"></td>
</tr>
<tr>
<td><input type="reset" value="重置"></td>
<td><input type="submit" value="确定"></td>
</tr>
</table>
</center>
</form>
</div>
<div style="margin: 0 auto; margin-top: 40px;">
<center>
<table width="40%" ; border="1" ; bgcolor="#FFFFC6">
<caption style="margin-bottom: 20px">班级信息列表</caption>
<tr>
<th>班级序号</th>
<th>班级名称</th>
<th>班级明细</th>
</tr>
<!-- 嵌入Java代码,注意配对 -->
<%
//从request作用域中取出保存的结果
List<ClassInfoBean> classInfo=(List<ClassInfoBean>)request.getAttribute("classInfo");
if(classInfo!=null && !classInfo.isEmpty()){
for(ClassInfoBean classes : classInfo){
%>
<tr>
<td><%=classes.getCid()%></td>
<td><%=classes.getCname()%></td>
<td><a
href="http://localhost:8080/JDBC/findAllStudentByClassId?reqType=FIND_STUDENT_BY_CLASS_ID&cid=<%=classes.getCid()%>">查看明细</a></td>
</tr>
<%
}
}
%>
</table>
</center>
</div>
</body>
</html>
studentInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.List"%>
<%@ page import="com.huaxin.bean.StudentInfoBean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增学生信息页面</title>
<style type="text/css">
tr {
text-align: center;
}
</style>
</head>
<body>
<div style="margin: 0 auto; margin-top: 40px;">
<form action="addStuInfoReq?reqType=ADD_STU_INFO" method="POST">
<center>
<table width="40%" ; border="1" ; bgcolor="#FFFFC6">
<caption style="margin-bottom: 20px">新增学生信息</caption>
<tr>
<td>学生姓名:</td>
<td><input type="text" name="stuSname"></td>
</tr>
<tr>
<td>学生性别:</td>
<td><select width="300px" name="stuSsex">
<option>男</option>
<option>女</option>
</select></td>
</tr>
<tr>
<td>学生年龄:</td>
<td><input type="text" name="stuSage"> <input
type="hidden" name="classId"
value="<%=request.getParameter("cid")%>"></td>
</tr>
<tr>
<td><input type="reset" value="重置"></td>
<td><input type="submit" value="确定"></td>
</tr>
</table>
</center>
</form>
</div>
<div style="margin: 0 auto; margin-top: 40px;">
<center>
<table width="80%" ; border="1" ; bgcolor="#FFFFC6">
<caption style="margin-bottom: 20px">学生信息列表</caption>
<tr>
<th>所属班级</th>
<th>学生学号</th>
<th>学生姓名</th>
<th>学生性别</th>
<th>学生年龄</th>
<th>余额</th>
<th> 操作类型 </th>
</tr>
<%
List<StudentInfoBean> stuInfo=(List<StudentInfoBean>)request.getAttribute("allStudentInfo");
for(StudentInfoBean stu: stuInfo){
%>
<tr>
<td><%=stu.getCid()%></td>
<td><%=stu.getSno()%></td>
<td><%=stu.getSname()%></td>
<td><%=stu.getSsex()%></td>
<td><%=stu.getSage()%></td>
<td><%=stu.getSbalance()%></td>
<td><a>充值</a> <a>消费</a></td>
</tr>
<%
}
%>
</table>
</center>
</div>
</body>
</html>
两个Bean类
package com.huaxin.bean;
public class ClassInfoBean {
private Integer cid;
private String cname;
public ClassInfoBean() {
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
}
package com.huaxin.bean;
import java.math.BigDecimal;
public class StudentInfoBean {
private Integer sno;
private String sname;
private String ssex;
private Integer sage;
private Integer cid;
private BigDecimal sbalance;
public BigDecimal getSbalance() {
return sbalance;
}
public void setSbalance(BigDecimal sbalance) {
this.sbalance = sbalance;
}
public Integer getSno() {
return sno;
}
public void setSno(Integer sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSsex() {
return ssex;
}
public void setSsex(String ssex) {
this.ssex = ssex;
}
public Integer getSage() {
return sage;
}
public void setSage(Integer sage) {
this.sage = sage;
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
}
两个Dao类
package com.huaxin.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.huaxin.Util.DBUtil;
import com.huaxin.bean.ClassInfoBean;
public class ClassInfoDao {
public void addClassInfo(ClassInfoBean bean) {
Connection conn = null;
Statement stmt = null;
try {
// 获取数据库连接
conn=DBUtil.getConnection();
// 整理一条SQL语句
String sql = "INSERT INTO class_info (cname) VALUES ('"
+ bean.getCname() + "')";
// 创建SQL执行对象
stmt = conn.createStatement();
// 执行sql语句
int row = stmt.executeUpdate(sql);
if (row != 1) {
throw new RuntimeException("新增班级失败!");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtil.release(conn, stmt, null);
}
}
public List<ClassInfoBean> findAll() {
Connection conn = null;
Statement stmt = null;
ResultSet rs =null;
List<ClassInfoBean> classList= new ArrayList<ClassInfoBean>();
try {
// 获取连接
conn = DBUtil.getConnection();
// 整理一条SQL语句
String sql = "select cid,cname from class_info";
// 创建执行sql的对象
stmt = conn.createStatement();
//执行sql语句
rs =stmt.executeQuery(sql);
//遍历结果集
while(rs.next()){
int cid =rs.getInt("cid");
String cname=rs.getString("cname");
ClassInfoBean bean = new ClassInfoBean();
bean.setCid(cid);
bean.setCname(cname);
classList.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtil.release(conn, stmt, rs);
}
return classList;
}
}
package com.huaxin.dao;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.huaxin.Util.DBUtil;
import com.huaxin.bean.ClassInfoBean;
import com.huaxin.bean.StudentInfoBean;
public class StudentInfoDao {
public void addStudentInfo(StudentInfoBean bean) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 获取数据库连接
conn=DBUtil.getConnection();
// 整理一条SQL语句
String sql = "INSERT INTO student_info (sname,ssex,sage,cid,sbalance) VALUES (?,?,?,?,?)";
// 创建SQL执行对象
pstmt=conn.prepareStatement(sql);
// 给预处理对象赋值
pstmt.setString(1, bean.getSname());
pstmt.setString(2, bean.getSsex());
pstmt.setInt(3, bean.getSage());
pstmt.setInt(4, bean.getCid());
pstmt.setBigDecimal(5, BigDecimal.ZERO);
//执行SQL语句
int row=pstmt.executeUpdate();
if (row != 1) {
throw new RuntimeException("新增学生信息失败!");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtil.release(conn, pstmt, null);
}
}
public List<StudentInfoBean> findAllStudentByClassId(int cid) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs =null;
List<StudentInfoBean> stuList= new ArrayList<StudentInfoBean>();
try {
// 获取连接
conn = DBUtil.getConnection();
// 整理一条SQL语句
//String sql = "SELECT sno,sname,ssex,sage,sbalance from student_info where cid=?";
// 创建执行sql的对象
pstmt = conn.prepareStatement("SELECT cid,sno,sname,ssex,sage,sbalance from student_info where cid=?");
//执行sql语句
pstmt.setInt(1, cid);
rs =pstmt.executeQuery();
//遍历结果集
while(rs.next()){
int scid =rs.getInt("cid");
int sno=rs.getInt("sno");
String name=rs.getString("sname");
String ssex=rs.getString("ssex");
int sage=rs.getInt("sage");
BigDecimal sbalance =rs.getBigDecimal("sbalance");
//封装成学生Bean对象
StudentInfoBean bean = new StudentInfoBean();
bean.setCid(scid);
bean.setSno(sno);
bean.setSname(name);
bean.setSage(sage);
bean.setSsex(ssex);
bean.setSbalance(sbalance);
//添加到队列中
stuList.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtil.release(conn, pstmt, rs);
}
return stuList;
}
}
Util工具类:
package com.huaxin.Util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
static{
// 加载数据库驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = null;
try {
// 获取数据库连接
conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/studentsystem?useUnicode=true&characterEncoding=UTF-8",
"root", "zhou");
}catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
// 关闭相关连接
public static void release(Connection conn,Statement stmt ,ResultSet rs){
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
两个Servlet类:
package com.huaxin.servlet;
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 com.huaxin.bean.ClassInfoBean;
import com.huaxin.dao.ClassInfoDao;
public class ClassInfoServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置编码,防止请求乱码
req.setCharacterEncoding("UTF-8");
//获取参数
String className=req.getParameter("className");
//获取请求类型
String reqType=req.getParameter("reqType");
if("QUERY_ALL_CLASS".equals(reqType)){
//创建ClassInfoBean对象保存信息
ClassInfoBean bean =new ClassInfoBean();
bean.setCname(className);
//创建数据库操作对象
ClassInfoDao dao =new ClassInfoDao();
//新增班级信息到数据库
dao.addClassInfo(bean);
//查询所有班级信息
List<ClassInfoBean> classInfo=dao.findAll();
//保存查询的班级信息
req.setAttribute("classInfo", classInfo);
//转发请求
req.getRequestDispatcher("/classInfo.jsp").forward(req, resp);
}
}
}
package com.huaxin.servlet;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.huaxin.bean.StudentInfoBean;
import com.huaxin.dao.StudentInfoDao;
public class StudentInfoServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置编码防止响应乱码
req.setCharacterEncoding("UTF-8");
//获取请求类型
String reqType=req.getParameter("reqType");
if("FIND_STUDENT_BY_CLASS_ID".equals(reqType)){
//获取客户端输入的参数
int cid=Integer.parseInt(req.getParameter("cid"));
//创建学生数据库操作对象
StudentInfoDao dao = new StudentInfoDao();
List<StudentInfoBean> allStudentInfo=dao.findAllStudentByClassId(cid);
//保存查询到的学生信息
req.setAttribute("allStudentInfo", allStudentInfo);
//将查询结果交给jsp处理
req.getRequestDispatcher("/studentInfo.jsp").forward(req, resp);
}
if("ADD_STU_INFO".equals(reqType)){
//获取客户端输入的参数
int cid=Integer.parseInt(req.getParameter("classId"));
String stuname=req.getParameter("stuSname");
String stusex=req.getParameter("stuSsex");
int stuage=Integer.parseInt(req.getParameter("stuSage"));
StudentInfoBean bean =new StudentInfoBean();
bean.setCid(cid);
bean.setSbalance(BigDecimal.ZERO);
bean.setSage(stuage);
bean.setSname(stuname);
bean.setSsex(stusex);
//创建学生数据库操作对象
StudentInfoDao dao = new StudentInfoDao();
dao.addStudentInfo(bean);
List<StudentInfoBean> allStudentInfo=dao.findAllStudentByClassId(cid);
//保存查询到的学生信息到req作用域中
req.setAttribute("allStudentInfo", allStudentInfo);
//将查询结果交给jsp处理
req.getRequestDispatcher("/studentInfo.jsp?cid="+cid+"").forward(req, resp);
}
}
}
web.xm配置文件(每写一个Servlet类记得要配置在该文件中并配置路径)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>JDBC2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>classInfo</servlet-name>
<servlet-class>com.huaxin.servlet.ClassInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>classInfo</servlet-name>
<url-pattern>/classInfoReq</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>addStuInfo</servlet-name>
<servlet-class>com.huaxin.servlet.StudentInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addStuInfo</servlet-name>
<url-pattern>/addStuInfoReq</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>findstuInfo</servlet-name>
<servlet-class>com.huaxin.servlet.StudentInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>findstuInfo</servlet-name>
<url-pattern>/findAllStudentByClassId</url-pattern>
</servlet-mapping>
</web-app>
七、总结
1、对JSP有了更加深入的了解;
2、对B/S模式有了更加深刻的认识;
3、再次体会到实体和数据库表的映射关系;
4、对路径的配置以及跳转有了深刻的认识,自己也能对平时打开的网页时,浏览器中地址栏中信息解读;
5、知道了一个WEB应用大致的开发流程;
6、在项目中,比较让我头痛的整个项目的流程,刚开始不太知道整个项目是怎么玩起来的,后来一步一步梳理思路,终于明白了整个项目的流程;
共勉!