2014-10-11 58 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