2016-02-29 66 views
0

我的JSP页面上有一个表单,它在提交时转到Java文件。执行特定步骤后,此Java文件将重定向到另一个JSP页面。重定向之前来自java文件的警报

在重定向之前,我想显示提交表单是否成功的提示。在其他JSP页面中,我使用了javascript alert()函数来执行此操作。我不能这样做,因为这是一个Java文件。

我试图使用JOptionPane,但警报框没有出现在浏览器页面上,它出现在我的桌面上(这很奇怪或应该是正常的..)。我试着用println,最后只打印出来给控制台。

因此,无论如何,我可以调用.java文件中的Javascript警报或其他方式显示警报? java文件中的所有内容都不会引起警报。

Java文件

private void alert(String msg){ 

     //this doesn't print to console, doesn't show alert 
     PrintWriter out = new PrintWriter(System.out); 
     out.println("<script type=\"text/javascript\">"); 
     out.println("alert(" + msg + ");"); 
     out.println("</script>"); 

     //This prints to console only 
     /*System.out.println("<script type=\"text/javascript\">"); 
     System.out.println("alert(" + msg + ");"); 
     System.out.println("</script>");*/ 
    } 

protected void doPost(HttpServletRequest request, 
          HttpServletResponse response) throws ServletException, IOException { 
     // gets values of text fields 
     String name = request.getParameter("name"); 

     InputStream inputStream = null; // input stream of the upload file 

     // obtains the upload file part in this multipart request 
     Part filePart = request.getPart("file"); 
     if (filePart != null) { 
      inputStream = filePart.getInputStream(); 
     } 

     Connection conn = null; // connection to the database 

     try { 
      // connects to the database 
      DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 
      conn = DriverManager.getConnection(dbURL, dbUser, dbPass); 

      // constructs SQL statement 
      String sql = "INSERT INTO table(name, image) values (?, ?)"; 
      PreparedStatement statement = conn.prepareStatement(sql); 
      statement.setString(1, name); 

      if (inputStream != null) { 
       statement.setBlob(2, inputStream); 
      } 

      // sends the statement to the database server 
      int row = statement.executeUpdate(); 
      if (row > 0) { 
       //This ends up appearing on my desktop instead of inside the browser. 
       //JOptionPane.showMessageDialog(null, "Input successful"); 

       //**THIS is the alert that doesn't show up** 
       alert("Input successful"); 

      } 
     } catch (SQLException ex) { 
      ex.printStackTrace(); 
     } finally { 
      if (conn != null) { 
       // closes the database connection 
       try { 
        conn.close(); 
       } catch (SQLException ex) { 
        ex.printStackTrace(); 
       } 
      } 
      response.sendRedirect("home.jsp"); 
     } 
    } 

回答

0

把HTML里面你的servlet真的东西,以避免。我个人会把它变成AJAX调用,或者至少首先重定向到“success.jsp”(或类似的东西),然后从那里重定向到“home.jsp”。这不是最好的用户体验,但您的设计颇具挑战性。

+0

在这种情况下不确定Ajax调用。我得到你的重定向的想法。猜猜如果我没有找到其他替代方案,我会保留这个作为我更糟的情况下计划:)。 – ksv99