Javaweb项目页面实时显示后台处理结果

http://www.cnblogs.com/dong-xu/p/6701271.html

此博文甚好,项目参照博主代码可实现。

前端页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page isErrorPage="true" %> 
<!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>
<script type="text/javascript" src="../js/jquery-2.1.1.js"></script>
<link rel="stylesheet" type="text/css" href="../css/css.css" />
<style type="text/css">
.loading{
    background-image: url(../img/1352886927_7549.gif);
                width: 35px;
                height: 35px;
                display: inline-block;
                float: left;
                margin-left: 10px;
                margin-right: 6px;
                background-repeat: no-repeat;
                
}  
</style>
</head>

<body>
    <div id="pageAll">
        <label style="color:red">导出数据说明:不支持wps类excel,文件后缀.xls,文件名不能包含汉字;</label><br>
        <label style="color:red">excel中数据格式如下,列名严格按照图片格式书写,列顺序不可变;(只支持excel)</label>
        <div style="width:80%;height:100px;background-image:url('../img/1512521006(1).jpg');display:block;background-repeat: no-repeat;" >
        </div>
        <form action="${pageContext.request.contextPath}/UploadUsingExcelServlet" method="post" enctype="multipart/form-data" id="dataForm">
        上传excel<input type="file" name="file1" id="fileInput">
         <input type="submit" value="提交" id="submit">
        </form>
        
        <div class="page">
        <div class="conShow" id="pro">
        
        </div>
            <div class="conShow" id="res">
            <span>错误信息:</span><br>
            </div>
            
        </div>

    </div>
</body>
 <script type="text/javascript">
   $(function () {
        var form = document.getElementById("dataForm");
        var progress = document.getElementById("pro");
        $("#submit").click(function(event) {
            //阻止默认事件
            event.preventDefault();
            //循环查看状态
            var t = setInterval(function(){
                
                $.ajax({
                    url: '${pageContext.request.contextPath}/ProgressServlet',
                    type: 'POST',
                    dataType: 'text',
                    data: {
                        filename: fileInput.files[0].name,
                    },
                    success: function (responseText) {
                        var data = JSON.parse(responseText);
                        //前台更新进度
                        var jindu="<span class=\"loading\"></span>&nbsp;传输进度:"+data.size+"/"+data.progress;
                        $("#pro").html(jindu);
                       // progress.innerText ="传输进度 :"+data.size+"/"+data.progress;
                       // alert( data.size+"/"+data.progress);
                        var tag="";
                        if(data.errors!=""){
                            tag="<span style=\"color:red\">"+data.errors+"</span><br>";
                            
                            $("#res").append(tag);
                        }
                         
                    },
                    error: function(){
                        console.log("error");
                    }
                });
            }, 100);
            //上传文件
            $.ajax({
                url: '${pageContext.request.contextPath}/UploadUsingExcelServlet',
                type: 'POST',
                dataType: 'text',
                data: new FormData(form),
                processData: false,
                contentType: false,
                success: function (responseText) {
                    //上传完成,清除循环事件
                    clearInterval(t);
                    //将进度更新至100%
                    progress.innerText = "完成!";
                },
                error: function(){
                    console.log("error");
                }
            });
            return false;
        });
    })();
    </script>
</html>

查询进度的servlet

package com.rfx.servlet;

import java.io.IOException;

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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.rfx.util.ProgressSingleton;

/**
 * <p>实时显示进度</p>
 * Servlet implementation class ProgressServlet
 */
@WebServlet("/ProgressServlet")
public class ProgressServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final Log log = LogFactory.getLog(getClass());
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProgressServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            log.info("进度反馈");
            Object size = ProgressSingleton.get("Size");
            Object progress = ProgressSingleton.get("Progress");
            Object errorstr = ProgressSingleton.get("errors");
            errorstr = errorstr == null ? "" : errorstr;
            JSONObject json = new JSONObject();
            json.put("size", size);
            json.put("progress", progress);
            json.put("errors", errorstr);
            ProgressSingleton.remove("errors");//在保证存储的信息是实时错误状态,所以,查询一次,清除一次,只存实时处理结果
            response.getWriter().print(json.toString());
        
    }

}

后台处理中,向单例存储数据。

//错误信息处理,遇到错误信息存储起来
ProgressSingleton.put("errors",map.get("product_num")+" >> "+string2);
//保存数据提条数和当前处理条数 ProgressSingleton.put("Size",list.size()); int count=0; if ("zb".equals(type)) { for (Map<String, String> map : list) { count++; ProgressSingleton.put("Progress",count); JSONObject jsonObject2 = mjService.addShiYongJiLu(map); jsonArray.add(jsonObject2); } //在处理完成的servlet中,清空单例 ProgressSingleton.remove("Size"); ProgressSingleton.remove("Progress"); ProgressSingleton.remove("errors");

 

posted @ 2017-12-06 14:51  王怀霞  阅读(8308)  评论(0编辑  收藏  举报