作業提交系統
阿新 • • 發佈:2018-12-30
大學在班上擔任學習委員,每次收作業都十分麻煩。因此想自己製作一個作業提交系統。
此係統主要功能就是作業提交,簡而言之就是檔案上傳。因為技術不佳,目前只做了個beta版,使用原生的HTML+JS+AJAX+Servlet,資料庫使用mysql。因此美觀度和功能性有待完善,各位大佬輕噴。
1.工作流程
2.資料庫設計
此係統包含兩個實體:課程,實驗。即一個課程對應多個實驗。
course表:
experiment表:
其中,experiment表中的courseid是外來鍵。
3.專案結構
此專案是用STS開發,專案結構如下:
匯入依賴包,包括:檔案上傳,ajax,mysql等
4.程式碼示例
Course類:
package cqut.entity; public class Course { public int CourseID; public String CourseName; public Course() { super(); } public Course(int courseID, String courseName) { super(); CourseID = courseID; CourseName = courseName; }public int getCourseID() { return CourseID; } public void setCourseID(int courseID) { CourseID = courseID; } public String getCourseName() { return CourseName; } public void setCourseName(String courseName) { CourseName = courseName; } }
Experiment類:
package cqut.entity; public class Experiment { public int ExperimentID; public String ExperimentName; public String ExperimentContent; public String EndTime; public int CourseID; public String path; public String coursename; public String getCoursename() { return coursename; } public void setCoursename(String coursename) { this.coursename = coursename; } public Experiment() { super(); } public Experiment(int experimentID, String experimentName, String experimentContent, String endTime, int courseID, String path) { super(); ExperimentID = experimentID; ExperimentName = experimentName; ExperimentContent = experimentContent; EndTime = endTime; CourseID = courseID; this.path = path; } public int getExperimentID() { return ExperimentID; } public void setExperimentID(int experimentID) { ExperimentID = experimentID; } public String getExperimentName() { return ExperimentName; } public void setExperimentName(String experimentName) { ExperimentName = experimentName; } public String getExperimentContent() { return ExperimentContent; } public void setExperimentContent(String experimentContent) { ExperimentContent = experimentContent; } public String getEndTime() { return EndTime; } public void setEndTime(String endTime) { EndTime = endTime; } public int getCourseID() { return CourseID; } public void setCourseID(int courseID) { CourseID = courseID; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
首頁Home.html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>作業提交</title> <link rel="stylesheet" href="css/h_style.css" type="text/css"> <script type="text/javascript" src="jquery-3.3.1.min.js"></script> <script type="text/javascript" src="js/h_js.js"></script> <script type="text/javascript"> $().ready(function () { $.ajax({ type: "GET", url: "servlet/CourseServlet", data: { }, beforeSend: function () { }, success: function (data) { var json = JSON.parse(data); for(var j in json) { var ul=document.getElementById("h_course"); var li=document.createElement("li"); ul.appendChild(li); var a=document.createElement("a"); li.appendChild(a); var div=document.createElement("div"); div.setAttribute("class","course"); div.setAttribute("id",json[j].CourseID); div.setAttribute("onclick","Experiment('"+json[j].CourseID+"')"); a.appendChild(div); var h2=document.createElement("h2"); h2.innerHTML=json[j].CourseName; div.appendChild(h2); } }, complete: function (XMLHttpRequest, textStatus) { }, error: function (XMLHttpRequest, textStatus, thrownError) { } }); }); function Experiment(id,name){ window.location.href="Experiment.html?id="+id; }; </script> </head> <body> <div class="container"> <div class="h_head"> <h1>軟體工程2班專屬作業提交系統 beta2</h1> </div> <div id="h_body"> <ul id="h_course"> </ul> <div class="left" onclick="a()"></div> <div class="right"></div> </div> </div> </body> </html>
實驗內容頁面 Experiment.html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>作業提交</title> <link rel="stylesheet" href="css/h_style.css" type="text/css"> <script type="text/javascript" src="jquery-3.3.1.min.js"></script> <script type="text/javascript" src="js/h_js.js"></script> <script type="text/javascript"> $().ready(function(){ $.ajax({ type: "POST", url: "servlet/CourseServlet", data: { courseid:getQueryVariable("id") }, beforeSend: function () { }, success: function (data) { var json = JSON.parse(data); var i=0; for(var j in json){ var id_h1=document.getElementById("id_h1"); id_h1.innerHTML=json[j].coursename; var ul=document.getElementById("h_test_list"); var li=document.createElement("li"); ul.appendChild(li); var item_body=document.createElement("div"); item_body.setAttribute("class","item_body"); li.appendChild(item_body); var item_title=document.createElement("div"); item_title.setAttribute("class","item_title"); item_body.appendChild(item_title); var h2=document.createElement("h2"); item_title.appendChild(h2); h2.innerHTML=json[j].ExperimentName; var item_content=document.createElement("div"); item_content.setAttribute("class","item_content"); item_body.appendChild(item_content); var h3=document.createElement("h3"); item_content.appendChild(h3); h3.innerHTML=json[j].ExperimentContent; var item_endtime=document.createElement("div"); item_endtime.setAttribute("class","item_endtime"); item_endtime.innerHTML="截止時間:"+json[j].EndTime; item_body.appendChild(item_endtime); var item_count=document.createElement("div"); item_count.setAttribute("class","item_count"); item_count.innerHTML="已提交人數:5人"; item_body.appendChild(item_count); var uploadForm=document.createElement("form"); uploadForm.setAttribute("id","uploadForm"); uploadForm.setAttribute("method","POST"); item_body.appendChild(uploadForm); var show=document.createElement("div"); show.setAttribute("class","show"); show.setAttribute("id","show"+i); show.innerHTML="請點選上傳檔案:"; uploadForm.appendChild(show); var blueButton=document.createElement("a"); blueButton.setAttribute("class","blueButton"); blueButton.setAttribute("href","javascript:void(0);"); blueButton.innerHTML="上傳檔案"; uploadForm.appendChild(blueButton); var myFileUpload=document.createElement("input"); myFileUpload.setAttribute("type","file"); myFileUpload.setAttribute("id","fileid"); myFileUpload.setAttribute("class","myFileUpload"); myFileUpload.setAttribute("onchange","c(this,"+i+")"); uploadForm.appendChild(myFileUpload); var whiteButton=document.createElement("a"); whiteButton.setAttribute("class","whiteButton"); whiteButton.setAttribute("href","javascript:void(0);"); whiteButton.innerHTML="提交"; uploadForm.appendChild(whiteButton); var mySubmit=document.createElement("input"); mySubmit.setAttribute("type","button"); mySubmit.setAttribute("onclick","onfile($('#fileid'))"); mySubmit.setAttribute("class","mySubmit"); uploadForm.appendChild(mySubmit); i++; } }, complete: function (XMLHttpRequest, textStatus) { }, error: function (XMLHttpRequest, textStatus, thrownError) { } }); }); function getQueryVariable(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); if(pair[0] == variable){return pair[1];} } return(false); } function c(data,i){ var arrs=$(data).val().split('\\'); var filename=arrs[arrs.length-1]; $("#show"+i).html(filename); } </script> </head> <body> <div class="container"> <div class="h_head"> <h1 id="id_h1"></h1> </div> <div class="h_test"> <ul id="h_test_list"> </ul> </div> </div> </body> </html>
檔案提交h_js.js:
{var xhr; function onfile(file) { var fd = new FormData(); fd.append("fileToUpload", document.getElementById('fileid').files[0]); xhr = new XMLHttpRequest(); xhr.open("POST", "servlet/UploadServlet"); //xhr.setRequestHeader("Content-Type","charset=UTF-8"); xhr.send(fd); xhr.onreadystatechange = processResponse; } function processResponse(){ if(xhr.readyState == 4){ //alert("upload data liu stop"); if(xhr.status == 200){ var infor = xhr.responseText; alert(infor); $("input[type=reset]").trigger("click"); } } } }
後臺檔案提交 UploadServlet:
package cqut.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class UploadServlet */ public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UploadServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳檔案的安全 String inputPath = "D:\\test"; File file = new File(inputPath); System.out.println("test。。。。"); // 判斷上傳檔案的儲存目錄是否存在 if (!file.exists() && !file.isDirectory()) { System.out.println(inputPath + "目錄不存在,需要建立"); // 建立目錄 file.mkdir(); } String filename = ""; // 訊息提示 String message = ""; try { // 使用Apache檔案上傳元件處理檔案上傳步驟: // 1、建立一個DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 2、建立一個檔案上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); // 解決上傳檔名的中文亂碼 upload.setHeaderEncoding("UTF-8"); // 3、判斷提交上來的資料是否是上傳表單的資料 if (!ServletFileUpload.isMultipartContent(request)) { // 按照傳統方式獲取資料 return; } // 4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> list = upload.parseRequest(request); for (FileItem item : list) { // 如果fileitem中封裝的是普通輸入項的資料 if (item.isFormField()) { String name = item.getFieldName(); // 解決普通輸入項的資料的中文亂碼問題 String value = item.getString("UTF-8"); // value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); } else {// 如果fileitem中封裝的是上傳檔案 // 得到上傳的檔名稱, filename = item.getName(); System.out.println(filename); if (filename == null || filename.trim().equals("")) { message = "上傳失敗[檔名空]"; continue; } // 注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,如: // c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt // 處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分 filename = filename .substring(filename.lastIndexOf("/") + 1); // 獲取item中的上傳檔案的輸入流 InputStream in = item.getInputStream(); // 建立一個檔案輸出流 FileOutputStream out = new FileOutputStream(inputPath + "/" + filename); // 建立一個緩衝區 byte buffer[] = new byte[1024 * 1024]; // 判斷輸入流中的資料是否已經讀完的標識 int len = 0; // 迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料 while ((len = in.read(buffer)) > 0) { // 使用FileOutputStream輸出流將緩衝區的資料寫入到指定的目錄(savePath + "\\" // + filename)當中 out.write(buffer, 0, len); } out.flush(); // 關閉輸入流 in.close(); // 關閉輸出流 out.close(); // 刪除處理檔案上傳時生成的臨時檔案 item.delete(); message = "檔案上傳成功!"; } } } catch (Exception e) { message = "檔案上傳失敗!"; e.printStackTrace(); } /*request.setAttribute("message", message); request.getRequestDispatcher("/message.jsp").forward(request, response);*/ response.setCharacterEncoding("UTF-8"); response.getWriter().print(message); } }
資料庫查詢 CourseServlet:
package cqut.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.DriverManager; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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 com.fasterxml.jackson.databind.ObjectMapper; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import cqut.entity.Course; import cqut.entity.Experiment; /** * Servlet implementation class SqlServlet */ @WebServlet("/SqlServlet") public class CourseServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CourseServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); Connection connection=null; Statement statement=null; ResultSet resultset=null; try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/homework"; connection=(Connection) DriverManager.getConnection(url, "root", "123"); statement=(Statement) connection.createStatement(); resultset=statement.executeQuery("select * from course"); List<Course> courses=new ArrayList<>(); while(resultset.next()) { Course course=new Course(); course.CourseID=resultset.getInt("CourseID"); course.CourseName=resultset.getString("CourseName"); System.out.println(course.CourseID+" "+course.CourseName); courses.add(course); } ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(courses); PrintWriter out =response.getWriter(); out.write(json); }catch (Exception e) { // TODO: handle exception } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String courseid=request.getParameter("courseid"); System.out.println(courseid); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); Connection connection=null; Statement statement=null; ResultSet resultset=null; try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/homework"; connection=(Connection) DriverManager.getConnection(url, "root", "123"); statement=(Statement) connection.createStatement(); resultset=statement.executeQuery("SELECT * from c_e where courseid="+courseid); List<Experiment> experiments=new ArrayList<>(); while(resultset.next()) { Experiment ex=new Experiment(); ex.ExperimentID=resultset.getInt("ExperimentID"); ex.ExperimentName=resultset.getString("ExperimentName"); ex.ExperimentContent=resultset.getString("ExperimentContent"); ex.CourseID=resultset.getInt("CourseID"); ex.EndTime=resultset.getString("EndTime"); ex.path=resultset.getString("path"); ex.coursename=resultset.getString("CourseName"); System.out.println(ex.ExperimentName+""+ex.coursename); experiments.add(ex); } ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(experiments); PrintWriter out =response.getWriter(); out.write(json); }catch (Exception e) { // TODO: handle exception } } }
另外,建立servlet後,需要在web.xml中新增對映
<?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/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>cqut.cn.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/servlet/UploadServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>CourseServlet</servlet-name> <servlet-class>cqut.servlet.CourseServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CourseServlet</servlet-name> <url-pattern>/servlet/CourseServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>ExperimentServlet</servlet-name> <servlet-class>cqut.servlet.ExperimentServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ExperimentServlet</servlet-name> <url-pattern>/servlet/ExperimentServlet</url-pattern> </servlet-mapping> </web-app>
5.效果展示