一、前言
本次作業總體使用了ssm(spring+springmvc+mybatis)框架,使用的IDE工具爲IntelliJ IDEA,並且使用Maven進行整體開發,數據庫使用的是SQL Server 2008 r2。前端是基於bootstrap框架進行開發,實現的主要功能有:
- 顯示已錄入成績列表;
- 新增學生成績信息(錄入學生標識、課程標識和成績);
- 修改學生成績信息(僅允許修改成績)
- 刪除學生成績信息
- 學生成績合計功能(所有學生所有課程的總成績和平均成績)
- 分頁顯示學生成績
- 按學生統計學生的總成績和平均成績
- 分別按專業、年級、學號、姓名、科目查詢學生成績信息
頁面概覽
二、文件目錄
三、主要Java類設計
3.1 studentController類
@Controller
public class studentController {
@Autowired
private IstudentService istudentService;
@RequestMapping(value = "index")
public String index(){
return "index";
}
//從數據庫中加載數據
@RequestMapping(value = "/student",method = RequestMethod.POST)
@ResponseBody
public JSONObject showStudentALL(HttpServletRequest request){
List<studentAllAttr> listStudent = istudentService.findStudentAllAttr();
JSONObject stujson = new JSONObject();
System.out.println(request.getParameter("pageIndex"));
int rows = Integer.parseInt(request.getParameter("pageSize"));//每一頁的最大記錄數
int page = Integer.parseInt(request.getParameter("pageIndex"));//頁碼
//System.out.print(page+" "+rows);
int PageIndexbegin = (page-1)*rows;//每一頁起始點位置
int PageIndexend = PageIndexbegin+rows>listStudent.size()-1?listStudent.size():PageIndexbegin+rows;
stujson.put("total",listStudent.size());
stujson.put("rows",listStudent.subList(PageIndexbegin,PageIndexend));//一頁的條數
System.out.println(stujson.toString());
return stujson;
}
//通過學號查找學生姓名
@RequestMapping(value = "/searchstuName",method = RequestMethod.POST)
@ResponseBody
public JSONObject searchstuName(HttpServletRequest request, HttpServletResponse response){
response.setContentType("text/html;charset=utf-8"); //當然如果是json數據,需要設置爲("text/javascript;charset=utf-8");
response.setCharacterEncoding("utf-8");
String stuNo = request.getParameter("stuNo");
System.out.println(stuNo);
String stuName = istudentService.searchName(Integer.parseInt(stuNo));
System.out.println(stuName);
JSONObject stuNamejson = new JSONObject();
stuNamejson.put("stuName",stuName);
return stuNamejson;
}
//添加成績信息
@RequestMapping(value = "/addscore",method = RequestMethod.POST)
@ResponseBody //@RequestBody轉換接受的JSON爲對象,用@ResponseBody轉換返回的對象爲JSON。有兩種接受前端數據的方式,一種使用Map接受,一種使用實體類進行接收
public String addscore(@RequestBody Map<String, String> addmap){
int stuNo = Integer.parseInt(addmap.get("studentNo"));//獲取學號,並進行類型轉換
//System.out.println(addmap.get("subjectName"));
int stuId = istudentService.searchStuId(stuNo);//通過學號獲取學生id
int subId = istudentService.searchId(addmap.get("subjectName"));//通過課程名獲取課程id
float stuscore = Float.parseFloat(addmap.get("stuscore"));//獲取學生成績
System.out.println(stuNo+" "+subId+" "+stuscore+" ");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
System.out.println(addmap.get("addtime"));
Date modifytime = sdf.parse(addmap.get("addtime"));
int hasfoundinScore = istudentService.searchalex(subId,stuId);//查找該學生課程信息,
System.out.println(hasfoundinScore);
//如果該條記錄存在就更新數據庫
if(hasfoundinScore!=0){
istudentService.updateScore(hasfoundinScore,subId,stuId,stuscore,new Date());
return "更新成功";
}//不存在就插入
else{
int isadd = 0;
isadd = istudentService.addScore(subId,stuId,stuscore,new Date());
if(isadd!=0)
return "新增成功";
else
return "新增失敗";
}
}catch (ParseException e){
e.printStackTrace();
return "失敗";
}
}
//刪除學生成績信息
@RequestMapping(value = "/delet",method = RequestMethod.POST)
@ResponseBody
public String delet(@RequestBody Map<String, String> deletemap){
int stuid = istudentService.searchStuId(Integer.parseInt(deletemap.get("stuNo")));//根據學號找stuid
int subid = istudentService.searchId(deletemap.get("subname"));//根據課程名找subid
int scoreid = istudentService.searchalex(subid,stuid);//查找是否存在該成績信息記錄
System.out.println(scoreid);
if(scoreid!=0) {
istudentService.delScore(scoreid);//存在即刪除
return "del ok";
}
return "del false";
}
//根據學號獲得學生總成績
@RequestMapping(value="/getGradeSum",method = RequestMethod.POST)
@ResponseBody
public String getGradeSum(HttpServletRequest request){
System.out.println(request.getParameter("sumno")+"");
int stuNo = Integer.parseInt(request.getParameter("sumno"));
int stuId = istudentService.searchStuId(stuNo);
System.out.println(stuId+"getsum");
float scoresum = istudentService.getGradeSum(stuId);
return scoresum+"";
}
//獲取所有學生總成績
@RequestMapping(value = "/getAllGradeSum",method = RequestMethod.POST)
@ResponseBody
public String getAllGradeSum(){
return istudentService.getAllGradeSum()+"";
}
//根據學號獲得學生平均成績
@RequestMapping(value="/getGradeAvg",method = RequestMethod.POST)
@ResponseBody
public String getGradeAvg(HttpServletRequest request){
System.out.println(request.getParameter("avgno")+"");
int stuNo = Integer.parseInt(request.getParameter("avgno"));
int stuId = istudentService.searchStuId(stuNo);
System.out.println(stuId+"getsum");
float scoreavg = istudentService.getGradeAvg(stuId);
return scoreavg+"";
}
//獲得所有學生平均成績
@RequestMapping(value = "/getAllGradeAvg",method = RequestMethod.POST)
@ResponseBody
public String getAllGradeAvg(){
return istudentService.getAllGradeAvg()+"";
}
}
3.2 ScoreMapper類
package zzx.mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import zzx.entity.score;
import java.util.Date;
import java.util.List;
@Repository
public interface ScoreMapper {
public List<score> findstuScore(@Param("stuid") int stuid,@Param("subid") int subid);
public List<score> findAllScore();
//查找某學生成績信息是否已經存在 already exist 返回已存在記錄ID
public int searchalex(@Param("subId")int subId,@Param("stuId") int stuId);
//添加成績信息
public int addScore(@Param("subjectId") int subjectId, @Param("studentId") int studentId, @Param("studentScore") float studentScore, @Param("motime") Date modifyTime);
//更新成績信息
public void updateScore(@Param("scoreId") int scoreId,@Param("subjectId") int subjectId, @Param("studentId") int studentId, @Param("studentScore") float studentScore, @Param("motime") Date modifyTime);
//刪除成績信息
public void delScore(@Param("scoreId") int scoreId);
//獲取某學生的總成績
public Float getGradeSum(@Param("sumNo") int sumNo);
//獲取所有學生總成績
public Float getAllGradeSum();
//獲取學生平均成績
public Float getGradeAvg(@Param("avgno") int avgno);
//獲取所有學生平均成績
public Float getAllGradeAvg();
}
3.3 IstudentServiceImpl類
@Service
@Transactional
public class IstudentServiceImpl implements IstudentService {
@Resource
private StudentMapper studentMapper;
@Resource
private SubjectMapper subjectMapper;
@Resource
private ScoreMapper scoreMapper;
@Override
public List<student> findAllStudent(){
return studentMapper.findAllStudent();
}
@Override
public List<studentAllAttr> findStudentAllAttr() {
return studentMapper.findStudentAllAttr();
}
@Override
public String searchName(int stuNo){System.out.println(stuNo);return studentMapper.searchName(stuNo);}
@Override
public int searchStuId(int stuNo){return studentMapper.searchStuId(stuNo);}
public StudentMapper getSdao(){
return studentMapper;
}
public void setSdao(StudentMapper studentMapper){
this.studentMapper = studentMapper;
}
@Override
public List<subject> findstubject(int subid){return subjectMapper.findstubject(subid);}
@Override
public List<subject> findAllsub(){return subjectMapper.findAllsub();}
@Override
public int searchId(String subname){System.out.println(subjectMapper.searchId(subname));return subjectMapper.searchId(subname);}
public SubjectMapper getSubjectMapper() {
return subjectMapper;
}
public void setSubjectMapper(SubjectMapper subjectMapper) {
this.subjectMapper = subjectMapper;
}
@Override
public List<score> findAllScore() {
return null;
}
@Override
public List<score> findstuScore(int subint, int stuid) {
return null;
}
@Override
public int addScore(int subjectId, int studentId, float studentScore, Date modifyTime){return scoreMapper.addScore(subjectId,studentId,studentScore,modifyTime);};
@Override
public int searchalex(int subId,int stuId){return scoreMapper.searchalex(subId,stuId);}
@Override
public void updateScore(int soreId,int subjectId, int studentId, float studentScore,Date modifyTime){
//Date now = new Date();
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
scoreMapper.updateScore(soreId,subjectId,studentId,studentScore,modifyTime);
}
@Override
public float getGradeSum(int sumNo){return scoreMapper.getGradeSum(sumNo);}
@Override
public Float getAllGradeSum(){return scoreMapper.getAllGradeSum();}
@Override
public Float getGradeAvg(int avgno){return scoreMapper.getGradeAvg(avgno);}
@Override
public Float getAllGradeAvg(){return scoreMapper.getAllGradeAvg();}
public void delScore(int scoreId){scoreMapper.delScore(scoreId);}
public ScoreMapper getScoreMapper() {
return scoreMapper;
}
public void setScoreMapper(ScoreMapper scoreMapper) {
this.scoreMapper = scoreMapper;
}
}
3.4 scoremapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="zzx.mapper.ScoreMapper">
<select id="findstuScore" parameterType="int" resultType="score">
select * from ScoreInfo where subjectId=#{subid} and studentId=#{stuid};
</select>
<select id="findAllScore">
select * from ScoreInfo;
</select>
<insert id="addScore" >
insert into ScoreInfo(subjectId,studentId,studentScore,modifyTime) values (#{subjectId},#{studentId},#{studentScore},#{motime})
<selectKey resultType="java.lang.Integer" keyProperty="id" >
SELECT @@IDENTITY AS ID
</selectKey>
</insert>
<select id="searchalex" resultType="java.lang.Integer">
select ISNULL(MAX(scoreId),0) from ScoreInfo where subjectId = #{subId} and studentId = #{stuId}
</select>
<update id="updateScore">
update ScoreInfo <trim prefix="set" suffixOverrides=",">
<if test="subjectId!=null">subjectId=#{subjectId},</if>
<if test="studentId!=null">studentId=#{studentId},</if>
<if test="studentScore!=null">studentScore=#{studentScore},</if>
<if test="motime!=null">modifyTime=#{motime},</if>
</trim>
where scoreId = #{scoreId}
</update>
<delete id="delScore">
delete from ScoreInfo where scoreId = #{scoreId}
</delete>
<select id="getGradeSum" resultType="java.lang.Float">
select sum(studentScore) from ScoreInfo where studentId = #{sumNo}
</select>
<select id="getAllGradeSum" resultType="java.lang.Float">
select sum(studentScore) from ScoreInfo
</select>
<select id="getGradeAvg" resultType="java.lang.Float">
select avg(studentScore) from ScoreInfo where studentId = #{avgno}
</select>
<select id="getAllGradeAvg" resultType="java.lang.Float">
select avg(studentScore) from ScoreInfo
</select>
</mapper>
四、主要網頁設計
4.1 表格設計
引用了bootstrapTable插件
4.1.1 表格HTML元素部分
<div id="gradetable">
<table class="table" id="stutable"></table>
</div>
4.1.2 表格JavaScript初始化
$(function () {
//1.初始化Table
var oTable = new TableInit();
oTable.Init();
//2.初始化Button的點擊事件
var oButtonInit = new ButtonInit();
oButtonInit.Init();
});
function tableHeight(){
//可以根據自己頁面情況進行調整
return $(window).height() -280;
}
var TableInit = function () {
var oTableInit = new Object();
//初始化Table
oTableInit.Init = function () {
$('#stutable').bootstrapTable({
method: 'post',
contentType: "application/x-www-form-urlencoded",//必須要有!!!!
url:"/student",//要請求數據的文件路徑
toolbar: '#toolbar',//指定工具欄
striped: true, //是否顯示行間隔色
height:tableHeight(),//高度調整
dataType:"json",//bootstrap table 可以前端分頁也可以後端分頁,這裏
//我們使用的是後端分頁,後端分頁時需返回含有total:總記錄數,這個鍵值好像是固定的
//rows: 記錄集合 鍵值可以修改 dataField 自己定義成自己想要的就好
smartDisplay:false,
pageNumber: 1, //初始化加載第一頁,默認第一頁
pagination:true,//是否分頁
queryParams:oTableInit.queryParams,//請求服務器時所傳的參數
sidePagination:'server',//指定服務器端分頁
pageSize:10,//單頁記錄數
pageList:[3,10,20,30],//分頁步進值
showRefresh:true,//刷新按鈕
showColumns:true,
clickToSelect: true,//是否啓用點擊選中行
toolbarAlign:'right',//工具欄對齊方式
buttonsAlign:'right',//按鈕對齊方式
toolbar:'#toolbar',//指定工作欄
columns: [{
checkbox: true
}, {
field: 'specialty',
title: '專業'
}, {
field: 'grade',
title: '年級'
}, {
field: 'studentNo',
title: '學號'
}, {
field: 'studentname',
title: '姓名'
}, {
field: 'studentsex',
title: '性別'
}, {
field: 'subjectName',
title: '科目'
}, {
field: 'studentScore',
title: '成績'
}, {
field: 'peration',
title: '操作',
width: 120,
align: 'center',
valign: 'middle',
formatter: actionFormatter
},
],
locale:'zh-CN',//中文支持,
responseHandler: function (res) {
//如果沒有錯誤則返回數據,渲染表格
console.log(res);
return res;
},
});
//操作欄的格式化
function actionFormatter(value, row, index) {
var id = value;
var result = "";
result += "<a href='javascript:;' onclick=\"modify(this)\" title='編輯'><span class='glyphicon glyphicon-pencil'>編輯</span></a>";
result += "<a href='javascript:;' onclick=\"deleteing(this)\" title='刪除'><span class='glyphicon glyphicon-remove'>刪除</span></a>";
return result;
}
};
//得到查詢的參數
oTableInit.queryParams = function (params) {
var temp = { //這裏的鍵的名字和控制器的變量名必須一直,這邊改動,控制器也需要改成一樣的
//每頁多少條數據
pageSize: params.limit,
//請求第幾頁
pageIndex:params.pageNumber,
//searchtext: $("#search_text").val(),
//searchkey: $(".search").text()
};
return temp;
};
return oTableInit;
};
var ButtonInit = function () {
var oInit = new Object();
var postdata = {};
oInit.Init = function () {
//初始化頁面上面的按鈕事件
};
return oInit;
};
4.2 表單部分
4.2.1 HTML元素部分
4.2.2 JavaScript事件處理
1、關於submit
這裏表單的提交按鈕控制兩個事件,一個是新增,一個是遞交修改,在提交之前會先調用後臺searchstuName方法查找該學生是否存在,如果存在,使用ajax向後臺addscore發送請求,addscore先判定該條記錄是否存在,如果存在則進行更新操作如果不存在則進行新增操作
function searchName(obj) {
var stuNo = $(obj).val();
if(stuNo!=null){
$.ajax({
url:"/searchstuName",//通過學號查找姓名,如果存在姓名自動出現在輸入框,否則新增
type:"post",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data:{stuNo:stuNo},
dataType:"json",//預期獲取的數據格式
success:function (data) {
console.log(data.stuName);
var stuname = data.stuName;
if(stuname!=null) {
$("#name").val(stuname);
isstuex = 1;
}
else {
$("#name").attr("placeholder","該用戶不存在");
isstuex = 0;
}
}
})
}
}
$("#submit1").click(function () {
var ischecked = checkform()
var adddata = {};
adddata["studentNo"] = $("#sno").val();
adddata["subjectName"] = $("input:radio[name='optionsRadiosinline2']:checked").val();
adddata["stuscore"] = $("#grade").val();
adddata["scoreId"] = formid;
var nowtime = new Date();
adddata["addtime"] = nowtime.toLocaleDateString();
console.log(adddata["studentNo"]);
console.log(adddata["subjectName"]);
console.log(adddata["addtime"]);
console.log(isstuex)
//添加操作
//學生存在。新增score表
if (isstuex == 1&&ischecked) {
console.log("addnewScore")
$.ajax({
url: "/addscore",
type: "post",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(adddata),
dataType: "text",//預期獲取的數據格式
success: function (data) {
console.log(data);
$("button[name='refresh']").trigger("click");
//window.location.reload();
if(submitflag==1)
alert("新增成功");
if(submitflag==2)
alert("修改成功");
}
})
}
if(isstuex==0){
//searchName(document.getElementById("name"));
alert("該用戶不存在");
}
})
2、關於delete
//刪除
function deleteing(obj){
var ttr = $(obj).parent().parent();
var ttd = ttr.children()
var deldata = {};
deldata["stuNo"] = ttd[3].innerHTML;
deldata["subname"] = ttd[6].innerHTML;
if(confirm("確認刪除?")){
$.ajax({
url: "/delet",
type: "post",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(deldata),
dataType: "text",//預期獲取的數據格式
success: function (data) {
console.log(data);
$("button[name='refresh']").trigger("click");//表格刷新
}
})
}
}
3、關於獲取學生總成績與平均成績
使用getGradeSum()來獲取學生總成績,getavgGrade()來獲取學生平均成績,當用戶輸入學生學號爲空時則統計所有學生總成績,否則則統計特定學生總成績,求平均成績同理
function getGradeSum() {
var sumNo = prompt("請輸入學生學號,不輸入即求所有學生總成績 ");
console.log(sumNo);
if(sumNo==''){
$.ajax({
url: "/getAllGradeSum",
type: "post",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "text",//預期獲取的數據格式
success: function (data) {
alert("所有學生總成績爲"+data);
},
error:function () {
console.log(sumNo);
}
})
}
else {
//先查找學生是否存在
$.ajax({
url:"/searchstuName",//通過學號查找姓名,如果存在姓名自動出現在輸入框,否則新增
type:"post",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data:{stuNo:sumNo},
dataType:"json",//預期獲取的數據格式
success:function (data) {
console.log(data.stuName);
var stuname = data.stuName;
if(stuname!=null) {
isstuex = 1;
//學生存在,獲取總成績
$.ajax({
url: "/getGradeSum",
type: "post",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: {sumno: sumNo},
dataType: "text",//預期獲取的數據格式
success: function (data) {
alert("該學生總成績爲" + data);
},
error: function () {
console.log(sumNo);
}
});
}
else {
alert("該用戶不存在");
isstuex = 0;
}
}
})
}
}
如下爲源碼地址:
GitHub源碼