如何避免使用新的HTML页面响应servlet



以下是我的servlet的get()和post()方法。我是servlet的新手。当我从客户端打电话时,此Servlet创建一个新页面,并覆盖我的客户端中的所有HTML元素。我想做的是,我只是留在我的HTML页面中,让Servlet独自完成他的工作。

public void doPost(HttpServletRequest request, 
               HttpServletResponse response)
              throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\temp"));
      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );
      try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);
      // Process the uploaded file items
      Iterator i = fileItems.iterator();
      while ( i.hasNext () ) 
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )  
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\") >= 0 ){
               file = new File( filePath + 
               fileName.substring( fileName.lastIndexOf("\"))) ;
            }else{
               file = new File( filePath + 
               fileName.substring(fileName.lastIndexOf("\")+1)) ;
            }
            fi.write( file ) ;
         }
      }
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {
        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   } 

我想做的是,我只是留在我的HTML页面中,让Servlet独自完成他的工作。

这是使用异步呼叫的理想候选者aka ajax。

学习ajax。

http://api.jquery.com/jquery.ajax/

如何使用servlet和ajax?

如果您想要servlet进行进程,并且应该显示HTML页面,则可以在Servlet的Try Block结束时使用RequestDispatcher。因此,当单击您的HTML页面上的任何操作时,它将o servlet并执行适当的操作,然后再次将其重定向到HTML。

RequestDispatcher rd = request.getRequestDispatcher("index.html");
            rd.include(request, response);

相关内容

  • 没有找到相关文章

最新更新