简体   繁体   English

在Java servlet doPost方法中启动线程,无法返回异常消息

[英]Starting a thread in a java servlet doPost method, cant return back exception messages

I'm making a web application to use the JAVE library online ( http://www.sauronsoftware.it/projects/jave/ ): 我正在制作一个Web应用程序以在线使用JAVE库( http://www.sauronsoftware.it/projects/jave/ ):

  • The user fills the form 用户填写表格
  • uploads the video 上传视频
  • the video is converted by the server 视频由服务器转换
  • the user downloads the video 用户下载视频

The interface is a jsp page with form, an upload progress bar (made with http://malsup.com/jquery/form/#download ) and a progress bar made in JS that starts ajax polling on a progress servlet (after the upload progress is complete). 该界面是一个带表单的jsp页面,一个上传进度条(由http://malsup.com/jquery/form/#download制作 )和一个JS进度条,可在进度servlet上启动ajax轮询(上传后)进度完成)。 The progress servlet takes the encoderListener from HttpSession that gives the % value of the encoding progress. 进度小服务程序从HttpSession中获取encoder侦听器,该监听器给出了编码进度的%值。 I'm having troubles with the conversion task because it blocks the doPost method of the servlets that handles the form. 我在转换任务上遇到麻烦,因为它阻止了处理表单的servlet的doPost方法。 So the user never receives the response that put the JS snippet of the progress bars in the complete state to start the ajax-polling. 因此,用户永远不会收到将进度条的JS代码段置于完整状态以启动Ajax轮询的响应。 I thought to put it in a thread so the doPost method returns while the conversion is going and the JS script keeps track of it through the ProgressServlet. 我想将其放在线程中,以便doPost方法在转换进行时返回,并且JS脚本通过ProgressServlet对其进行跟踪。 Now the problem is that I cannot print the exception message back to the user anymore. 现在的问题是我无法再将异常消息打印回用户。 What can I do? 我能做什么? Here some code: 这里有一些代码:

The Converter class just executes the enc.encode(...) method in a try/catch. Converter类仅在try / catch中执行enc.encode(...)方法。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    Part part = request.getPart("filename");
    InputStream inStream = part.getInputStream();
    String fileName = part.getSubmittedFileName();
    //upload path
    File uploads = new File(System.getProperty("user.home")+System.getProperty("file.separator"));
    File file = new File(uploads,fileName);
    OutputStream outStream = new FileOutputStream(file);
    byte[] buffer = new byte[8 * 1024];
    int bytesRead;
    while ((bytesRead = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }
    outStream.close();
    PrintWriter writer = response.getWriter();
    response.setContentType("text/html");
    writer.println("File uploaded");        

    AudioAttributes audio = new AudioAttributes();
    VideoAttributes video = new VideoAttributes();
    EncodingAttributes attrs = new EncodingAttributes();
    Encoder enc = new Encoder();
    EncoderListener elist = new EncoderListener();      
    HttpSession session = request.getSession();
    session.setAttribute("listener", elist);

    File target = new File(System.getProperty("user.home")+System.getProperty("file.separator"),request.getParameter("outFile"));

    attrs.setFormat(request.getParameter("formats"));

    setAttributes(request,audio,video);

    attrs.setVideoAttributes(video);
    attrs.setAudioAttributes(audio);

    //long running task
    Converter conv = new Converter(file,target,enc,elist,attrs);
    Thread t = new Thread(conv);
    t.start();      

}

This is the snippet that handles the upload progress bar, and the conversion progress bar. 这是处理上传进度栏和转换进度栏的代码段。

 <script> $(function() { var bar = $("#bar"); var percent = $("#percent"); var status = $('#status'); $('form').ajaxForm({ beforeSend: function() { status.empty(); var percentVal = '0%'; bar.width(percentVal); percent.html(percentVal); $("#ConversionBar").width(percentVal); $("#ConversionPercent").html(percentVal); }, uploadProgress: function(event, position, total, percentComplete) { var percentVal = percentComplete + '%'; bar.width(percentVal); percent.html(percentVal); }, complete: function(xhr) { status.html(xhr.responseText); var IntervalID = setInterval(function(){ $.get("/ElaboratoAT/ProgressServlet",function(data,status){ $("#ConversionBar").width(data/10+'%'); $("#ConversionPercent").html(data/10+'%'); if( data/10 >= 100) clearInterval(IntervalID); $("#download").show(); }) },100); } }); }); </script> 
This is the servlet that gives the progress. 这是提供进度的servlet。

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession session = request.getSession(); response.setContentType("text/html"); EncoderListener elist = (EncoderListener)session.getAttribute("listener"); response.getWriter().println(elist.getProgress()); } 

Thank you for your help and time. 感谢您的帮助和时间。

Starting new thread for each request is not a good solution. 为每个请求启动新线程不是一个好的解决方案。 There is a limit for threads application can start. 线程应用程序可以启动有一个限制。 It will eventually run out of resources. 最终将耗尽资源。

To perform long running tasks you need asynchronous servlet. 要执行长时间运行的任务,您需要异步servlet。 Solutions: 解决方案:

  1. Write your own realization using thread pools in servlet and executing tasks within it. 使用Servlet中的线程池并在其中执行任务来编写自己的实现。
  2. Use existing solution like Asynchronous processing . 使用现有解决方案,例如异步处理

Here is code examples. 这是代码示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM