先在/WEB-INF/jsp文件夹里新建grade文件夹,在其中新建gradeList.jsp文件
将资料中的/grade/gradeList.html文件内容拷贝到新建的文件里
将gradeList.jsp中的相对路径改成合适的(和courseList.jsp一样,cv过来即可)
alt+回车将名称空间导入进来
在/demo/servlet中新建grade文件夹,在其中新建GradeServlet文件输入如下代码
修改admin.jsp中如下年级列表的url
在/demo/model中新建Grade代码如下
package demo.model;
/**
* model/entity po (persistent object)这个类和数据库中的表是一一对应的
* dto (data transfer object)用来转换model和vo
* vo (view object)这是前端来展示的数据,这个和前端是一一对应的
* bo (business object)
*/
public class Grade {
private Integer gid;
private String gradeName;
public Integer getGid() {
return gid;
}
public void setGid(Integer gid) {
this.gid = gid;
}
public String getGradeName() {
return gradeName;
}
public void setGradeName(String gradeName) {
this.gradeName = gradeName;
}
}
继续新建GradeDTO,代码如下
package demo.model;
import java.util.List;
public class GradeDTO extends Grade {
private List<Course> courses;
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
继续GradeServlet如下,并在service文件夹新建GradeService文件
在GradeService中补全方法如下,并在dao文件夹新建GradeDao
在GradeDao补全方法如下
先在SQLyog里运行SQL语句无误后再写入代码中
手动处理一对多
在GradeService中捕获异常
用Postman测试一下先
代码补全及注释
gradeList.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>教师列表</title>
<link href='<c:url context="${pageContext.request.contextPath}" value="/easyui/themes/default/easyui.css"/>' rel="stylesheet" type="text/css" />
<link href='<c:url context="${pageContext.request.contextPath}" value="/easyui/themes/icon.css"/>' rel="stylesheet" type="text/css" />
<link href='<c:url context="${pageContext.request.contextPath}" value="/easyui/css/demo.css"/>' rel="stylesheet" type="text/css" />
<script type="text/javascript" src='<c:url value="/easyui/jquery.min.js" context="${pageContext.request.contextPath}"/>'></script>
<script type="text/javascript" src='<c:url value="/easyui/jquery.easyui.min.js" context="${pageContext.request.contextPath}"/>'></script>
<script type="text/javascript" src='<c:url value="/easyui/js/validateExtends.js" context="${pageContext.request.contextPath}"/>'></script>
<script type="text/javascript">
$(function() {
//datagrid初始化
$('#dataList').datagrid({
title:'年级列表',
iconCls:'icon-more',//图标
border: true,
collapsible: false,//是否可折叠的
fit: true,//自动大小
method: "post",
url:"GradeServlet?method=GradeList&course=course&t="+new Date().getTime(),
idField:'id',
singleSelect: true,//是否单选
pagination: false,//分页控件
rownumbers: true,//行号
sortName:'id',
sortOrder:'DESC',
remoteSort: false,
columns: [[
{field:'chk',checkbox: true,width:50},
{field:'id',title:'ID',width:50, sortable: true},
{field:'name',title:'年级名称',width:200},
{field:'courseList',title:'年级课程',width:650,
formatter: function(value,row,index){
if (row.courseList){
var cl = " | ";
var list = row.courseList;
for(var i=0;i < list.length;i++){
cl += list[i].name+" | ";
}
return cl;
} else {
return value;
}
}
},
]],
toolbar: "#toolbar"
});
//设置工具类按钮
$("#add").click(function(){
$("#addDialog").dialog("open");
});
//删除
$("#delete").click(function(){
var selectRow = $("#dataList").datagrid("getSelected");
if(selectRow == null){
$.messager.alert("消息提醒", "请选择数据进行删除!", "warning");
} else{
var gradeid = selectRow.id;
$.messager.confirm("消息提醒", "将删除与年级相关的所有数据(包括班级,学生),确认继续?", function(r){
if(r){
$.ajax({
type: "post",
url: "GradeServlet?method=DeleteGrade",
data: {gradeid: gradeid},
success: function(msg){
if(msg == "success"){
$.messager.alert("消息提醒","删除成功!","info");
//刷新表格
$("#dataList").datagrid("reload");
} else{
$.messager.alert("消息提醒","删除失败!","warning");
return;
}
}
});
}
});
}
});
//课程下拉框
$("#add_courseList").combobox({
valueField: "id",
textField: "name",
multiple: true, //可多选
editable: false, //不可编辑
method: "post",
url: "CourseServlet?method=CourseList&t="+new Date().getTime(),
});
//设置添加学生窗口
$("#addDialog").dialog({
title: "添加年级",
width: 500,
height: 400,
iconCls: "icon-add",
modal: true,
collapsible: false,
minimizable: false,
maximizable: false,
draggable: true,
closed: true,
buttons: [
{
text:'添加',
plain: true,
iconCls:'icon-world-add',
handler:function(){
var validate = $("#addForm").form("validate");
if(!validate){
$.messager.alert("消息提醒","请检查你输入的数据!","warning");
return;
} else{
$.ajax({
type: "post",
url: "GradeServlet?method=AddGrade",
data: $("#addForm").serialize(),
success: function(msg){
if(msg == "success"){
$.messager.alert("消息提醒","添加成功!","info");
//关闭窗口
$("#addDialog").dialog("close");
//清空原表格数据
$("#add_name").textbox('setValue', "");
$("#add_courseList").combobox("clear");
//重新刷新页面数据
$('#dataList').datagrid("reload");
} else{
$.messager.alert("消息提醒","添加失败!","warning");
return;
}
}
});
}
}
},
{
text:'重置',
plain: true,
iconCls:'icon-world-reset',
handler:function(){
$("#add_name").textbox('setValue', "");
$("#add_courseList").combobox("clear");
}
},
]
});
});
</script>
</head>
<body>
<!-- 数据列表 -->
<table id="dataList" cellspacing="0" cellpadding="0">
</table>
<!-- 工具栏 -->
<div id="toolbar">
<div style="float: left;"><a id="add" href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">添加</a></div>
<div style="float: left;" class="datagrid-btn-separator"></div>
<div><a id="delete" href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-some-delete',plain:true">删除</a></div>
</div>
<!-- 添加数据窗口 -->
<div id="addDialog" style="padding: 10px">
<form id="addForm" method="post">
<table cellpadding="8" >
<tr>
<td>年级名称:</td>
<td><input id="add_name" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="name" data-options="required:true, validType:'repeat_grade', missingMessage:'不能为空'" /></td>
</tr>
<tr>
<td>选择课程:</td>
<td><select id="add_courseList" style="width: 200px; height: 30px;" name="clazzid" data-options="required:true, missingMessage:'请选择课程'" ></select></td>
</tr>
</table>
</form>
</div>
</body>
</html>
GradeServlet.java
package demo.servlet.grade;
import com.fasterxml.jackson.databind.ObjectMapper;
import demo.model.GradeDTO;
import demo.service.GradeService;
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
//http://localhosst:8080/s/grade?action=page
@WebServlet(urlPatterns = "/grade")
public class GradeServlet extends HttpServlet {
GradeService gradeService =new GradeService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
if ("page".equals(action)){
req.getRequestDispatcher("/WEB-INF/jsp/grade/gradeList.jsp").forward(req,resp);
}else if ("data".equals(action)){
//获取json
//查询所有的年级
List<GradeDTO> list =gradeService.getAllGrades();
resp.setContentType("application/json;charset=utf-8");
PrintWriter out=resp.getWriter();
out.write(new ObjectMapper().writeValueAsString(list));
}
}
}
admin.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>学生成绩管理系统 管理员后台</title>
<link rel="shortcut icon" href="favicon.ico"/>
<link rel="bookmark" href="favicon.ico"/>
<link href='<c:url context="${pageContext.request.contextPath}" value="/easyui/css/default.css"/>' rel="stylesheet" type="text/css" />
<link href='<c:url context="${pageContext.request.contextPath}" value="/easyui/themes/default/easyui.css"/>' rel="stylesheet" type="text/css" />
<link href='<c:url context="${pageContext.request.contextPath}" value="/easyui/themes/icon.css"/>' rel="stylesheet" type="text/css" />
<script type="text/javascript" src='<c:url value="/easyui/jquery.min.js" context="${pageContext.request.contextPath}"/>'></script>
<script type="text/javascript" src='<c:url value="/easyui/jquery.easyui.min.js" context="${pageContext.request.contextPath}"/>'></script>
<script type="text/javascript" src='<c:url value="/easyui/js/outlook2.js" context="${pageContext.request.contextPath}"/>'></script>
<%-- <script type="text/javascript" src='<c:url value="/easyui/js/easyui-lang-zh_CN.js" context="${pageContext.request.contextPath}"/>'></script>--%>
<script type="text/javascript">
var _menus = {"menus":[
{"menuid":"1","icon":"","menuname":"成绩统计分析",
"menus":[
{"menuid":"11","menuname":"考试列表","icon":"icon-exam","url":"../exam/examList.html"},
]
},
{"menuid":"2","icon":"","menuname":"学生信息管理",
"menus":[
{"menuid":"21","menuname":"学生列表","icon":"icon-user-student","url":"../student/studentList.html"},
]
},
{"menuid":"3","icon":"","menuname":"教师信息管理",
"menus":[
{"menuid":"31","menuname":"教师列表","icon":"icon-user-teacher","url":"../teacher/teacherList.html"},
]
},
{"menuid":"4","icon":"","menuname":"基础信息管理",
"menus":[
{"menuid":"41","menuname":"年级列表","icon":"icon-world","url":"/s/grade?action=page"},
{"menuid":"42","menuname":"班级列表","icon":"icon-house","url":"../class/clazzList.html"},
{"menuid":"43","menuname":"课程列表","icon":"icon-book-open","url":"/s/course?action=page"}
]
},
{"menuid":"5","icon":"","menuname":"系统管理",
"menus":[
{"menuid":"51","menuname":"系统设置","icon":"icon-set","url":"../admin/adminPersonal.html"},
]
}
]};
</script>
</head>
<body class="easyui-layout" style="overflow-y: hidden" scroll="no">
<noscript>
<div style=" position:absolute; z-index:100000; height:2046px;top:0px;left:0px; width:100%; background:white; text-align:center;">
<img src="images/noscript.gif" alt='抱歉,请开启脚本支持!' />
</div>
</noscript>
<div region="north" split="true" border="false" style="overflow: hidden; height: 30px;
background: url(../images/layout-browser-hd-bg.gif) #7f99be repeat-x center 50%;
line-height: 20px;color: #fff; font-family: Verdana, 微软雅黑,黑体">
<span style="float:right; padding-right:20px;" class="head"><span style="color:red; font-weight:bold;">${loginUser.nickname} </span>您好 <a href="SystemServlet?method=LoginOut" id="loginOut">安全退出</a></span>
<span style="padding-left:10px; font-size: 16px; ">学生信息管理系统</span>
</div>
<div region="south" split="true" style="height: 30px; background: #D2E0F2; ">
<div class="footer">Copyright © Power By Mryang</div>
</div>
<div region="west" hide="true" split="true" title="导航菜单" style="width:180px;" id="west">
<div id="nav" class="easyui-accordion" fit="true" border="false">
<!-- 导航内容 -->
</div>
</div>
<div id="mainPanle" region="center" style="background: #eee; overflow-y:hidden">
<div id="tabs" class="easyui-tabs" fit="true" border="false" >
<div title="欢迎使用" style="padding:20px;overflow:hidden; color:red; ">
<p style="font-size: 50px; line-height: 60px; height: 60px;">${si.schoolName}</p>
<p style="font-size: 25px; line-height: 30px; height: 30px;">欢迎使用学生成绩管理系统</p>
<p>开发人员:${si.developer}</p>
<p>开发周期:${si.devTime}</p>
<hr />
<h2>系统环境</h2>
<p>系统环境:${si.osName}</p>
<p>开发工具:${si.devTools}</p>
<p>Java版本:${si.javaVersion}</p>
<p>服务器:${si.tomcatVersion}</p>
<p>数据库:${si.mysqlVersion}</p>
<p>系统采用技术:${si.info}</p>
</div>
</div>
</div>
<iframe width=0 height=0 src="refresh.jsp"></iframe>
</body>
</html>
GradeService.java
package demo.service;
import demo.dao.GradeDao;
import demo.model.GradeDTO;
import java.sql.SQLException;
import java.util.List;
public class GradeService {
GradeDao gradeDao = new GradeDao();
public List<GradeDTO> getAllGrades() {
try {
return gradeDao.getAllGrades();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
GradeDao.java
package demo.dao;
import demo.model.Course;
import demo.model.GradeDTO;
import demo.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class GradeDao {
QueryRunner queryRunner = new QueryRunner(DBUtils.getDs());
public List<GradeDTO> getAllGrades() throws SQLException {
return queryRunner.query("select g.*,c.* from grade g left join grade_course gc on g.`gid`=gc.`gid` left join course c on gc.`cid`=c.`cid` order by g.`gid` ", new ResultSetHandler<List<GradeDTO>>() {
@Override
public List<GradeDTO> handle(ResultSet rs) throws SQLException {
List<GradeDTO> list = new ArrayList<>();
//上一次遍历发年纪id
int lastGid = -1;
GradeDTO gradeDTO = null;
while (rs.next()) {
int gid = rs.getInt("gid");
if (gid == lastGid) {
//说明这一行的年级已经读过了,这个地方只要处理课程id和课程名称
Course c = new Course();
c.setCid(rs.getInt("cid"));
c.setCourseName(rs.getString("courseName"));
gradeDTO.getCourses().add(c);
} else {
//这一行的年级还没读过,这里要处理四列
//说明这里是一个新的年级了
gradeDTO = new GradeDTO();
gradeDTO.setGid(gid);
gradeDTO.setGradeName(rs.getString("gradeName"));
List<Course> courses = new ArrayList<>();
Course c = new Course();
c.setCid(rs.getInt("cid"));
c.setCourseName(rs.getString("courseName"));
courses.add(c);
gradeDTO.setCourses(courses);
list.add(gradeDTO);
}
lastGid = gid;
}
return list;
}
});
}
}