2014-10-11 59 views
0

我正在使用JSP和SERVLET開發WEB PROJECT。如何在ajax之後獲取新的請求對象

我想上傳使用AJAX調用的文件。 文件已成功上傳。 但是,雖然ajax稱爲控制器(servlet文件)向jsp文件發送請求和響應對象。

JSP文件

$(document).ready(function(){ 
    $(':file').change(function(){ 
      var fileObj = this.files[0]; 
       var form = $('#mOBJ'); 
       var fd = new FormData();  
       fd.append('file', fileObj); 
       $.ajax({ 
        url:form.attr('action'), 
        type:form.attr('method'), 
        data:fd, 
        processData: false, 
        contentType: false, 
        async:false, 

       }).done(function(){ 
        alert('ajax complete'); 

///////////////////////////////// /////////////////////////////// 在這裏,我收到了舊的請求值。 我希望在調用ajax之後獲得新的請求和響應對象。

     var Check2Bool = <%=context.getAttribute("comeFromUploadTemp")%>; 
         var check2 = <%=request.getAttribute("comeFromUploadTemp")%>; 
         alert(Check2Bool + " " + check2); 

       }).fail(function() { 
        alert("error"); 
        $('#ldiv').hide(); 
       }); 

}); 

的Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     ServletContext context = getServletContext(); 

     /** 
     * Display XML file to the user 
     */ 
     TemplateVO template = null; 
     TemplateUtil util = new TemplateUtil(); 

     //Prepare XML file path 
     String path=(String) context.getAttribute(Constants.USER_DIR); 
     String strFilePath = null; 

     //Upload XML file 
     if(ServletFileUpload.isMultipartContent(request)){ 
      try{ 
       List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); 
       for(FileItem item : multiparts){ 
        if(!item.isFormField()){ 
         String name = new File(item.getName()).getName(); 
         request.setAttribute("FileName",name); 
         String path1 = path + File.separator + "data-in"; 
         strFilePath = FileUtil.createFileOnFileSystem(item,path1,name,"xml"); 
        } 
       } 
      }catch(Exception ex){ 
       ex.printStackTrace(); 
      } 

     } 

     //set variables into Request Object 
     template = util.readXML(strFilePath); 

     context.setAttribute("comeFromUploadTemp", true); 
     request.setAttribute("comeFromUploadTemp", true); 

     request.getRequestDispatcher("mappingObject.jsp").forward(request, response); 
    } 

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     doGet(request, response); 
    } 

回答

0

請求是JSP的工作區,notajax。 你應該通過響應i.o傳遞數據。請求。 喜歡:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    //... your code here 
    response.getOutputStream().write(data); 

} 

然後ü可以解析響應並根據需要獲取數據。

http://www.coderanch.com/t/522069/Servlets/java/Adding-Custom-Data-Response-Headers http://www.w3schools.com/ajax/ajax_xmlhttprequest_response.asp