作业提交系统

大学在班上担任学习委员,每次收作业都十分麻烦。因此想自己制作一个作业提交系统。

此系统主要功能就是作业提交,简而言之就是文件上传。因为技术不佳,目前只做了个beta版,使用原生的HTML+JS+AJAX+Servlet,数据库使用mysql。因此美观度和功能性有待完善,各位大佬轻喷。

1.工作流程

作业提交系统_第1张图片

2.数据库设计

此系统包含两个实体:课程,实验。即一个课程对应多个实验。

course表:

experiment表:

作业提交系统_第2张图片

其中,experiment表中的courseid是外键。

 

 3.项目结构


此项目是用STS开发,项目结构如下:

作业提交系统_第3张图片

导入依赖包,包括:文件上传,ajax,mysql等

作业提交系统_第4张图片

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班专属作业提交系统 beta2h1>
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对应一个Form表单的输入项
            List 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 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 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>UploadServletservlet-name>
    <servlet-class>cqut.cn.UploadServletservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>UploadServletservlet-name>
    <url-pattern>/servlet/UploadServleturl-pattern>
  servlet-mapping>
  <servlet>
    <servlet-name>CourseServletservlet-name>
    <servlet-class>cqut.servlet.CourseServletservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>CourseServletservlet-name>
    <url-pattern>/servlet/CourseServleturl-pattern>
  servlet-mapping>
   <servlet>
    <servlet-name>ExperimentServletservlet-name>
    <servlet-class>cqut.servlet.ExperimentServletservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>ExperimentServletservlet-name>
    <url-pattern>/servlet/ExperimentServleturl-pattern>
  servlet-mapping>
web-app>

5.效果展示

 

转载于:https://www.cnblogs.com/luoyijian/p/10200741.html

你可能感兴趣的:(作业提交系统)